0

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?

2
  • Is your question why the first version is wrong? Commented Sep 10, 2022 at 19:26
  • 2
    Just a best practice thing - you shouldn't use global variables if you don't have to Commented Sep 10, 2022 at 19:28

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.