Sunday, 1 March 2015

Recursion (week 7)

Last week I wrote the note about the o-o design  ,  which are just some basic concepts . But I think that's not good enough , this week I'm going to write something interesting about recursion , and I will write about the ADT next week .

Here comes the first question , what is recursion?
In website Wikipedia , we can find the formal definition has two properties:
1.A simple base case (or cases) 2.A set of rules that reduce all other cases toward the base case
After having 148 class , I grow my own idea about this such that recursion is something that a parameter run in a function  , then a parameter will come from the previous result and continuing run in that previous function , and this work will work infinite time .In a word ,  the parameter will change automatically(after every time calculation ) and work in a same function.

Then you might ask that how it works , it that applicable  ?
Actually recursion is very important in both math and computer science . As in math , people can use recursion to find the rule of the numbers , and it will be easier to define them , mostly people will use formula to define set of recursive numbers, for example , there's 2^n(0<=n<=4, n is integer) for {1,2,4,8,16},there is also lots of recursive numbers that can not be defined by math just like famous Fibonacci numbers . But for this one , we can use the computer language to express it . In computer science , it works similarly , but it takes the advantage that computer can compute automatically and accurate .

You probably think recursion is awesome after read the previous things , well,  let's read a recursion question to have some fun .

def nested_concat(L):
    ’’’(list or str) -> str
    Return L if it’s a str, if L is a (possibly-nested) str return
    concatenation of str elements of L and (possibly-nested) sublists of L.
    Assume: Elements of L are either str or lists with elements that
            satisfy this same assumption.
    # examples omitted!
    ’’’
    if isinstance(L, str):
        return L
    else: # L is a possibly-nested list of str
        return ’’.join([nested_concat(x) for x in L])

trace nested concat([[’how’, [’now’, ’brown’, [’cow’]], ’eh?’]])
     nested_concat([[’how’, [’now’, ’brown’, [’cow’]], ’eh?’]])
        --> ’’.join([nested_concat(x) for x in [[’how’, [’now’, ’brown’, [’cow’]], ’eh?’]]
        --> ’’.join([’how’, ’nowbrowncoweh?’]) # believe docstring for str and possibly-nested

                                               # list of str or possibly-nested...
the answer:
        --> ’hownowbrowncoweh?’
In this question  , I find a special way to solve this kind of  problem is that trying to count the number of brackets will help.

That's the things for this week . Thank you for reading my log .



Cited websites or other materials  :

No comments:

Post a Comment