#1, to calculate the factorial of a function with recursion
def MYFAC (n): #用循环实现 s= 1 for i in range (1,n+1): s*=i print (s) MYFAC (5) def MYFAC (n): #用循环实现 if n==1: return 1 return N*MYFAC (n-1) Print (MYFAC (5))
#2, summing with recursion: Def mysum (n): #返回1 +2+3+4+5+n and print (mysum) #5050def mysum (n): if n==1: return 1 return N+mysum (n-1) print (mysum (100))
3. A list is known
L=[[3,5,8],10,[[13,14,],15,18],20]
Write a function print_list (LST) to print out all the numbers
Write a function sum_list (LST) to return all numbers in the list
and the
Note:
The type (x) function can return the types of an object
>>>type () is int #True
Type ([3,5,8]) is List #True
def print_list (LST): # l=[] for x in LST: if Type (x) is int: # print_list (x) print (x) else: print_list (x) # Print (x) def sum_list (LST): sum=0 for x in LST: if Type (x) is list: sum+=sum _list (x) else: sum+=x return suml=[[3,5,8],10,[[13,14,],15,18],20]print_list (l) Print (Sum_list (l) )
4, using recursive method to achieve fast sorting
def QuickSort (mylist,start,end): If start < end: i,j = start,end #设置基准数 base = mylist[i] while I < j: #如果列表后边的数, larger or equal than the base number, move forward one until there is a number smaller than the base number appears while (I < J) and (Mylist[j] >= base): j = j-1 #如找到, then Assign the first J element to the first element I, and the table i,j elements equal mylist[i] = mylist[j] #同样的方式比较前半区 while (i < J) and (Mylist[i] <= base) : i = i + 1 mylist[j] = mylist[i] #做完第一轮比较之后, the list is divided into two halves, and i=j, this number needs to be set back to base mylist[i] = base #递归前后半区 QuickSort (myList, Start, i-1) QuickSort (MyList, J + 1, end) return mylistmylist = [49,38,65,97,7 6,13,27,49]print ("Quick Sort:") QuickSort (Mylist,0,len (myList)-1) print (myList)
Python implementation: recursive (example) of a function