We learned recursion. I think to understand recursion, knowing the basic structure of recursion coding is the most important thing.
The general form of recursion is:
if <condition to detect a base case>:
<do something without recursion>
else: # <general case>
<do something that involves recursive call(s)>
However, it is still not clearly show what recursion is by only understand the general form. In the class our prof provide us example about sorting. Sorting or counting numbers are some simple examples of recursion.
The sorting of a list of number could be write as:
def quick_sort(L):
‘ ‘ ‘(list) -> list
if len(L) < 2:
return L
else:
return (quick_sort([x for x in L if x < L[0]]) + [L[0]] + quick_sort([x for x in L if x > L[0]]))
But we have to make sure L is a list or the type it should be in other exercise.
Recursion is deeply related to binary tree. We can count the height, number of leaves or parity of the tree by using recursion.

没有评论:
发表评论