递归解决基本乘法

问题描述 投票:1回答:3

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

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

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

python recursion jython multiplication
3个回答
4
投票

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

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

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

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


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

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

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

Mul(3,3)
>>>9
© www.soinside.com 2019 - 2024. All rights reserved.