2015년 2월 7일 토요일

Week 5: Impressions of tracing recursion from week 4

On week 4, we learned how to trace recursions. We also got a worksheet in class to practice tracing recursions. From the work sheet, recursions are usually written in this form:

def c(s):
     """ (Docstring omitted)
     """

     return sum ([c(i) for i in s]) if isinstance (s, list) else 1

Which means if there is a list, for example c(["one", 2, 3.5], the isinstance (s, list) will check if s is in a list. If so, the function will use a for loop to go over each element in s with an "i". However, I noticed that in this case, the "i" will be put in a c(i) for every element and in the end, all the elements in the list will refer to the else part of the fuction where in this case, it will return 1. Then the function will find the sum according to how many 1's there will be. I noticed that the faster way to figure out the answer in this case is to count how many elements there are in a list and times it by the number that is in the else part.

Another example of a recursion is:

def sum_list(L):
     """ (Docstring omitted)
     """

     if isinstance (L, list):
          return sum([sum_list(x) for x in L])
     else:
          return L

In this case, it is similar to the example above. However, in the return section, it says return sum([sum_list(x) for x in L]). So when the for loop is running, x will go over each elements in the list L and will be put in a sum_list(x). If this were to be saved as (a, b, c), then in the end, the y will be written sum([a, b, c]) which will produce a+b+c.
Example: sum_list ([4, 1, 8]) ---> sum([sum_list(4), sum_list(1), sum_list(8)])
                                           ---> sum([4, 1, 8])
                                           ---> 13

댓글 없음:

댓글 쓰기