In this week, recursion is a new concept for me, and I think this is hard to understand how it works at first. I usually get wrong way in some problems.But I work it out with some help of TA and I try some exercise in the lab successfully.
For example, in this question:
def count_elements(L):
’’’(list or non-list) -> int
Return 1 if L is a non-list, or number of non-list elements in possibly- nested list L.
Assume: L is any Python object. # examples omitted!
’’’
if isinstance(L, list):
return sum([count_elements(x) for x in L])
else: # if L is not a list, count it
return 1
1.Trace count_elements('smoke')
The answer is 1 because 'smoke' is a string but not a list.
2.Trace count_elements([2, 1, 3])
The answer is 3 because [2, 1, 3] is a list and then the elements in the list are 2, 1, 3 which are integers but not lists. Then it comes out sum[1, 1, 1] which is 3.
3.Trace count_elements([[2, 1, 3, '[4]’]])
The answer is 4. In the same way, it goes through the loop again and again and it comes out sum[1, 1, 1, 1] which is 4.
4.Trace count_elements([7, [2, 1, 3], 9, [3, 2, 4]])
The answer is 8 comes from sum[1. 1. 1. 1. 1. 1. 1. 1]
Overall, solving the recursion problem is going through the loop. And the best way to work it out is write down all things step by step.
没有评论:
发表评论