Demand:
Factorial: Also a term in mathematics; factorial means multiplying from 1 times 2 times 3 times 4 to the required number; When expressing factorial, use "! "To express. such as h factorial, is expressed as h!; factorial is generally difficult to calculate, because the product is very large.
Question: Ask for 1+2!+3!+...+20! 's and
Implementation environment: Python3
Editor: Pycharm
Analysis: 1, factorial calculation is a more troublesome part of the implementation of recursive function is a better solution, first define a recursive function to achieve the factorial function.
def recursion (n): ' Define recursive function for factorial function ' if N==1:return 1else:return n*recursion (n-1)
2, summed up the idea, you can directly sum, you can also define a list to append the factorial result of the for traversal traversal to the list, and then use the sum () function to sum.
Sum_0=0print ("For loop directly calls recursive function summation". Center ("*")) #显示效果明显for I in Range (1,21): Sum_0 +=recursion (i) print (SUM_0) list sum scheme: l Ist=[] #定义一个空的列表, append the factorial value generated by the calling recursive function to the list print ("Write 1-20 factorial to the list, sum with the SUM function". Center ("*") #显示效果明显for I in Range (1,21): list. Append (recursion (i)) # appends the factorial value generated by the calling recursive function to the list print (SUM (list) #列表求和两者代码行数一样多都可以实现其功能.
Use knowledge points: Recursive functions for loop range () functions, and so on.
Full source code and results:
#/usr/bin/env python#_*_coding:utf-8_*_def recursion (n : ' definition of recursive function for factorial function ' if n==1: return 1 else: Return n*recursion (n-1) list=[] #定义一个空的列表, append the factorial value generated by the calling recursive function to the list print ("Write the factorial of 1-20 to the list, sum with the SUM function.") Center ("*") #显示效果明显for i in range (1,21): List.append (recursion (i)) # appends the factorial value generated by the calling recursive function to the list print (sum (list)) #列表求和sum_0 =0print ("The For loop calls the recursive function sum directly.") Center ("*") #显示效果明显for i in range (1,21): sum_0 +=recursion (i) print (SUM_0) Result: ***************************** writes the factorial of 1-20 to the list, using the SUM function to sum ************************ 2561327494111820313********************************for Loop Direct call recursive function summation ********************************* 2561327494111820313
Both are verified to achieve basic functionality, but the calculation of larger amounts of data is not tested.
This article is from the "Keep Dreaming" blog, please be sure to keep this source http://dreamlinux.blog.51cto.com/9079323/1910979
The factorial summation of Python's small code