Python 怎么定義計(jì)算N的階乘的函數(shù)
定義計(jì)算N的階乘的函數(shù)
1)使用循環(huán)計(jì)算階乘
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)使用遞歸計(jì)算階乘
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)調(diào)用reduce函數(shù)計(jì)算階乘
說明:Python 在 functools 模塊提供了 reduce() 函數(shù),該函數(shù)使用指定函數(shù)對序列對象進(jìn)行累計(jì)。
查看函數(shù)信息:
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
補(bǔ)充:python求n的階乘并輸出_python求n的階乘
階乘是基斯頓·卡曼(Christian Kramp,1760~1826)于1808年發(fā)明的運(yùn)算符號(hào),是數(shù)學(xué)術(shù)語。
一個(gè)正整數(shù)的階乘(factorial)是所有小于及等于該數(shù)的正整數(shù)的積,并且0的階乘為1。自然數(shù)n的階乘寫作n!。
下面我們來看一下使用Python計(jì)算n的階乘的方法:
第一種:利用functools工具處理import functools
result = (lambda k: functools.reduce(int.__mul__, range(1, k + 1), 1))(5) print(result)```
第二種:普通的循環(huán)x = 1
y = int(input("請輸入要計(jì)算的數(shù):")) 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)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章
用Python制作簡單的樸素基數(shù)估計(jì)器的教程
這篇文章主要介紹了用Python制作簡單的樸素基數(shù)估計(jì)器的教程,同時(shí)介紹了如何去改進(jìn)精度來進(jìn)行算法優(yōu)化,需要的朋友可以參考下2015-04-04python實(shí)現(xiàn)釘釘機(jī)器人自動(dòng)打卡天天早下班
這篇文章主要為大家介紹了python實(shí)現(xiàn)釘釘機(jī)器人自動(dòng)打卡天天下早班實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06pandas重置索引標(biāo)簽的實(shí)現(xiàn)示例
在使用Pandas進(jìn)行數(shù)據(jù)處理時(shí),有時(shí)候我們可能會(huì)需要對數(shù)據(jù)進(jìn)行重置索引的操作,本文主要介紹了pandas重置索引標(biāo)簽的實(shí)現(xiàn)示例,具有一定的參考價(jià)值,感興趣的可以了解一下2024-04-04用tensorflow實(shí)現(xiàn)彈性網(wǎng)絡(luò)回歸算法
這篇文章主要介紹了用tensorflow實(shí)現(xiàn)彈性網(wǎng)絡(luò)回歸算法2018-01-01多個(gè)版本的python共存時(shí)使用pip的正確做法
這篇文章主要介紹了多版本python共存時(shí)使用pip的正確做法,幫助有多個(gè)python版本需求的人可以正確的導(dǎo)包,感興趣的朋友可以了解下2020-10-10