Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

3
3

Correct code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading