2017-10-09 58 views
-1
def choose (x, y): 
    if y > x: 
     print ("False") 
    elif y == 0 or y == x: 
     return 1 
    elif y == 1: 
     return x 
    else: 
     if (x-y) > y: 
      biggest = x-y 
      smallest = y 
     else: 
      biggest = y 
      smallest = x-y 
     resultatet = x * choose (x-1, biggest) 
    res = resultatet // smallest 
    return res 

我的功能与任何X输入我插入但更大的Y输入像8000例如我越来越的两个数字蟒教师3

File "/home/nazel607/labb3b_2.py", line 20, in choose 
resultatet = x * choose (x-1, biggest) 
    File "/home/nazel607/labb3b_2.py", line 3, in choose 
if y > x: 
RuntimeError: maximum recursion depth exceeded in comparison 

完美的工作有没有一种方法可以让我克服这个问题还是因为Python的限制而无法实现?除了增加限制还有另一种方法吗?

+0

嗨。你有兴趣找到一种不同的方法来计算这个值吗?或者你想知道如何实现这个特定的算法,而不会遇到这种限制? – jwg

+0

@jwg嗨,我更感兴趣的是找到一种方法来使用这个特定的算法,并克服了限制的问题 –

+0

你见过[this](https://stackoverflow.com/questions/8177073/python-maximum-recursion -depth-超标)? – RolfBly

回答

2

似乎可以摆脱递归的:

def choose2(x, y): 
    if y > x: 
     raise ValueError() 

    if y == 0 or y == x: 
     return 1 

    if y == 1: 
     return x 

    result = 1 
    while y != x: 
     big, small = max(x-y, y), min(x-y, y) 
     result *= x // small 
     x -= 1 
     y = big 
    return result 

我已经在几个例子进行了测试

for x, y in [ 
    (4, 2), 
    (17, 9), 
    (125, 79), 
    (8005, 13), 
    (9005, 13), 
    # (19005, 7004) # exceeds max recursion depth on my machine 
]: 
    assert choose(x, y) == choose2(x, y) 

似乎工作正常。

-1

你是不是退出程序...

def choose (x, y): 
    if y > x: 
     print ("False") 
     return 
    # ...rest of your program 
+0

你是对的,但即使在编辑后我也得到完全相同的问题 –

+0

Python阻止你递归得太深。查看'https:// docs.python.org/3/library/sys.html#sys.setrecursionlimit'。 Python不会执行尾递归 – ssm