te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>need help in python algorithm, problem with variable? - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

need help in python algorithm, problem with variable? - Stack Overflow

programmeradmin3浏览0评论

i am trying to solve a python algorithm problem but having trouble i will explain the question below ( I couldn't copy it here)

Q : in a N*N array, each square consisting of random numbers, (every number is different)

You are at a random number, you need to move to a neighboring number that is smaller than you. You can only move in 4 directions(up, down, left, right). When you move, if there are more than one place you can move to, you should only move to the smallest number possible.

example: 19 57 74 73 94

26 27 32 98 61

40 88 49 38 25

21 66 53 95 46

80 23 58 39 89

if you start at 49, you move like this: 49 -> 32 -> 27 -> 26 -> 19, so you move 4 times.

Keep moving until you cannot move anymore. Return the maximal times you can move in each test case.

my code:

import sys
sys.stdin = open('input.txt', 'r')

T = int(input())
for test_case in range(1, T + 1):

    N = int(input())
    arr = [list(map(int, input().split())) for _ in range(N)]

    # directions
    di = [-1, 1, 0, 0]
    dj = [0, 0, -1, 1]

    # max move
    # max(count_list)

    count_list = []
    count = 0  # count every time you move
    for i in range(N):
        for j in range(N):
            for d in range(4):
                ni = i + di[d]
                nj = j + dj[d]
                small_list_arr = []  # smallest of arr[ni][nj] 
                if 0 <= ni < N and 0 <= nj < N:   # inside N*N
                    if arr[ni][nj] < arr[i][j]:  # if there is smaller neighboring num
                        small_list_arr.append(arr[ni][nj])
                        # if there are multiple smaller neighboring nums
                        if arr[ni][nj] == min(small_list_arr):
                            count += 1  # move count
                            ni, i = i, ni    # new i, j
                            nj, j = j, nj    
                            
            count_list.append(count)
    print(f'#{test_case} {max(count_list)}')

my problem is, I think I am okay with finding the new (i, j) (smallest neighboring number's location) but when I use the debugger I find that <for d in range(4)> does not start over from 0 again, for example if I found new (i, j) when d = 2, the debugger shows that when you go back up to <for d in range(4)> the d starts from 2. how do i solve this? maybe there is a problem with how i allocate ni, nj to i, j variables?

I tried break but didn't work, I am new to python so need help sorry for my english

i am trying to solve a python algorithm problem but having trouble i will explain the question below ( I couldn't copy it here)

Q : in a N*N array, each square consisting of random numbers, (every number is different)

You are at a random number, you need to move to a neighboring number that is smaller than you. You can only move in 4 directions(up, down, left, right). When you move, if there are more than one place you can move to, you should only move to the smallest number possible.

example: 19 57 74 73 94

26 27 32 98 61

40 88 49 38 25

21 66 53 95 46

80 23 58 39 89

if you start at 49, you move like this: 49 -> 32 -> 27 -> 26 -> 19, so you move 4 times.

Keep moving until you cannot move anymore. Return the maximal times you can move in each test case.

my code:

import sys
sys.stdin = open('input.txt', 'r')

T = int(input())
for test_case in range(1, T + 1):

    N = int(input())
    arr = [list(map(int, input().split())) for _ in range(N)]

    # directions
    di = [-1, 1, 0, 0]
    dj = [0, 0, -1, 1]

    # max move
    # max(count_list)

    count_list = []
    count = 0  # count every time you move
    for i in range(N):
        for j in range(N):
            for d in range(4):
                ni = i + di[d]
                nj = j + dj[d]
                small_list_arr = []  # smallest of arr[ni][nj] 
                if 0 <= ni < N and 0 <= nj < N:   # inside N*N
                    if arr[ni][nj] < arr[i][j]:  # if there is smaller neighboring num
                        small_list_arr.append(arr[ni][nj])
                        # if there are multiple smaller neighboring nums
                        if arr[ni][nj] == min(small_list_arr):
                            count += 1  # move count
                            ni, i = i, ni    # new i, j
                            nj, j = j, nj    
                            
            count_list.append(count)
    print(f'#{test_case} {max(count_list)}')

my problem is, I think I am okay with finding the new (i, j) (smallest neighboring number's location) but when I use the debugger I find that <for d in range(4)> does not start over from 0 again, for example if I found new (i, j) when d = 2, the debugger shows that when you go back up to <for d in range(4)> the d starts from 2. how do i solve this? maybe there is a problem with how i allocate ni, nj to i, j variables?

I tried break but didn't work, I am new to python so need help sorry for my english

Share Improve this question edited Feb 18 at 3:44 ccccc asked Feb 18 at 3:43 cccccccccc 11 bronze badge New contributor ccccc is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
Add a comment  | 

2 Answers 2

Reset to default 3

Unlike C, Python's for loop effectively assigns the iterated value every time. So your assignment on i, j in your code doesn’t affect the loop.

You may instead use a while loop to achieve the same effect as for loop in C.

I have generated a solution, based on a different approach,

arr = [
  [ 19, 57, 74, 73, 94 ],
  [ 26, 27, 32, 98, 61 ],
  [ 40, 88, 49, 38, 25 ],
  [ 21, 66, 53, 95, 46 ],
  [ 80, 23, 58, 39, 89 ]
]

initial = [ 2, 3 ]
steps = 0

  # returns the value contained in the matrix
def getValue( point ):
    return arr[ point[ 0 ] ][ point[ 1 ]]
  
  # if the row and column values are within the appropriate range and the value 
  # returned by **getValue()** is less than **value** it returns “true”, 
  # otherwise it returns “false”.
def evaluate( row, col, value ):
    if( row > -1 and row < len( arr )  and col > -1 and col < len( arr[ 0 ] ) ):
        if arr[ row ][ col ] < value:
            return True
    return False

  # calls "evaluate" four times, passing as parameters, the supposed neighbor 
  # cells of the current cell and "value", if any call returns true, it updates 
  # the value of "value" and "newPoint", finally returns "newPoint"
def getMinNeighbor( point, value ):
    newPoint = [ -1, -1 ]
    if evaluate( point[ 0 ] - 1, point[ 1 ], value ):
        newPoint = [ point[ 0 ] - 1, point[ 1 ] ]
        value = getValue( newPoint )
        print( f" ^ {value}" )

    if evaluate( point[ 0 ] , point[ 1 ] - 1, value ):
        newPoint = [ point[ 0 ], point[ 1 ] - 1 ]
        value = getValue( newPoint )
        print( f" < {value}" )

    if evaluate( point[ 0 ] + 1, point[ 1 ], value ):
        newPoint = [ point[ 0 ] + 1, point[ 1 ] ]
        value = getValue( newPoint )
        print( f" v {value}" )

    if evaluate( point[ 0 ], point[ 1 ] + 1, value ):
        newPoint = [ point[ 0 ], point[ 1 ] + 1 ]
        value = getValue( newPoint )
        print( f" > {value}" )
    return newPoint

  # this method calls “getMinNeighbor” assigning to “newPoint” the value returned 
  # by it, if it is a valid value, it increments “steps” and resorts to recursion, 
  # to reach the result, if it is not, it returns “steps”.
def explore( point ):
    global steps
    value = getValue( point )
    newPoint = getMinNeighbor( point, value )
    if newPoint != [ -1, -1 ]:
        steps += 1
        return explore( newPoint )
    else:
        return steps
        
print( explore( initial ))
发布评论

评论列表(0)

  1. 暂无评论