20190108 use of recursive function to realize the use of basic recursive functions such as finding the greatest common divisor

1. Given a = [1,2,[3,4,[5,6,7,[8,9,[10,11]]]], print output is required: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 Use the recursive function to traverse A. w...

1. Given a = [1,2,[3,4,[5,6,7,[8,9,[10,11]]]], print output is required: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11

Use the recursive function to traverse A. when the value of a is list, continue to call the recursive function, and take values one by one

def iter_list(l): for i in l: if isinstance(i,list): iter_list(i) #The elements in the list passed in before are list Call the recursive function else: print(i,end =' ') iter_list(a)

2. Make the result a list based on the first question

#Method 1 def iter_list(l,result=[]): #result Is the default parameter, which is used when no value is passed result=[],Use the value passed in when passing the value for i in l: if isinstance(i,list): iter_list2(i,result) else: result.append(i) return result print(iter_list(a)) #Method 2 def iter_list2(l,result): for i in l: if isinstance(i,list): iter_list2(i,result) else: result.append(i) return result result =[] print(iter_list2(a,result))

3. Write a method recursively to output n,n-1....10, 9, 8... 1 to 0 end

#algorithm:Print each number, exit recursion when the number is less than 0 def output_num(n): print(n) if n>0: output_num(n-1) else: print('----') output_num(5)

4. Using recursive function to write a method to find the maximum co constraint

#Algorithm: use the rolling phase division method for the maximum common divisor
Find (319377):
∵ 319 ÷ 377 = 0 (balance 319)
∴(319,377)=(377,319);
∵ 377 ÷ 319 = 1 (remaining 58)
∴(377,319)=(319,58);
∵ 319 ÷ 58 = 5 (remaining 29)
∴ (319,58)=(58,29);
∵ 58 ÷ 29 = 2 (remaining 0)
∴ (58,29)= 29;
∴ (319,377)=29

def find_max_common_divisor(a,b): if a<b: a,b = b,a print(a,b) #ensure a>b if a%b!=0: print('a%b Branch taken') temp = b b = a%b a = temp print(a,b) return find_max_common_divisor(a,b) #return There is a short-circuit effect. The following statements will not be executed else: return b print(find_max_common_divisor(319,377))

4 December 2019, 13:08 | Views: 5985

Add new comment

For adding a comment, please log in
or create account

0 comments