我在这里有这个尾递归函数:
def recursiveFunction(n, sum):
if n < 1:
return sum
else:
return recursiveFunction(n-1, sum+n)
c = 998
print(recursiveFunction(c, 0))
Run Code Online (Sandbox Code Playgroud)
它可以工作到n = 997,然后它就会中断并吐出"比较时超出的最大递归深度" RuntimeError.这只是一个堆栈溢出?有办法解决它吗?
我试图找到一个最大的立方根,它是一个整数,小于12,000.
processing = True
n = 12000
while processing:
n -= 1
if n ** (1/3) == #checks to see if this has decimals or not
Run Code Online (Sandbox Code Playgroud)
我不知道怎么检查它是否是一个整数但是!我可以将它转换为字符串然后使用索引来检查结束值并查看它们是否为零,但这似乎相当麻烦.有更简单的方法吗?
假设我们要计算一些斐波那契数,以 997 为模。
因为n=500在 C++ 中我们可以运行
#include <iostream>
#include <array>
std::array<int, 2> fib(unsigned n) {
if (!n)
return {1, 1};
auto x = fib(n - 1);
return {(x[0] + x[1]) % 997, (x[0] + 2 * x[1]) % 997};
}
int main() {
std::cout << fib(500)[0];
}
Run Code Online (Sandbox Code Playgroud)
在 Python 中
def fib(n):
if n==1:
return (1, 2)
x=fib(n-1)
return ((x[0]+x[1]) % 997, (x[0]+2*x[1]) % 997)
if __name__=='__main__':
print(fib(500)[0])
Run Code Online (Sandbox Code Playgroud)
两者都可以毫无问题地找到答案 996。我们采用模数来保持合理的输出大小,并使用对来避免指数分支。
对于n=5000,C++ 代码输出 783,但 Python 会抱怨
RecursionError: …Run Code Online (Sandbox Code Playgroud) 似乎没有用于计算阶乘的 PyTorch 函数。PyTorch 有没有办法做到这一点?我希望在 Torch 中手动计算泊松分布(我知道存在这种分布:https: //pytorch.org/docs/stable/ generated /torch.poisson.html),并且该公式需要分母中的阶乘。
泊松分布: https: //en.wikipedia.org/wiki/Poisson_distribution
可能重复:
Python中的因子函数
我需要在python中编写一个返回N!的程序,而不使用factorial函数.我有一个程序到目前为止,但我一直收到错误说,local variable "fact" is assigned but never used.fact = 1分配后如何使用?
from pylab import *
def factorial(n):
fact = 1
for i in range(n):
print("i = ", i)
fact = fact * i
print("The factorial of " + str(n) + " is: " + str(fact))
Run Code Online (Sandbox Code Playgroud)