Global variable gives different results in Recursive Function Python

Question:

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:

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:

3
2

Hey guys. I am coding a ghost leg function for Python by implementing a recursive function.

There are two versions of the function. Why does the version with global k give the wrong results?

Asked By: Cyrus

||

Answers:

In the first version of the code, before play(b, 0) is called, k is 0. After that, k is no longer 0, because it was modified inside play. But when play(b, 3) is called, it requires k to be 0 in order to give a correct result.

Answered By: mkrieger1
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.