首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python编程错误RecursionError:比较中超出了最大递归深度

python编程错误RecursionError:比较中超出了最大递归深度
EN

Stack Overflow用户
提问于 2019-12-07 16:29:25
回答 3查看 157关注 0票数 0

这是我的python程序,也是练习6.4的答案。

代码语言:javascript
复制
#!/usr/bin/env python3

"""
Exercise 6.4.
A number, a, is a power of b if it is divisible by b and a/b is a power of b.
Write a function called is_power that takes parameters a and b and returns
True if a is a power of b.
Note: you will have to think about the base case.
"""

def is_power(a, b):
    """Checks if a is power of b."""
    if a == b:
        return True
    elif a%b == 0:
        return is_power(a/b, b)
    else:
        return False

print("is_power(10, 2) returns: ", is_power(10, 2))
print("is_power(27, 3) returns: ", is_power(27, 3))
print("is_power(1, 1)  returns: ",  is_power(1, 1))
print("is_power(10, 1) returns: ", is_power(10, 1))
print("is_power(3, 3)  returns: ",  is_power(3, 3))

每当我一次又一次地尝试显示这个错误时,我都会得到这个错误。请给我指点一下我的程序哪里出了错。

代码语言:javascript
复制
is_power(10, 2) returns:  False
is_power(27, 3) returns:  True
is_power(1, 1)  returns:  True
Traceback (most recent call last):
  File "C:\Users\Aaban Shakeel\Desktop\Think-Python-2e---my-solutions-master\ex6\ex6.4.py", line 23, in <module>
    print("is_power(10, 1) returns: ", is_power(10, 1))
  File "C:\Users\Aaban Shakeel\Desktop\Think-Python-2e---my-solutions-master\ex6\ex6.4.py", line 16, in is_power
    return is_power(a/b, b)
  File "C:\Users\Aaban Shakeel\Desktop\Think-Python-2e---my-solutions-master\ex6\ex6.4.py", line 16, in is_power
    return is_power(a/b, b)
  File "C:\Users\Aaban Shakeel\Desktop\Think-Python-2e---my-solutions-master\ex6\ex6.4.py", line 16, in is_power
    return is_power(a/b, b)
  [Previous line repeated 1021 more times]
  File "C:\Users\Aaban Shakeel\Desktop\Think-Python-2e---my-solutions-master\ex6\ex6.4.py", line 13, in is_power
    if a == b:
RecursionError: maximum recursion depth exceeded in comparison
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-12-07 16:35:36

似乎迭代地重写算法比使用递归更好。这是因为尾递归在python中效率不高。更多信息:https://stackoverflow.com/a/3323013/5746085

票数 0
EN

Stack Overflow用户

发布于 2019-12-07 16:33:15

这是因为对于b=1,您的递归将永远不会结束-我会补充:

代码语言:javascript
复制
def is_power(a, b):
    """Checks if a is power of b."""
    if a == b:
        return True
    elif b==1:
        return False
    elif a%b == 0:
        return is_power(a/b, b)
    else:
        return False
票数 0
EN

Stack Overflow用户

发布于 2019-12-07 16:34:13

您必须为数字1添加额外的检查,因为您的算法在此行中停滞(参数'a‘停止更改)

代码语言:javascript
复制
is_power(a / b, b)

如果b ==为1,则永远调用相同的函数(实际上直到达到最大递归深度:P )

代码语言:javascript
复制
is_power(10 / 1, 1)
is_power(10 / 1, 1)
...

递归限制可以防止堆栈溢出。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59224276

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档