简体   繁体   中英

Why does this recursive program behave strangely

I'm writing a simple recursive function that takes a square matrix and the starting position coordinates and the value of the starting position, and then finds if there is a path to the bottom right corner of the square matrix. The rule is to start from the starting position Move right or down, when the value of the next position is less than or equal to the current value, you can move and update the value of the sum of the two, and so on. If it exists, return True and the path, if not, return False and [ ]. Below is the program I wrote

def find_path(matrix, x, y, value):
    length = len(matrix)

    if x == y == (length-1):
        return (True,[(x,y)])

    # Go down and search
    if x < length -1 and matrix[x+1][y] <= value:
        hasSolution,solution = find_path(matrix, x+1, y, value + matrix[x+1][y])
        if hasSolution:
            solution.append((x,y))
            return solution
    
    # If the road below is not feasible, take the right
    if y < length -1 and matrix[x][y+1] <= value:
        hasSolution,solution = find_path(matrix, x, y+1, value + matrix[x][y+1])
        if hasSolution:
            solution.append((x,y))
            return solution
    
    # If neither left nor right, it means there is no solution
    return (False,[])

However when I enter [[76,13],[40,42]], the python interpreter returns

File "/Users/zg/PycharmProjects/z/main.py", line 42, in find_path
     solution.append((x,y))
AttributeError: 'tuple' object has no attribute 'append'

Why does this result occur?

From the error it appears that solution is a tuple and tuples are immutable and don't have an append method, of course.

solution is defined outside of the code snippet you posted so it must be a global variable or in a wrapping function outside of find_path . If you want to append to it, a list would be the right data structure to use.

In addition, return (True,[(x,y)]) doesn't make much sense since x and y will always be length-1 when you find a valid path, so I would reconsider that part of the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM