Mal*_*gbo 2 python recursion jython multiplication
我应该编写一个函数来查找给定数量的狗需要的鞋子数量。它可以很容易地用乘法来完成,但我们需要使用递归,所以我有
def dogShoes(n):
total = 0
if n>0:
shoes = n + dogShoes(n)
total = total + 1
if total == 4:
return shoes
Run Code Online (Sandbox Code Playgroud)
但我现在意识到第 4 行将走向无穷大,而我认为会阻止它的底部甚至不会实现。有没有办法说 when totalis 4,停止并返回答案而不shoes走向无穷大?
您可以大大简化您的功能:
def dogShoes(n):
if n == 0:
return 0
else:
return 4 + dogShoes(n-1)
Run Code Online (Sandbox Code Playgroud)
由于您必须使用递归而不是仅返回,n * 4您可以简单地将乘法重写为加法(递归)。
好奇怪的任务啊……