递归解决基本乘法

时间:2016-11-14 20:45:08

标签: python recursion jython multiplication

我应该写一个功能,找出一定数量的狗需要的鞋子数量。它可以通过乘法轻松完成,但我们需要使用递归,所以我有

def dogShoes(n):
    total = 0
    if n>0:
        shoes =   n + dogShoes(n)
        total = total + 1
        if total == 4:
            return shoes

但我现在意识到,第4行将走向无限,而我将会停止它的底部甚至无法实现。有没有办法说total 4时,如果没有shoes走向无限,请停止并返回答案?

3 个答案:

答案 0 :(得分:4)

您可以大量简化您的功能:

def dogShoes(n):
    if n == 0:
        return 0
    else:
        return 4 + dogShoes(n-1)

由于你必须使用递归而不是只返回n * 4,你可以简单地将乘法重写为加法(递归)。

多么奇怪的任务......

答案 1 :(得分:2)

您以递归方式调用函数,但从不更改参数,从而提供无限递归。尝试:

>>> def dog_shoes(n):
...   if n > 0:
...     return 4 + dog_shoes(n-1)
...   else:
...     return 0
...
>>> dog_shoes(1)
4
>>> dog_shoes(2)
8
>>> dog_shoes(3)
12

答案 2 :(得分:0)

def Mul(n, x):
if n==1:
    return x
else:
    return x+ Mul(n-1,x)

这是一个使用Python递归的简单乘法函数,使用两个参数。

Mul(3,3)
>>>9
相关问题