2016年3月2日星期三

SLOG WEEK7

Recently, we have learned something called recursion. Recursion is very important in computer programming, and it is very useful. Sometimes, it can solve the problem easier than not using recursion. I have never seen this word before, thus I feel a little bit difficult. In computer science, recursion is a method that divides a big problem into several small problems. The lecturer said that recursion must call itself in the function text, otherwise, it is not recursion. Therefore, when I am dealing with recursion, I have to think how do I call it in itself, and make it like a “loop”, maybe it is not an accurate word to describe recursion, but I cannot find another word to replace it.
"The power of recursion evidently lies in the possibility of defining an infinite set of objects by a finite statement. In the same manner, an infinite number of computations can be described by a finite recursive program, even if this program contains no explicit repetitions."(Wirth, Niklaus (1976). Algorithms + Data Structures = Programs. Prentice-Hall. p. 126.)
This is a very accurate description by Wirth, Niklaus. For example, Fibonacci sequence. The following codes are doing Fibonacci sequence with and without recursion.
def F(n):
                              if n == 0: return 0
                              elif n == 1: return 1
                              else: return F(n-1)+F(n-2)
                          def F(n):
                              a=1
                             b=1
                              temp=int()
                             for i in range(1,int(n)-1):
                                temp = a+b
                                a=b
                                b=temp
                             return b
From the codes, we can see that recursion can be simpler than not using recursion. In the first version, we just like peeling a fruit. Finally, we will get the core. Another method is more complicated. When we do a more complicated question, we might make mistakes without using recursion and the mistake is very hard to find in many codes. When I was doing the exercise, I found that there is a mistake that people always make, the function call itself infinite times and python give “maximum recursion depth exceeded” error to you. We need to be careful.


没有评论:

发表评论