简体   繁体   English

全局变量在递归 Function Python 中给出不同的结果

[英]Global variable gives different results in Recursive Function Python

Wrong Code:错误代码:

def play(b, n):
    global k
    if k == len(b):
        return n
    elif k in range(0, len(b)):
        if b[k][n] == 'a':
            k = k + 1
            return play(b, n + 1)
        elif b[k][n] == 'b':
            k = k + 1
            return play(b, n - 1)
        elif b[k][n] == 'c':
            k = k + 1
            return play(b, n)


b = ['ababc', 'cabab', 'ccabc', 'cabab', 'abcab']
k = 0
print(play(b, 0))  # Print 3
print(play(b, 3))  # Print 2

# The starting position is b[0][n]
# Return the resulting lane number of the game

Wrong Output:错误的 Output:

3
3

Correct code:正确代码:

def play(b, n, k):
    if k == len(b):
        return n
    elif k in range(0, len(b)):
        if b[k][n] == 'a':
            return play(b, n + 1, k + 1)
        elif b[k][n] == 'b':
            return play(b, n - 1, k + 1)
        elif b[k][n] == 'c':
            return play(b, n, k + 1)


b = ['ababc', 'cabab', 'ccabc', 'cabab', 'abcab']
print(play(b, 0, 0))  # Print 3
print(play(b, 3, 0))  # Print 2

# The starting position is b[0][n]
# Return the resulting lane number of the game

Correct Output:正确的 Output:

3
2

Hey guys.大家好。 I am coding a ghost leg function for Python by implementing a recursive function.我正在通过实现递归 function 为 Python 编写鬼腿 function。

There are two versions of the function. function 有两个版本。 Why does the version with global k give the wrong results?为什么global k的版本会给出错误的结果?

In the first version of the code, before play(b, 0) is called, k is 0 .在代码的第一个版本中,在调用play(b, 0)之前, k0 After that, k is no longer 0 , because it was modified inside play .之后, k不再是0 ,因为它在play内部被修改了。 But when play(b, 3) is called, it requires k to be 0 in order to give a correct result.但是当调用play(b, 3)时,它要求k0才能给出正确的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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