比较中超过了最大递归深度 [英] maximum recursion depth exceeded in comparison

查看:84
本文介绍了比较中超过了最大递归深度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了这段代码来计算组合数量:

I wrote this piece of code to compute the number of combinations:

def fact(n):
    return 1 if(n == 1) else n * fact(n - 1)

def combinations(n,k):
    return fact(n)/((fact(n - k) * fact(k)))

while(True):
    print(combinations(int(input()), int(input())))

阶乘函数似乎可以正常工作。但是,当我尝试找到两个数字的组合时,为什么在比较错误中却给了我最大的递归深度?阶乘函数有什么问题,因为错误似乎出自此?

The factorial function seems to work fine. But why does it give me a maximum recursion depth exceeded in comparison error when I try to find the combinations of two numbers? Is there something wrong with the factorial function, since that's where the error seems to be originating from?

这是我得到的错误:


builtins.RuntimeError:比较中超出了最大递归深度

builtins.RuntimeError: maximum recursion depth exceeded in comparison


推荐答案

尝试替换:

def fact(n):
    return 1 if(n == 1) else n * fact(n - 1)

到:

def fact(n):
    return 1 if(n <= 1) else n * fact(n - 1)

因为如果传递2个相同的数字,您将尝试计算 fact(0)(将调用 fact(-1) fact(-2)等,直到最大递归深度错误)。

Because if you pass 2 identical numbers, you would try to compute fact(0) (which would call fact(-1) and fact(-2), etc until the maximum recursion depth error).

这篇关于比较中超过了最大递归深度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆