recursion(5)
sum(reduce(lambda x,y: x*y, range(1,n+1)) for n in range(1,6))
How to implement mathematical factorial n in Python!
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
Copy after login
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) # 递归函数
Copy after loginrrree
def recursion(n): if n == 0 or n == 1: # 特殊情况 return 1 else: return n * recursion(n-1) # 递归函数
120Method 3 - The reduce function of the third-party library functools
recursion(5)
Copy after login
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+5Copy after login
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+5
# 求出下面的阶乘的累加求和
1 + 1*2 + 1*2*3 + 1*2*3*4 + 1*2*3*4*5
Copy after login
# 求出下面的阶乘的累加求和 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)
Copy after login
Call the recursive function based on for loop and sum summation# 定义累乘函数 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)
def 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))
Copy after login
# 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))
Copy after login
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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Many website developers face the problem of integrating Node.js or Python services under the LAMP architecture: the existing LAMP (Linux Apache MySQL PHP) architecture website needs...

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

When using Scapy crawler, the reason why pipeline persistent storage files cannot be written? Discussion When learning to use Scapy crawler for data crawler, you often encounter a...

Getting started with Python: Hourglass Graphic Drawing and Input Verification This article will solve the variable definition problem encountered by a Python novice in the hourglass Graphic Drawing Program. Code...

Python process pool handles concurrent TCP requests that cause client to get stuck. When using Python for network programming, it is crucial to efficiently handle concurrent TCP requests. ...

Deeply explore the viewing method of Python functools.partial object in functools.partial using Python...

Choice of Python Cross-platform desktop application development library Many Python developers want to develop desktop applications that can run on both Windows and Linux systems...

Many developers rely on PyPI (PythonPackageIndex)...
