2015年1月31日星期六

slog week 4

slog week 4

In this week’s lecture I learned about recursion. We use sum_list to example and trace it to learn recursion. 

def sum_list(L):
’’’ (list or int) -> int
Return L if it’s an int, or sum of the numbers in possibly nested list L
>>> sum_list(17)
17
>>> sum_list([1, 2, 3])
6
>>> sum_list([1, [2, 3, [4]], 5])
15
’’’
I think the code of recursion for this example should write as:
return sum([sum_list(x) for x in L])
However, I ignored the type of the list, we need to use:
if isinstance(L, list): to see whether L is a list or not.
and if L is not a list, we need to use:
else: # L is an int
return L

I did pretty well in the class worksheet’s question. However, I did figure out the lab question.

In the lab I follow the instruction sheet to do the 4 examples first. The third example nd(L), was really hard. Other than the examples given by the instruction sheet, I create several example to trace nd(L), such as [[3,3],[4,[4,5]]], and [[3,3],[4,[4,[3,3,[4,4]],5]]].


Although I did not finish the lab, I feel I could do better about recursion.

没有评论:

发表评论