【问题标题】:Python implementation not working for same logic in c++Python实现不适用于c ++中的相同逻辑
【发布时间】:2019-04-20 20:25:06
【问题描述】:

我正在寻找一个问题的解决方案,我已经在 c++ 中找到了解决方案,但是当我在 python 中尝试相同的逻辑时,它给出了RecursionError: maximum recursion depth exceeded in comparison

x=2
y=500

#Python Implementation

def F(x,y):
    if(x==0):
        return (y+1)%1000
    if(x>0 and y==0):
        return F(x - 1, 1)%1000
    else:
        return F(x - 1, F(x, y - 1))

print(str(F(x,y)))


#C++ Implementation

int f(int x,int y)
{
if(x==0)
    return (y+1)%1000;
if(x>0&&y==0)
    return f(x-1,1)%1000;
else
    return f(x-1,f(x,y-1));
}

int main()
{
 int x,y;
 scanf("%d%d",&x,&y);
 printf ("%03d", f(x,y));
 return 0;
}

提前致谢。

【问题讨论】:

  • 在不相关的注释中,“C++”代码中没有任何特定于 C++ 的内容,它可能是一个普通的 C 程序。在更相关的说明中,这两个程序并不完全相同:函数中的条件不一样(elifelse)。
  • 更新请检查

标签: c++ python-3.x recursion


【解决方案1】:

这类似于堆栈溢出预防。那是因为 python 没有特别针对尾递归进行优化。

您可以更改该限制,但不建议这样做(使用 sys.setrecursionlimit() )。如果您要更改它,解释器设置的默认值为 1000。

【讨论】:

    【解决方案2】:
    import resource, sys
    resource.setrlimit(resource.RLIMIT_STACK, (2**29,-1))
    sys.setrecursionlimit(10**6)
    

    这样就可以了。但是,如果可以,请尝试使用记忆来减少递归调用。如果您确实需要通过递归来执行此操作,请使用上面的代码并将其附加到 python 代码中。它会增加python的递归限制,我认为是997。

    来源:Setting stacksize in a python script

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

    【讨论】:

      猜你喜欢
      • 2017-11-22
      • 2015-05-27
      • 1970-01-01
      • 1970-01-01
      • 2019-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多