Python uses recursion, tail recursion, and loop to implement the Fibonacci series.

Source: Internet
Author: User

Python uses recursion, tail recursion, and loop to implement the Fibonacci series.

At the beginning, all the Fibonacci codes were written recursively. recursion has many disadvantages, such as low execution efficiency, resource waste, and stack overflow, the advantage of recursive Programs is also obvious, that is, the structural layers are clear and easy to understand.

Recursive can be replaced by a loop, or tail recursion.

Tail recursion is calculated from the end, and the corresponding result is calculated every time the recursion is performed. That is to say, the function call appears at the end of the caller's function, because it is the end, therefore, there is no need to save any local variables. directly let the called function return more than the caller, and return to the caller. Tail recursion is to put the current calculation result (or path) in the parameter and pass it to the lower-level function. Deep functions face more and more complex problems than simple ones, because the parameter contains the path of the previous steps. Tail recursion is extremely important, and does not require tail recursion. The Stack Consumption of functions is immeasurable and the stacks of many intermediate functions need to be saved. In a directly recursive program, it is extremely resource-consuming to save all the statuses of the previous n steps, but tail recursion is not required. tail recursion is a programming technique. In a recursive function, the result returned by a recursive call is always directly returned, which is called tail recursion. Recursive functions at the end can be used to convert algorithms into function programming languages. In addition, they are easily optimized into common loops from the compiler perspective. This is because from the computer fundamentals, all cycles are implemented by repeatedly moving to the beginning of the Code. If there is tail delivery, you only need to stack one stack, because the computer only needs to change the function parameter and then call it again

In order to deepen the comparison of tail recursion, recursion, and loop, the following is an example of the implementation of the Fibonacci series:

#! Usr/bin/env python # encoding: UTF-8 ''' _ Author __: the function of the cold city of Lishui: tail recursion ''' import time def glasrecursion (num ): ''''' solve the nth num digit of the Fibonacci number directly using recursion ''' if num <2: return num return maid (num-1) + fig (num-2) def fiber _ tail_recursion (num, res, temp): ''' use the tail recursion method to solve the num Number of the Fibonacci quantity ''' if num = 0: return res else: return fig (num-1, temp, res + temp) def maid (num ): ''' directly uses a loop to solve ''' a = 0 B = 1 for I in range (1, num ): c = a + B a = B = c return c if _ name _ = '_ main _': num_list = [5, 10, 20, 30, 40, 50] for num in num_list: start_time = time. time () print maid (num) end_time = time. time () print maid (num, 0, 1) end_time2 = time. time () print maid (num) end_time3 = time. time () print 'the Fibonacci number subscript being solved is % s' % num print 'Direct recursion time is:', end_time-start_time print 'tail recursion call time is :', end_time2-end_time print 'Use loop time directly:', end_time3-end_time2

The result is as follows:

5 5 5 the final Fibonacci number subscript being solved is 5 and the time consumed for direct recursion is: 6.38961791992e-05. the time consumed for tail recursion call is 2.31266021729e-05. the time consumed for direct use of the loop is: 1.97887420654e-05 55 55 55 the Fibonacci numeric subscript being solved is 10 direct recursion time: 6.60419464111e-05 tail recursive call time: 3.31401824951e-05 direct use of the cycle time is: 1.8835067749e-05 6765 6765 6765 the Fibonacci subscripts being solved are 20. The direct recursion time is: 0.00564002990723. The tail recursion call time is: 3.09944152832e-05. The direct cycle time is: 2.09808349609e-05 832040 832040 832040 the Fibonacci subscripts being solved are 30 direct recursion time consuming: 0.39971113205 tail recursion call time consuming: 1.69277191162e-05 direct use cycle time consuming: 1.19209289551e-05 102334155 102334155 the Fibonacci subscripts being solved are 40 direct recursion time consumed: 102334155 tail recursion call time consumed: 2.19345092773e-05 direct use cycle time consumed: 1.78813934326e-05 12586269025 12586269025 the Fibonacci subscripts being solved are 50. Direct recursion: 12586269025 tail recursion: 2.19345092773e-05. cycle: 2.09808349609e-05.

You can see the gap more clearly in the drawing chart:

Because of the large gap, the time increase of tail recursion and loop is almost a horizontal line, while the time increase of direct recursion is close to 90 degrees.

This time, I felt very patient and always waited for the results of the program. We can see the time comparison between the three. Obviously, the time of direct recursion is growing rapidly, loop performance is better than tail recursion, which tells us to minimize the use of recursion. Using the method of loop instead of recursion is undoubtedly a way to improve the program running efficiency.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.