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 calls recursive function summation directly". Center ("*") #显示效果明显for i in range (1,21): sum_0 +=recursion (i) Print (SUM_0) List summation scheme: list=[] #定义一个空的列表, 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)) #列表求和
The same number of lines of code can implement its functionality.
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): ' define 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) # append the factorial value generated by the calling recursive function to the list print (sum (list)) # List sum Sum_0=0print ("For loop calls recursive function summation directly". Center ("*") #显示效果明显for i in range (1,21): sum_0 +=recursion ( i) print (SUM_0) Result: ***************************** writes 1-20 factorial 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.