Python 怎么定義計算N的階乘的函數(shù)
定義計算N的階乘的函數(shù)
1)使用循環(huán)計算階乘
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)調(diào)用reduce函數(shù)計算階乘
說明:Python 在 functools 模塊提供了 reduce() 函數(shù),該函數(shù)使用指定函數(shù)對序列對象進行累計。
查看函數(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
補充:python求n的階乘并輸出_python求n的階乘
階乘是基斯頓·卡曼(Christian Kramp,1760~1826)于1808年發(fā)明的運算符號,是數(shù)學術(shù)語。
一個正整數(shù)的階乘(factorial)是所有小于及等于該數(shù)的正整數(shù)的積,并且0的階乘為1。自然數(shù)n的階乘寫作n!。
下面我們來看一下使用Python計算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("請輸入要計算的數(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)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章
Python基于smtplib協(xié)議實現(xiàn)發(fā)送郵件
這篇文章主要介紹了Python基于smtplib協(xié)議實現(xiàn)發(fā)送郵件,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-06-06
Pytest使用fixture實現(xiàn)token共享的方法
同學們在做pytest接口自動化時,會遇到一個場景就是不同的測試用例需要有一個登錄的前置步驟,登錄完成后會獲取到token,用于之后的代碼中,本文給大家介紹Pytest使用fixture實現(xiàn)token共享的方法,感興趣的朋友一起看看吧2023-11-11
安裝Keras,tensorflow,并實現(xiàn)將虛擬環(huán)境添加到j(luò)upyter?notebook
這篇文章主要介紹了安裝Keras,tensorflow,并實現(xiàn)將虛擬環(huán)境添加到j(luò)upyter?notebook,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03
Pygame實現(xiàn)游戲最小系統(tǒng)功能詳解
這篇文章主要介紹了Pygame實現(xiàn)游戲最小系統(tǒng),Pygame是一個專門用來開發(fā)游戲的 Python 模塊,主要為開發(fā)、設(shè)計 2D 電子游戲而生,具有免費、開源,支持多種操作系統(tǒng),具有良好的跨平臺性等優(yōu)點2022-11-11

