递归堆栈误导输出

时间:2019-10-14 18:11:50

标签: python recursion

我在递归上有些困惑。我不了解打印效果如何

def gcd(a, b):
    # Everything divides 0
    print (a, b)
    if (b == 0):
        print ("I am here")
        return a
    return gcd(b, a % b)


# Driver program to test above function
a = 13
b = 24
if (gcd(a, b)):
    print('GCD of', a, 'and', b, 'is', gcd(a, b))
else:
    print('not found')

13 24

24 13

13 11

11 2

2 1

1 0

我在这里

13 24#-----需要从这里知道打印的工作方式,13和24的工作方式吗?此时堆栈如何保持13、24?

24 13

13 11

11 2

2 1

1 0

我在这里

13和24的GCD为1

1 个答案:

答案 0 :(得分:1)

您再次打印的问题是导致您两次调用了该函数。

def gcd(a, b):
    # Everything divides 0
    print ("input received is", a, b)
    if (b == 0):
        print ("I am here")
        return a
    return gcd(b, a % b)


# Driver program to test above function
a = 13
b = 24
if (gcd(a, b)):        #<------you call the function here and it does all the prints
    print('GCD of', a, 'and', b, 'is', gcd(a, b)) #<----then you call it again here so prints again
else:
    print('not found')

只需调用一次函数并捕获返回值

def gcd(a, b):
    # Everything divides 0
    print ("input received is", a, b)
    if (b == 0):
        print ("I am here")
        return a
    return gcd(b, a % b)


# Driver program to test above function
a = 13
b = 24
result = gcd(a, b)   #<-----call the function once and store the result
if (result):
    print('GCD of', a, 'and', b, 'is', result) #<---print the result
else:
    print('not found')