2015年2月8日星期日

Week 5 SLOG for tracing Recursion

Again, here is some recursion exercises I have done before:

def count_lists(L):
    '''(list or non-list) -> int

    Return 0 if L is a non-list, or number of lists in possibly-nested L.
    
    if isinstance(L, list):
        return 1 + sum([count_lists(x) for x in L])
    else: # L is not a list
        return 0

1)Trace([2, 1, 3])
Answer: 1

Because there is only one list which is himself, and the elements in the list are non-list. Therefore, it returns (1 + sum[0, 0, 0]) which is 1.

2)Trace([2, 1, 3, '[4]'])
Answer: 1

'[4]' is not a list so it returns (1 + sum[0, 0, 0, 0]) which is 1, like above one.

3)Trace([7, [2, 1, [3, 4], 5], 9, [3, 2, 4]])
Answer: 4 

Because there are 4 lists, it returns (1 + 1 + 1 + 1 + sum[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) which is 4.


Here is the other one example:

def count_all(L):
    '''(list or non-list) -> int

    Return 0 if L is a non-list, or number of lists, plus non-list elements,
    in possibly-nested L.
    
    if isinstance(L, list):
        return 1 + sum([count_all(x) for x in L])
    else: # L is not a list
        return 1

1)Trace([2, 1, 3])
Answer: 4

According to the code, I know that if L is a list then it returns 1 + sum(elements in L), and if the element in L is also a list then it will run again like 1 + sum(a in element).If the element is not a list, then it returns 1.

So [2, 1, 3] is only one list which is himself. Then it returns 1 + sum([1, 1, 1]) which is 4.


2)Trace([2, 1, 3, [4]])
Answer: 6

[2, 1, 3, [4]] has two lists, then it returns 1 + 1 + sum([1, 1, 1, 1]) which is 6

3)Trace([7, [2, 1, [3, 4], 5], 9, [3, 2, 4]])
Answer: 14 

[7, [2, 1, [3, 4], 5], 9, [3, 2, 4]] has 4 lists, then it returns 1 + 1 + 1 + 1 + sum([1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) which is 14.


After some exercises, I find it is easy to trace recursion if I understand the codes and I know how it works. :)



没有评论:

发表评论