网络编程
位置:首页>> 网络编程>> Python编程>> Python 怎么定义计算N的阶乘的函数

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

作者:痴迷、淡然~  发布时间:2021-04-12 01:44:04 

标签:Python,阶乘,函数

定义计算N的阶乘的函数

1)使用循环计算阶乘


def frac(n):
 r = 1
 if n<=1:
   if n==0 or n==1:
     return 1
   else:
     print('n 不能小于0')
 else:
   for i in range(1, n+1):
     r *= i
   return r
print(frac(5))  
print(frac(6))
print(frac(7))

120

720

5040

2)使用递归计算阶乘


def frac(n):
 if n<=1:
   if n==0 or n==1:
     return 1
   else:
     print('n 不能小于0')
 else:
   return n * frac(n-1)

print(frac(5))
print(frac(6))
print(frac(7))

120

720

5040

3)调用reduce函数计算阶乘

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

查看函数信息:


import functools
print(help(functools.reduce))

Help on built-in function reduce in module _functools:
reduce(...)
 reduce(function, sequence[, initial]) -> value

Apply a function of two arguments cumulatively to the items of a sequence,
 from left to right, so as to reduce the sequence to a single value.
 For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
 ((((1+2)+3)+4)+5). If initial is present, it is placed before the items
 of the sequence in the calculation, and serves as a default when the
 sequence is empty.

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


import functools
def fn(x, y):
 return x*y
def frac(n):
 if n<=1:
   if n==0 or n==1:
     return 1
   else:
     print('n 不能小于0')
 else:
   return functools.reduce(fn, range(1, n+1))

print(frac(5))
print(frac(6))
print(frac(7))

120

720

5040


# 使用 lambda 简写
import functools
def frac(n):
 if n<=1:
   if n==0 or n==1:
     return 1
   else:
     print('n 不能小于0')
 else:
   return functools.reduce(lambda x, y: x*y, range(1, n+1))

print(frac(5))
print(frac(6))
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


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

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


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

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


if n == 0 or n == 1:
return 1
else:
return (n * func(n - 1))
a = func(5)
print(a)

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

来源:https://blog.csdn.net/qq_36512295/article/details/94209873

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com