Python decorator and recursive algorithm details, python Recursion

Source: Internet
Author: User
Tags python decorator

Python decorator and recursive algorithm details, python Recursion

1. python decorators

I just got in touch with the python decorator, and I just forgot how many times I Debug and how many times I checked the information, I started to understand it. I have summarized the following explanations:

Little P has nothing to do with it. He just looks at some of the functions he previously wrote and suddenly became interested in one of the most basic functions:

 def sum1():   sum = 1 + 2   print(sum) sum1()

At this time, the small P wants to see how long it took to execute this function, so I wrote a few codes and inserted them into it:

 import time  def sum1():   start = time.clock()   sum = 1+2   print(sum)   end = time.clock()   print("time used:",end - start)  sum1()

After running, perfect ~~

However, as I continue to look at it, I am interested in more and more functions. I want to see how long they run. Do I need to change functions one by one? Of course not! We can consider redefining a function timeit, passing the reference of sum1 to him, and then calling sum1 in timeit for timing. In this way, we have achieved the goal of not modifying the definition of sum1, no matter how many functions P reads, we don't have to modify the function definition!

import timedef sum1():  sum = 1+ 2  print (sum)def timeit(func):  start = time.clock()  func()  end =time.clock()  print("time used:", end - start)timeit(sum1)

You can run it! However, I modified some code and changed sum1 () to timeit (sum1 ). In this case, if sum1 is called at N, You have to modify the code at N. Therefore, we need Yang sum1 () to have the same effect as timeit (sum1), so we assign timeit to sum1. However, timeit has parameters, so you need to find a method to unify the parameters and assign the return value of timeit (sum1) (a function for calculating the running time) to sum1.

 import time  def sum1():   sum = 1+ 2   print (sum)  def timeit(func):   def test():     start = time.clock()     func()     end =time.clock()     print("time used:", end - start)   return test  sum1 = timeit(sum1) sum1()

This simple decorator is ready. We only need to add sum1 = timeit (sum1) before calling sum1 after sum1 is defined to achieve the purpose of timing, this is the decorator concept. It looks like sum1 is decorated by timeit! Python provides a syntax sugar to reduce the input of characters.

 import time   def timeit(func):   def test():     start = time.clock()     func()     end =time.clock()     print("time used:", end - start)   return test  @timeit def sum1():   sum = 1+ 2   print (sum)  sum1()

Focus on the @ timeit of the 11th rows. The addition of this row in the definition is equivalent to the addition of sum1 = timeit (sum1.

2. Recursive Algorithms

A recursive algorithm is a process of directly or indirectly calling its own algorithms. In computer programming, recursive algorithms are very effective in solving a large variety of problems. They often make the description of algorithms concise and easy to understand.

Features of recursive algorithms:

(1) recursion is to call itself in a process or function.
(2) When using a recursive policy, there must be a clear recursive termination condition called the recursive exit.
(3) recursive algorithms are usually simple in solving problems, but they are less efficient in solving problems. Therefore, recursive algorithms are generally not recommended for programming.
(4) In the process of recursive calling, the system opens a stack for storing the return points and local volumes of each layer. Too many recursion times may cause stack overflow. Therefore, recursive algorithms are generally not recommended for programming.

For example, divide a number by 2 and exit and output the result when the value is less than or equal to 1.

def divide(n,val):  n += 1  print(val)  if val / 2 > 1:    aa = divide(n,val/2)    print('the num is %d,aa is %f' % (n,aa))  print('the num is %d,val is %f' % (n,val))  return(val)divide(0,50.0)

Result description (if the return parameter is left blank, it is equivalent to a nested loop, which exits layer by layer ):

50.025.012.56.253.1251.5625the num is 6,val is 1.562500the num is 5,aa is 1.562500the num is 5,val is 3.125000the num is 4,aa is 3.125000the num is 4,val is 6.250000the num is 3,aa is 6.250000the num is 3,val is 12.500000the num is 2,aa is 12.500000the num is 2,val is 25.000000the num is 1,aa is 25.000000the num is 1,val is 50.000000

2. return in recursion:

def divide(n,val):  n += 1  print(val)  if val / 2 > 1:    aa = divide(n,val/2)    print('the num is %d,aa is %f' % (n,aa))    return(aa)  print('the num is %d,val is %f' % (n,val))  return(val)divide(0,50.0)

Result description ):

50.025.012.56.253.1251.5625the num is 6,val is 1.562500the num is 5,aa is 1.562500the num is 4,aa is 1.562500the num is 3,aa is 1.562500the num is 2,aa is 1.562500the num is 1,aa is 1.562500

Implement the Fibonacci Function Using Recursion

def feibo(first,second,stop,list):  if first >= stop or second >= stop:    return list  else:    sum = first + second    list.append(sum)    if sum <= stop:      return feibo(second,sum,stop,list)  return listif __name__ == '__main__':  first = int(raw_input('please input the first number:'))  second = int(raw_input('please input the second number:'))  stop = int(raw_input('please input the stop number:'))  l = [first,second]  a = feibo(first,second,stop,l)  print(a)

Articles you may be interested in:
  • Introduction to functions and function parameters of the python decorator
  • Using the Python decorator without calling the parent class Constructor
  • Python implements recursive file copy implementation code
  • Python uses recursion to solve the example of a fully-arranged number
  • Use python to implement the recursive tower example (tower recursive algorithm)
  • Python Implementation of Fibonacci recursive functions
  • Detailed description of function programming for Python decorators
  • A detailed tutorial on the decorator, closure, and functools in Python
  • Multiple decorators in Python
  • Recursive functions in Python
  • Describes the usage of the @ property modifier in Python

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.