Python implementation of factorial-basic version
What is factorial?
In mathematical operations, n! represents the factorial
of n. It is expressed as a mathematical formula:
n!=1*2*3*....*( n-1)*n
An example is provided below: For example, the factorial of 5
# 正确的结果 1*2*3*4*5
The correct result is: 120
The editor provides you with 3 types Different methods to implement factorial operation:
- ##Cumulative multiplication based on for operation
- Based on recursive function implementation
- Reduction function implementation based on the third-party library functools
result = 1 # 给定一个初始值
n = 5
for i in range(1, n+1):
print("累乘前result: ", result)
print("循环数i的值: ", i)
result = result * i # 不断地累成result
print("累乘后result: ", result)
print("------------")
result
Result before cumulative multiplication: 1Method 2-Use recursive functionValue of cycle number i: 1
Result after cumulative multiplication: 1
------------
Result before cumulative multiplication: 1
Value of cycle number i : 2
result after cumulative multiplication: 2
------------
result before cumulative multiplication: 2
value of loop number i: 3
cumulative multiplication After result: 6
------------
Result before cumulative multiplication: 6
Value of loop number i: 4
Result after cumulative multiplication: 24
------------
Result before cumulative multiplication: 24
Value of cycle number i: 5
Result after cumulative multiplication: 120
------- -----
The result is: 120
def recursion(n):
if n == 0 or n == 1: # 特殊情况
return 1
else:
return n * recursion(n-1) # 递归函数
rrree
120Method 3 - The reduce function of the third-party library functools
recursion(5)
120Explanation of usage of the reduce function:
# 在python3中reduce函数被移入到functools中;不再是内置函数 from functools import reduce n = 5 reduce(lambda x,y: x*y, range(1,n+1))
- Required Given a function to be executed (the above is an anonymous function; or a custom function)
- Given an iterable object iterable
- Optional initializer
reduce(function, iterable[, initializer])
15# 使用自定义函数 from functools import reduce number = range(1,6) # number = [1,2,3,4,5] def add(x,y): return x+y reduce(add, number) # 1+2+3+4+5
15Python implements factorial accumulation Sum-Advanced VersionThe following is an advanced requirement:
How to implement the cumulative sum of factorials?
# 使用匿名函数 from functools import reduce number = range(1,6) reduce(lambda x,y: x+y, number) # 1+2+3+4+5The correct result is 153Method 1-cumulative sum
# 求出下面的阶乘的累加求和
1 + 1*2 + 1*2*3 + 1*2*3*4 + 1*2*3*4*5
120The above is our implementation For the factorial of a single number, put it into a for loop to find the cumulative sum:
# 定义累乘函数 def func(n): result = 1 for i in range(1, n+1): result = result * i # 不断地累成re return result func(5) # 测试案例
153Method 2-Cumulative multiplication recursionIn Use cumulative multiplication and recursive functions simultaneously in one function
# func(1) + func(2) + func(3) + func(4) + func(5) # 调用累乘函数 sum(func(i) for i in range(1,6))
153Method 3-Recursive sum
# 定义累乘函数
def func(n):
result = 1 # 定义初始值
for i in range(1, n+1):
result = result * i # 不断地累成re
# if result == 1 : 等价于下面的条件
if n==0 or n==1:
return 1
else: # 下面是关键代码
return result + func(n-1) #在这里实现递归 func(n-1)
func(5)
Call the recursive function based on for loop and sum summationdef recursion(n): """ 之前定义的递归函数 """ if n == 0 or n == 1: return 1 else: return n * recursion(n-1)
153Method 4-reduce combined with sum
# recursion(1) + recursion(2) + recursion(3) + recursion(4) + recursion(5)
# 调用定义的递归函数
sum(recursion(i) for i in range(1,6))
120Single Call the reduce function twice, combining the for loop and sum to find the sum
from functools import reduce n = 5 reduce(lambda x,y: x*y, range(1,n+1))
153Method 5 - reduce function twice
sum(reduce(lambda x,y: x*y, range(1,n+1)) for n in range(1,6))
[ 1, 2, 6, 24, 120]Pass the above result into the reduce function again as an iterable list. The execution function at this time is the sum of two elements (x y):
[reduce(lambda x,y: x*y, range(1,n+1)) for n in range(1,6)]
153
The above is the detailed content of How to implement mathematical factorial n in Python!. For more information, please follow other related articles on the PHP Chinese website!

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version
SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

WebStorm Mac version
Useful JavaScript development tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
