Sunday, March 2, 2014

Recursion

    The recursion method of python is very interesting, because it will call the function itself when you write the body of the function, and this makes the program much more succinct. For example, we want to write a program that reverses the string '12345' to '54321', with the help of recursion, we can write the following code to implement the request.
   def reverse(n):
    def reversestr(s):
        if s:
            return s[-1] + reversestr(s[:-1])
        else:
            return ''
    return int(reversestr(str(n)))
   
   As we can see, recursion can make a question that seems to have complicated steps easier to solve., and there must be a statement in the code to end the recursion (mainly the if or else statement), in the above example, it is the else statement that ends the recursion. Another classic example is the Fibonacci sequence 0,1,1,2,3,5,8,13,21......:
    def fib(n):
        if n<=1:
           return n
        t=fib(n-1)+fib(n-2)
        return t
   Like we want to find the 7th value of this sequence, and we need to add the 5th and 6th values together, and to get the 6th value, we need to find 4th and 5th, and so on. The two values are 0 and 1, so they are constant and will be the end of this recursion.
   Recursion is very useful, but kind of difficult for me to come up with ,so I need to read more materials and do more exercises to improve this skill.

No comments:

Post a Comment