欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

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

时间:2021-09-11 08:10:10|栏目: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.

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)

上一篇:python GUI库图形界面开发之PyQt5切换按钮控件QPushButton详细使用方法与实例

栏    目:Python代码

下一篇:浅谈python中的占位符

本文标题:Python 怎么定义计算N的阶乘的函数

本文地址:http://www.codeinn.net/misctech/174300.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有