2017-06-06 141 views
0

有這個蟒蛇入門課程的最後一個任務。與編程第一次接觸麻煩,所以..蟒蛇遞歸函數 - 與輸出

準則困擾:

  1. 實現返回打擾(n)函數一個包含「麻煩」(字尾後跟空格)n次的字符串。如果n不是嚴格正整數,則函數應該返回一個空字符串。該功能必須使用遞歸來實現。
  2. 使用上述功能,實現返回包含的字母串的大象(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 

我該怎麼辦?

+0

使用可視化的Python的網站這是你第一次用遞歸函數,將使其更容易理解發生了什麼事情。 – Rosh

+0

我知道問題在哪裏..但我沒有修復它的工具。我使用pythontuthor.com。謝謝。 – fullone

+0

我看不出有任何理由在這裏使用遞歸函數....你爲什麼要做這樣的說法? – abccd

回答

0

試試這個:如果

def bother(n): 
    if n == 0: 
     return 'bother ' 
    elif n <= 0: 
     return '' 
    else: 
     return 'bother ' + bother(n - 1) 

def elephants(n, first=True): #first keeps track of which output per n 
    if n <= 0: 
     return '' 
    elif n == 1: 
     return "An elephant bothers a lot of people" 
    elif first: 
     return elephants(n, not first) \ 
     + str(n) + ' elephants ' + bother(n - 1) + 'a lot of people' 
    else: 
     return str(n) + ' elephants ' + bother(n - 1) + 'much more\n' 


print(elephants(1)) 
print(elephants(2)) 
print(elephants(3)) 
print(elephants(4)) 


""" 
This gives you the desired output. The main part of the elephants section if that it alternates between the two different returned strings: 
-a lot of people   (first=True) 
-much more    (first=False) 

When called recursively it flips the Boolean with not operator and returns the second string, then flips back for the next value of n to the first returned string 
""" 
+1

它沒有返回正確的答案..但我會嘗試使用這個布爾招解決它。謝謝! – fullone