python递归函数-输出问题
在python入门课程的最后一个作业中遇到问题。。第一次接触编程,所以 准则:python递归函数-输出问题,python,python-3.x,recursion,Python,Python 3.x,Recursion,在python入门课程的最后一个作业中遇到问题。。第一次接触编程,所以 准则: 实现hord(n)函数,该函数返回包含“hord”(单词后跟空格)的字符串n次。如果n不是严格的正整数,则函数应返回空字符串。此函数必须使用递归实现 使用上述函数,实现大象(n)函数,该函数返回一个字符串,其中包含从1到n只大象的字母“大象打扰了很多人…”。如果n不大于1,则函数应返回空字符串。此函数还必须使用递归实现 所以,我试着: def bother(n): if n <= 0:
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'
召唤大象(4)应返回:
An elephant bothers a lot of people...
2 elephants bother much more
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
我该怎么做?试试这个:
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
"""
def(n):
如果n==0:
返回“麻烦”
如果您是第一次使用递归函数,请使用Visualize Python网站,这将使您更容易理解正在发生的事情。我知道问题出在哪里。。但是我没有工具来修复它。我确实使用pythontuthor.com。谢谢。我看不出有什么理由在这里使用递归函数。。。。你为什么要那样做?这是一项任务。。我不能做任何我想做的事。它没有返回正确的答案。。但我会尝试用这个布尔技巧来修复它。谢谢!