Table of Contents
Python implementation of factorial-basic version
recursion(5)
Copy after login
" >
recursion(5)
Copy after login
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))
Copy after login
Home Backend Development Python Tutorial How to implement mathematical factorial n in Python!

How to implement mathematical factorial n in Python!

May 11, 2023 am 08:40 AM
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
Copy after login

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
Copy after login

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)  # 递归函数
Copy after login
rrree

120

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

recursion(5)
Copy after login

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))
Copy after login

  • 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])
    Copy after login
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
Copy after login
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
Copy after login

The correct result is 153

Method 1-cumulative sum

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

1 + 1*2 + 1*2*3 + 1*2*3*4 + 1*2*3*4*5
Copy after login

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)  # 测试案例
Copy after login

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))
Copy after login

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)
Copy after login

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)
Copy after login

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))
Copy after login

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))
Copy after login

153

Method 5 - reduce function twice

sum(reduce(lambda x,y: x*y, range(1,n+1)) for n in range(1,6))
Copy after login

[ 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)]
Copy after login
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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to efficiently integrate Node.js or Python services under LAMP architecture? How to efficiently integrate Node.js or Python services under LAMP architecture? Apr 01, 2025 pm 02:48 PM

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...

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

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

What is the reason why pipeline persistent storage files cannot be written when using Scapy crawler? What is the reason why pipeline persistent storage files cannot be written when using Scapy crawler? Apr 01, 2025 pm 04:03 PM

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...

Python hourglass graph drawing: How to avoid variable undefined errors? Python hourglass graph drawing: How to avoid variable undefined errors? Apr 01, 2025 pm 06:27 PM

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...

What is the reason why the Python process pool handles concurrent TCP requests and causes the client to get stuck? What is the reason why the Python process pool handles concurrent TCP requests and causes the client to get stuck? Apr 01, 2025 pm 04:09 PM

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. ...

How to view the original functions encapsulated internally by Python functools.partial object? How to view the original functions encapsulated internally by Python functools.partial object? Apr 01, 2025 pm 04:15 PM

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

Python Cross-platform Desktop Application Development: Which GUI Library is the best for you? Python Cross-platform Desktop Application Development: Which GUI Library is the best for you? Apr 01, 2025 pm 05:24 PM

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...

Do Google and AWS provide public PyPI image sources? Do Google and AWS provide public PyPI image sources? Apr 01, 2025 pm 05:15 PM

Many developers rely on PyPI (PythonPackageIndex)...

See all articles