1 回答

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個(gè)贊
看起來這個(gè)函數(shù)正在返回不超過某個(gè)值的連續(xù)數(shù)字的總和。在查看代碼并嘗試?yán)斫馑?,您需要分解問題:
讓我們?nèi)∫恍┳兞縮umUpTo6 = 6 + 5 + 4 .... 0,它是最多 6 的數(shù)字的總和。然后讓我們?nèi)×硪粋€(gè)變量sumUpTo7 = 7 + 6 + 5 + 4 ... 0,它是最多 7 的數(shù)字的總和。現(xiàn)在注意,我可以重寫sumUpTo7為sumUpTo7 = 7 + sumUpTo6
現(xiàn)在,如果我們用對(duì)您的函數(shù)的調(diào)用替換這些變量:
如果recursion(6)給我最多 6 個(gè)數(shù)字的總和,
然后recursion(7) = 7 + recursion(6)
更一般地說,recursion(number) = number + recursion(number-1)
但是當(dāng)我們到達(dá)時(shí)recursion(0)呢?好吧,這稱為基本情況,我們想要recursion(0) = 0(因?yàn)?0 以內(nèi)的數(shù)字之和為 0)。
所以現(xiàn)在讓我們把這一切都寫成代碼:
def recursion(number): # `number` here is the number we want to add up to
if (number > 0): # if `number` is greater than 0, we can use the number below it to get the answer
result = number + recursion(number-1) # we use the logic above
print(result) # show the result on the command line
else: # if `number` is not greater than 0, then it must be less than or equal to 0
result = 0 # in this case the sum up to number will be 0
return result # pass the result up to the caller
對(duì) 的調(diào)用recursion(6)將運(yùn)行如下所示:
我們稱之為
recursion(6)
6 大于 0。所以我們調(diào)用
recursion(6-1)
which isrecursion(5)
并將其加 6。我們還沒有打印任何東西,因?yàn)槲覀冋诘却?code>recursion(5)完成。5 大于 0。所以我們稱
recursion(4)
。還沒有打印出來。4 大于 0。所以我們稱
recursion(3)
。還沒有打印出來。3 大于 0。所以我們稱
recursion(2)
。還沒有打印出來。2 大于 0。所以我們稱
recursion(1)
。還沒有打印出來。1 大于 0。所以我們稱
recursion(0)
。還沒有打印出來。0 不大于 0,所以我們返回 0。我們這里不打印任何東西
所以對(duì)于遞歸
recursion(1)
我們得到1 + 0
(從前一行)所以我們打印 1 并返回 1因?yàn)?code>recursion(2)我們得到了
2 + 1
(從上一行)所以我們打印并返回 3因?yàn)?code>recursion(3)我們得到
3 + 3
所以我們打印并返回 6因?yàn)?code>recursion(4)我們得到
4 + 6
所以我們打印并返回 10因?yàn)?code>recursion(5)我們得到
5 + 10
所以我們打印并返回 15
......你明白了
我在下面的代碼中添加了一些打印語(yǔ)句,以便于理解:
用不同的數(shù)字運(yùn)行這個(gè)......
def recursion(number):
if(number > 0):
print("{} is greater than 0".format(number))
print("Calling recursion({}-1)\n".format(number))
previous_result = recursion(number - 1)
print("recursion({}-1) gave {}".format(number, previous_result))
result = number + previous_result
print("returning {} + {} = {}\n".format(number, previous_result, result))
else:
print("Hit 0! Returning 0\n")
result = 0
return result
print("\n\nRecursion Example Results\n\n")
recursion(6)
添加回答
舉報(bào)