【问题标题】:Python: writing function mult(a,b) for a*b with only add/sub/neg, recursion error for testing (-a,b)Python:为 a*b 编写函数 mult(a,b),只有 add/sub/neg,用于测试的递归错误 (-a,b)
【发布时间】:2016-09-11 22:04:00
【问题描述】:

到目前为止,我有这个 - 但如果我使用 (-a, b) 进行测试,python 会给我一个递归错误。请帮忙,不知道为什么这不起作用。所有其他测试都在这里工作。

def mult(a, b):
""" mult returns the product of two inputs
    inputs: n and m are integers
    output: result of multiplying n and m
""" 
    if b < 0:
       return -mult(a,-b)
    elif b == 0:
       return 0
    elif b == 1:
       return a
    else:
       return a + mult(a,b-1)

谢谢。

【问题讨论】:

  • 请显示错误的完整回溯。此外,您显示的代码的缩进是错误的,因此您应该会收到语法错误。最后,b == 1 的检查是无关的,不需要:b 将在下一个递归步骤中变为零。
  • 此代码在更正缩进后对我有用。请显示函数失败的值。

标签: python function python-3.x recursion multiplication


【解决方案1】:

Python 对递归数有限制。你可能只是在碰它。请参阅以下答案:

What is the maximum recursion depth in Python, and how to increase it?

【讨论】:

  • 是的,通常在 1000 左右。您的输入是什么?
猜你喜欢
  • 1970-01-01
  • 2014-03-29
  • 2010-12-08
  • 1970-01-01
  • 2021-10-06
  • 2017-04-06
  • 2021-11-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多