跟蹤遞迴呼叫(Recursion)
阿新 • • 發佈:2018-12-23
以前直接看演算法時看不懂遞迴,每次都是一行一行用print函式來研究遞迴呼叫的順序,真是太蠢太費時間了。
在遞迴函式里加入margin,每次遞迴改變一下margin再打印出來,方便實用多了!
以下程式碼摘自《資料結構:Python語言描述》P18
def ourSum(lower, upper, margin = 0):
'''Returns the sum of the numbers from lower to upper,
and outputs a trace of the arguments and return values
on each call.'''
blanks = ' ' * margin
print(blanks, lower, upper)
if lower > upper:
print(blanks, 0)
return 0
else:
result = lower + ourSum(lower+1, upper, margin+4)
print(blanks, result)
return result
if __name__ == '__main__':
ourSum(1, 4)
#執行結果
1 4
2 4
3 4
4 4
5 4 #先進入遞迴,不斷完成(print)外層程式碼
0
4 #後回溯,完成遞迴層程式碼(result = lower + )
7
9
10
注意:第11行的return 0不能去掉,否則TypeError: unsupported operand type(s) for +: ‘int’ and ‘NoneType’
以下是對採用遞迴方法的階乘進行跟蹤:
def factorial (n, margin = 0):
'''Returns the factorial of n'''
blanks = ' ' * margin
print blanks, n
if n == 1: return 1
else:
result = n * factorial(n-1, margin+4)
print blanks, result
return result
print factorial(5)
#執行結果:
5
4
3
2
1
2
6
24
120
120