微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

定义计算N的阶乘的函数

1)使用循环计算阶乘

def frac(n): r = 1 if n

120

720

5040

2)使用递归计算阶乘

def frac(n): if n

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

120

720

5040

# 使用 lambda 简写 import functools def frac(n): if n

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)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐