• Python使用递归方法求阶乘
千次阅读
2020-08-19 17:24:44

# 递归求阶乘

求阶乘 1！+2！+3！+4！+5！+…+n！。

## 代码如下

def jiecheng(n): # 定义一个函数名是jiecheng,参数为n的函数
if n==1:     # 当参数n为1时，返回n的值
return n    # 结束函数，并返回一个值n给函数
n = n*jiecheng(n-1)   # 当不满足n==1时，进行递推，n!=n*(n-1)!
return n     # 结束函数，并返回一个值n给函数
m = jiecheng(5)  # 将函数中的参数n赋值为5，将函数值赋值给m
print(m)         # 打印出m的值


## 输出结果

120

更多相关内容
• I am having trouble implementing this in Python. I want to write a function with (sole) input n, that recursively generates a list of factorial values 1! ... n!So far I have thought of storing the rec...

I am having trouble implementing this in Python. I want to write a function with (sole) input n, that recursively generates a list of factorial values 1! ... n!

So far I have thought of storing the recursively derived values of n-factorial in a variable, and then adding (pushing?) them into a list. The question I have is how do I 'save' the list? I am not sure how to check if a list exists or not as well...

def recFactorial(n):

if n == 1:

return 1

print(l)

else:

l = []

f = n * recFactorial(n-1)

if l:

l = l.push(f)

else:

l = []

解决方案

Recursive function calls can't see the local variables of the other calls to the same function. If you want several calls to be able to work with the same list, the list needs to either be a parameter or a return value of the function (or I suppose a global variable, but that would be really bad design).

In this case, I think it would be easiest to pass the list as the return value of the function. It would be created in the base case, where you'd return the trivial list [1]. Each outer call would append a value to the list (and use the last value that was on it previously to do their calculation).

def recFactorialList(n):

if n == 1:

return [1] # base case, still returns a list

lst = recFactorialList(n-1)

n_fac = lst[-1] * n # use the last value to calculate a new value

lst.append(n_fac) # add n factorial to the end of the list

return lst # return the updated list

展开全文
• 递归函数两大特点：1.能够调用函数自身2.至少有一个出口（结束函数自身调用）函数实现：def calnum(num):if num != 1:# 递归调用自身函数csum = num * calnum(num - 1)else:# 设置递归出口csum =...一个程序中python...

递归函数两大特点：

1.能够调用函数自身

2.至少有一个出口（结束函数自身调用）

函数实现：

def calnum(num):

if num != 1:

# 递归调用自身函数

csum = num * calnum(num - 1)

else:

# 设置递归出口

csum = 1

return csum

ret = calnum(5)

print(ret)

递归函数的缺点：

占用资源多，一般不会优先选择。

一个程序中python默认只允许调用自身1024次，超过这个次数，

python解释器会认为该程序执行有错误而报错停止

报错信息：

RuntimeError: maximum recursion depth exceeded

当然python是支持自定义次数的：

import sys

# 设置允许的调用次数为2000

sys.setrecursionlimit(2000)

补充知识：python：编写一个求菲波那奇数列的递归函数，输入n值，使用该递归函数

题目：

编写一个求菲波那奇数列的递归函数，输入n值，使用该递归函数，输出如下图形。例如：当n=6时。

0

0 1 1

0 1 1 2 3

0 1 1 2 3 5 8

0 1 1 2 3 5 8 13 21

0 1 1 2 3 5 8 13 21 34 55

规律：

1.每行第一个数为0；

2.第n行数的个数为2n-1；

3.第n行第m列数为第n行中第m-1列和m-2列数之和；

代码：

def fei(i,j): #i为行数，j为列数

if i == 1 or j ==1:

return 0

elif j == 2 :

return 1

else:

return fei(i,j-1) + fei(i,j-2)

for i in range(1,7):

print()

for k in range(1,7-i): #控制空格数

print(" ",end="")

for j in range(1,(2*i)):

print(fei(i,j),"",end="")

运行结果：

以上这篇python递归函数求n的阶乘,优缺点及递归次数设置方式就是小编分享给大家的全部内容了，希望能给大家一个参考，也希望大家多多支持我们。

本文标题: python递归函数求n的阶乘,优缺点及递归次数设置方式

本文地址: http://www.cppcns.com/jiaoben/python/305477.html

展开全文
• I am having trouble implementing this in Python. I want to write a function with (sole) input n, that recursively generates a list of factorial values 1! ... n!So far I have thought of storing the rec...

I am having trouble implementing this in Python. I want to write a function with (sole) input n, that recursively generates a list of factorial values 1! ... n!

So far I have thought of storing the recursively derived values of n-factorial in a variable, and then adding (pushing?) them into a list. The question I have is how do I 'save' the list? I am not sure how to check if a list exists or not as well...

def recFactorial(n):

if n == 1:

return 1

print(l)

else:

l = []

f = n * recFactorial(n-1)

if l:

l = l.push(f)

else:

l = []

解决方案

Recursive function calls can't see the local variables of the other calls to the same function. If you want several calls to be able to work with the same list, the list needs to either be a parameter or a return value of the function (or I suppose a global variable, but that would be really bad design).

In this case, I think it would be easiest to pass the list as the return value of the function. It would be created in the base case, where you'd return the trivial list [1]. Each outer call would append a value to the list (and use the last value that was on it previously to do their calculation).

def recFactorialList(n):

if n == 1:

return [1] # base case, still returns a list

lst = recFactorialList(n-1)

n_fac = lst[-1] * n # use the last value to calculate a new value

lst.append(n_fac) # add n factorial to the end of the list

return lst # return the updated list

展开全文
• 本文实例讲述了python递归计算N！的方法。分享给大家供大家参考。具体实现方法如下： def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) 希望本文所述对大家的Python程序设计有所帮助...
• def fn(num,result=1): result *= num # if num == 1: # return result # else: # return fn(num-1,result) return result if num == 1 ...fn = lambda n:1 if n == 1 else n*fn(n-1) fn(4) 运行结果: 24
• Python入门程序 函数应用（判断素数、递归求n阶乘、x的n次方、最大最小值、插入排序） 1.判断素数 #编写函数，判断一个数是否是素数。 def isprime(n): if n==1: return False for i in range(2, n): if n ...
• python递归求阶乘的方法阶乘：例如 5! 指的是“5的阶乘”，即 5! = 1*2*3*4*5。“递归”就是对自身进行调用的函数。def f(x):if x == 0:return 0elif x == 1:return 1else:return (x * f(x-1))print(f(5))代码解释：...
• 本文内容介绍了python递归函数求n阶乘,优缺点及递归次数设置方式，具有很好的参考价值，希望对大家有所帮助。一起跟随小编过来看看吧！递归函数两大特点：1.能够调用函数自身2.至少有一个出口(结束函数自身调用)...
• ## python 利用递归方法求解n的阶乘和

万次阅读 多人点赞 2018-09-04 23:07:40
写程序算出n阶乘的和 def fn(x): if x==1: return 1 def f(x): if x==1: return 1 return f(x-1)*x return fn(x-1)+f(x) n = int(input("请输入值")) print(fn(n))...
• 不用多说，看完代码绝对明了，只是要提一句，递归函数会创造大量的函数对象，过量的消耗内存和运算能力。而我们也会用递归实现分析几何，画出漂亮的图案。
• 递归的实现是函数自己调用自己，每次调用函数都要压栈弹栈保存和恢复寄存器的栈操作，非常消耗空间的。
• 请帮助我理解我错在哪里：这是一个问题：创建一个称为递归析因的递归函数和一个称为迭代析因的迭代函数Accepts as parameter an Integer nComputes the factorial of nReturns the factorial of n这是我用来回答问题...
• 键盘输入一个数，用递归函数计算此数的阶乘。 代码如下： def func(count): if count == 1: return 1 else: return func(count-1)*count num = int(input("请输入一个数：")) print("%d的阶乘为%d"%(num,func...
• 给出一个数n,写一个函数myfac(n)来计算n!(n阶乘) def myfac(n): if n==1: return 1 else: return myfac(n-1)*n
• 程序调用自身的编程技巧称为递归（recursion）。递归做为一种算法在程序设计语言中广泛应用。一个过程或函数在其定义或说明中有直接或间接调用自身的一种方法，它通常把一个大型复杂的问题层层转化为一个与原问题...
• 举个例子，我们来计算阶乘 n! = 1 * 2 * 3 * ... * n，用函数 fact(n)表示，可以看出：fact(n) = n! = 1 * 2 * 3 * ... * (n-1) * n = (n-1)! * n = fact(n-1) * n所以，fact(n)可以表示为 n * fact(n...
• 自然数n阶乘写作n!。1808年，基斯顿·卡曼引进这个表示。 亦即n!=1×2×3×...×(n-1)×n阶乘亦可以递归方式定义：0!=1，n!=(n-1)!×n。 1. 递归方法 def fact(n): if n == 0: return 1 else
• def factorial(n): result = n for i in range(1,n): result *=i return result number = int(input('请输入一个正整数：')) result = factorial(number) print("%d 的阶乘是:%d"%(number,result))
• 求n阶乘是一个很简单的问题，循环操作和递归操作都能够实现。 '''求n阶乘''' #for循环写法 def func1(n): sum_n = 1 for i in range(1,n+1): sum_n *= i return sum_n #递归写法 def func2(n): if (n == 0...
• 迭代方法_求n阶乘 def factorial(n): result = n for i in range(1, n): result *= i return result number = int(input("请输入一个正整数：")) result1 = factorial(number) print("%d的阶乘为：%d" % ...
• def factorial(n): if n == 1: return 1 els e: return n * factorial(n-1) number = int(input('请输入一个正整数：')) result = factorial(number) print("%d的阶乘是：%d" % (number, result)) 注：pyt...
• 本文首发于微信公众号："算法与编程之美"，欢迎关注，及时了解更多此系列文章。1理解递归“程序设计是实践计算机思维的重要手段”。程序设计的三种特征就是封装、继承和多态。...递归算法在数学阶乘的...
• ## Python递归算法求n!

万次阅读 2018-02-28 12:02:12
def fact(n): if n == 1: return 1 result = n * fact(n - 1) return result print fact(5)Factorial : 阶乘
• n = int(input('请输入整数nn>=0）：')) def fact(n): if n == 0: sum1 = 1 else: sum1 = n * fact(n-1) return sum1 print(fact(n)) 我自认为我的代码没打错，它也能求阶乘，但导师还是说错了，大错特错，我很不...

...