2015年2月3日星期二

Week 4 : Think like a computer scientist (recursion)

My impression of first few weeks is that in order to think like a computer scientist you have to concrete the abstract concepts in  your mind. When doing the first two labs, I had trouble about understanding. For example, how to write methods as instructions indicate, what are subclass and how to implement it.

After doing all additional exercises, I kind of got some pictures in my head while coding. For example, when writing class Roster, I imaged myself create a blank sheet while writing r.Roster() and draw a line in the middle of the sheet while writing self.female = {}, self.male = {}. Likewise, every time I read the description of the class, I applied my imagination.

When it comes to recursion, the imagination lost its power. I had to trace step by step to help me understand the purpose of the method(e.g.count the number of lists)I have started to the concept of recursion,  “defining something in terms of itself multiple times”. Here is an example with comments are my understanding of each line:

    def count_elements(L):
    '''(list or non-list) -> int
    Count all elements in a given list(may contains many inner lists).
    '''
    if isinstance(L, list):
        return sum([count_elements(x) for x in L]) # if list, deg deeper
    else:
        return 1 # count plus 1 until the element is not list

Hope I can use recursion correctly and quickly through more practices.
   

没有评论:

发表评论