When I first heard this idea during lecture, a few sentences came to my mind:
To see a world in a grain of sand
And a heaven in a wild flower,
Hold infinity in the palm of your hand
And eternity in an hour.
It may sounds nonsense, but personally I feel there is a correlation. Recursion is just like a sand, inside you find a whole world, and inside that world you still have a sand, and it loops. However, in recursion, you will finally reach a point where you can exit the loop.
We focused on tracing recursions last week, here is a brief example:
def sum_list(L):
’’’
(arbitrarily nested list of int or int) -> int
Return the sum of all ints in L.
>>> sum_list([1, [2, 3], [4, 5, [6, 7], 8]]) 36 ’’’
if isinstance(L, list):return sum([sum_list(x) for x in L]) # calls isinstance(), sum(), sum_list() methodselse:
return L # base case1.sum_list(27) --> 27 # int, depth(0)2.sum_list([4, 1, 8] --> sum( [ sum_list(4), sum_list(1), sum_list(8) ] )
--> sum([4, 1, 8])
--> 13 # depth(1)
3. sum_list([4]) --> sum([sum_list(4)])
-->sum([4])
--> 4
4. sum_list([]) --> sum(sum_list(x) for x in [])--> sum([])
--> 0
5. sum_list([4, [1, 2, 3], 8]) --> sum([ sum_list(4), sum_list([1, 2, 3]), sum_list(8)])# already traced depth 0 and depth 1--> sum([4, 6, 8])--> 186. sum_list([[1, 2, 3], [4, 5], 8]) --> sum([sum_list([1, 2, 3]), sum_list([4, 5]), sum_list(8)])# already traced depth 0 and depth 1--> sum([6, 9, 8])--> 237. sum_list([1, [2, 2], [2, [3, 3, 3], 2]]) --> sum([sum_list(1), sum_list([2, 2]), sum_list([2, [3, 3, 3], 2])])# already traced depth 0, depth 1 and depth 2--> sum([1, 4, 13])--> 188. sum_list([1, [2, 2], [2, [3, [4, 4], 3, 3], 2]]) --> sum([sum_list(1), sum_list([2, 2]), sum_list([2, [3, [4, 4], 3 , 3], 2])])# already traced depth 0, depth 1, and depth 3--> sum([1, 4, 21])--> 26First, be clear about the base case.Then just trace the recursion step by step, and we use the results before, otherwise the tracing will be too long.

No comments:
Post a Comment