0
有這個蟒蛇入門課程的最後一個任務。與編程第一次接觸麻煩,所以..蟒蛇遞歸函數 - 與輸出
準則困擾:
- 實現返回打擾(n)函數一個包含「麻煩」(字尾後跟空格)n次的字符串。如果n不是嚴格正整數,則函數應該返回一個空字符串。該功能必須使用遞歸來實現。
- 使用上述功能,實現返回包含的字母串的大象(n)函數的「大象困擾了很多人......」從1到n的大象。如果n不大於1,則函數應該返回一個空字符串。該功能還必須使用遞歸來實現。
所以,我想:
def bother(n):
if n <= 0:
return ''
elif n == 1:
return 'bother '
else:
return 'bother ' + bother(n - 1)
def elephants(n):
if n <= 0: return ''
if n == 1: return 'An elephant bothers a lot of people...\r\n'
return elephants(n - 1) \
+ str(n) + ' elephants ' + bother(n) + 'much more\r\n' \
+ str(n) + ' elephants ' + bother(n) + 'a lot of people\r\n'
但調用大象(2)應返回:
An elephant bothers a lot of people...
2 elephants bother much more
,並呼籲大象(4)應該返回:
An elephant bothers a lot of people...
2 elephants bother bother much more
2 elephants bother bother a lot of people
3 elephants bother bother bother much more
3 elephants bother bother bother a lot of people
4 elephants bother bother bother bother much more
我該怎麼辦?
使用可視化的Python的網站這是你第一次用遞歸函數,將使其更容易理解發生了什麼事情。 – Rosh
我知道問題在哪裏..但我沒有修復它的工具。我使用pythontuthor.com。謝謝。 – fullone
我看不出有任何理由在這裏使用遞歸函數....你爲什麼要做這樣的說法? – abccd