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.
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 1 else: return n*recursion (n-1)
2, summing ideas, (1) can be summed directly. (2) You can also define a list, append the factorial result for the for traversal to the list, and then use the sum () function to sum.
Sum=0print ("For loop directly calls recursive function summation". Center ("*")) for I in range (1,21): sum +=recursion (i) print (sum) List sum scheme: 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 ("*") ) Range (1,21): list.append (Recursion (i) # appends the factorial value generated by the calling recursive function to the list print (sum (list)) #列表求和
Full source code and results:
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 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)) #列表求和Sum = 0for i in range (1,21): sum +=recursion (i) print (sum) results: 2561327494111820313
Python asks for the sum of the factorial. Seeking 1+2!+3!+...+20! and