python - 递归解决基本乘法

标签 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 行将走向无穷大,而我认为会停止它的底部甚至不会实现。有没有办法说当 total4 时,停止并返回答案而不让 shoes 趋向于无穷大?

最佳答案

你可以大大简化你的函数:

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

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

多么奇怪的任务...

关于python - 递归解决基本乘法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40597530/

相关文章:

python - 如何在Python中仅在需要时才进行解码

python - 通过 pd.TimeGrouper ('D' 按天聚合每小时时间序列;问题@时间戳00 :00:00 (hour 24)

c++ - 递归中 void 的无效操作数

java - 将数据从 java 传递到 python 并返回 jython

java - 泛型与类<?>

python - pretty-print json,但将内部数组保留在一行python

python - Flask 不会在 POST 方法上重定向

javascript - 递归 JavaScript 方法范围

scala - 为什么这个不可变的双向链表实现会溢出堆栈

python - 在 Jython 中使用 PyCrypto 导入问题