脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python 怎么定义计算N的阶乘的函数

Python 怎么定义计算N的阶乘的函数

2021-09-19 00:26痴迷、淡然~ Python

这篇文章主要介绍了Python 怎么定义计算N的阶乘的函数,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

定义计算N的阶乘函数

1)使用循环计算阶乘

  1. def frac(n):
  2. r = 1
  3. if n<=1:
  4. if n==0 or n==1:
  5. return 1
  6. else:
  7. print('n 不能小于0')
  8. else:
  9. for i in range(1, n+1):
  10. r *= i
  11. return r
  12. print(frac(5))
  13. print(frac(6))
  14. print(frac(7))

120

720

5040

2)使用递归计算阶乘

  1. def frac(n):
  2. if n<=1:
  3. if n==0 or n==1:
  4. return 1
  5. else:
  6. print('n 不能小于0')
  7. else:
  8. return n * frac(n-1)
  9.  
  10. print(frac(5))
  11. print(frac(6))
  12. print(frac(7))

120

720

5040

3)调用reduce函数计算阶乘

说明:Python 在 functools 模块提供了 reduce() 函数,该函数使用指定函数对序列对象进行累计。

查看函数信息:

  1. import functools
  2. print(help(functools.reduce))
  1. Help on built-in function reduce in module _functools:
  2. reduce(...)
  3. reduce(function, sequence[, initial]) -> value
  4.  
  5. Apply a function of two arguments cumulatively to the items of a sequence,
  6. from left to right, so as to reduce the sequence to a single value.
  7. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
  8. ((((1+2)+3)+4)+5). If initial is present, it is placed before the items
  9. of the sequence in the calculation, and serves as a default when the
  10. sequence is empty.

Python 怎么定义计算N的阶乘的函数

  1. import functools
  2. def fn(x, y):
  3. return x*y
  4. def frac(n):
  5. if n<=1:
  6. if n==0 or n==1:
  7. return 1
  8. else:
  9. print('n 不能小于0')
  10. else:
  11. return functools.reduce(fn, range(1, n+1))
  12.  
  13. print(frac(5))
  14. print(frac(6))
  15. print(frac(7))

120

720

5040

  1. # 使用 lambda 简写
  2. import functools
  3. def frac(n):
  4. if n<=1:
  5. if n==0 or n==1:
  6. return 1
  7. else:
  8. print('n 不能小于0')
  9. else:
  10. return functools.reduce(lambda x, y: x*y, range(1, n+1))
  11.  
  12. print(frac(5))
  13. print(frac(6))
  14. print(frac(7))

120

720

5040

补充:python求n的阶乘并输出_python求n的阶乘

阶乘是基斯顿·卡曼(Christian Kramp,1760~1826)于1808年发明的运算符号,是数学术语。

一个正整数的阶乘(factorial)是所有小于及等于该数的正整数的积,并且0的阶乘为1。自然数n的阶乘写作n!。

下面我们来看一下使用Python计算n的阶乘的方法:

第一种:利用functools工具处理import functools

  1. result = (lambda k: functools.reduce(int.__mul__, range(1, k + 1), 1))(5)
  2. print(result)```

第二种:普通的循环x = 1

  1. y = int(input("请输入要计算的数:"))
  2. for i in range(1, y + 1):
  3. x = x * i
  4. print(x)

第三种:利用递归的方式def func(n):

  1. if n == 0 or n == 1:
  2. return 1
  3. else:
  4. return (n * func(n - 1))
  5. a = func(5)
  6. print(a)

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。如有错误或未考虑完全的地方,望不吝赐教。

原文链接:https://blog.csdn.net/qq_36512295/article/details/94209873

延伸 · 阅读

精彩推荐