Home  >  Article  >  Backend Development  >  How to implement mathematical factorial n in Python!

How to implement mathematical factorial n in Python!

WBOY
WBOYforward
2023-05-11 08:40:054107browse

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

Method 1-Cumulative multiplication

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: 1

Value 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

Method 2-Use recursive function

def recursion(n):
    if n == 0 or n == 1:  # 特殊情况
        return 1
    else:
        return n * recursion(n-1)  # 递归函数
rrree

120

Method 3 - The reduce function of the third-party library functools

recursion(5)

120

Explanation 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
15

Python implements factorial accumulation Sum-Advanced Version

The 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

The correct result is 153

Method 1-cumulative sum

# 求出下面的阶乘的累加求和

1 + 1*2 + 1*2*3 + 1*2*3*4 + 1*2*3*4*5

120

The 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)  # 测试案例

153

Method 2-Cumulative multiplication recursion

In 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))

153

Method 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 summation

def recursion(n):
    """
    之前定义的递归函数
    """
    if n == 0 or n == 1:
        return 1
    else:
        return n * recursion(n-1)

153

Method 4-reduce combined with sum

# recursion(1) + recursion(2) + recursion(3) +  recursion(4) + recursion(5)

# 调用定义的递归函数
sum(recursion(i)  for i in range(1,6))

120

Single 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))

153

Method 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

How to implement mathematical factorial n in Python!

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete