Method of factorial summation in python code

高洛峰
Release: 2017-03-28 16:48:42
Original
21722 people have browsed it

Requirements:

Factorial: It is also a term in mathematics; factorial refers to multiplying from 1 times 2 times 3 times 4 to the required number; when expressing factorial, use " !"To represent. For example, h factorial is expressed as h!; factorial is generally difficult to calculate because the products are very large.

Question: Find the sum of 1+2!+3!+...+20!

Implementation environment: python3

Editor:pycharm

Analysis: 1. The calculation of factorial is a troublesome part. Using recursive function is a better solution. First define a recursive function to implement the solution. factorial function.

def  recursion(n):
 
   '定义递归函数实现求阶乘功能'
if n==1:
    return 1
else:
 
    return  n*recursion(n-1)
Copy after login

2. The idea of ​​​​summing can be summed directly, or you can define a list to append the factorial results obtained by for traversal to the list, and then use the sum() function to sum.

sum_0=0
print("for循环直接调用递归函数求和".center(80,"*")) #显示效果明显
for  i  in range(1,21):
    sum_0 +=recursion(i)
print(sum_0)
 
列表求和方案:
list=[] #定义一个空的列表,将调用递归函数生成的阶乘值追加到列表
print("将1-20的阶乘写入列表,使用sum函数求和".center(80,"*")) #显示效果明显
for  i  in range(1,21):
    list.append(recursion(i))# 将调用递归函数生成的阶乘值追加到列表
print(sum(list)) #列表求和
Copy after login

Both can achieve their functions with the same number of lines of code.

Use knowledge points: recursive functions, for loops, range() functions, etc.

Complete source code and results:

#/usr/bin/env python
#_*_coding:utf-8_*_
def  recursion(n):
    '定义递归函数实现求阶乘功能'
    if n==1:
        return 1
    else:
        return  n*recursion(n-1)
list=[] #定义一个空的列表,将调用递归函数生成的阶乘值追加到列表
 
print("将1-20的阶乘写入列表,使用sum函数求和".center(80,"*")) #显示效果明显
for  i  in range(1,21):
    list.append(recursion(i))# 将调用递归函数生成的阶乘值追加到列表
print(sum(list)) #列表求和
sum_0=0
print("for循环直接调用递归函数求和".center(80,"*")) #显示效果明显
for  i  in range(1,21):
    sum_0 +=recursion(i)
print(sum_0)
结果:
*****************************将1-20的阶乘写入列表,使用sum函数求和*****************************
2561327494111820313
********************************for循环直接调用递归函数求和*********************************
2561327494111820313
Copy after login

It has been verified that both can achieve basic functions, but calculations with larger amounts of data have not been tested.

The above is the detailed content of Method of factorial summation in python code. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template