Python Decorator and recursive algorithm

Source: Internet
Author: User
Tags python decorator
1. Python Decorator

Just touch the Python decorator, simply ignorant of what the meaning of ah, there are wood, I have forgotten how many times debug, check how many times the information, guess a little bit began to understand. Summed up the explanation of the better, easy to understand to illustrate:

Small p idle come to nothing, casually look at their previous written functions, suddenly on a most basic function of interest:

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

At this point, the small p want to see how long this function takes, so write a few lines of code into the:

Import Time  def sum1 ():   start = Time.clock ()   sum = 1+2   print (sum)   end = Time.clock ()   print (" Time used: ", End-start)  sum1 ()

After running, perfect ~ ~

But as we continue to look, little P is interested in more and more functions, want to see their running time, do you want to change a function? Of course not! We can consider redefining a function Timeit, passing the sum1 reference to him, and then calling Sum1 in Timeit and timing it so that we don't have to change the SUM1 definition, and we don't have to modify the function definition no matter how many functions the little p looks at!

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)

Suck a look, no problem, can run! However, a part of the code was modified to change sum1 () to Timeit (SUM1). In this case, if the sum1 is called at N, you have to modify the code in the N place. So, we need Yang Sum1 () has the same effect as Timeit (SUM1), so Timeit is assigned to SUM1. However, Timeit is a parameter, so we need to find a way to unify the parameters, the return value of Timeit (SUM1) (the function that calculates the run time) assigns the value 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 ()

Such a simple decorator is done, we only need to call sum1 after the definition of sum1, plus sum1= Timeit (sum1), you can achieve the purpose of timing, which is the concept of adorners, it looks like sum1 was Timeit decorated! Python then provides a syntactic sugar to reduce the amount of character input.

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 ()

Focusing on the @timeit of line 11th, adding this line to the definition is exactly equivalent to the other write sum1 = Timeit (sum1).

2. Recursive algorithm

Recursive algorithm is a direct or indirect process to invoke its own algorithm. In the computer programming, the recursive algorithm is very effective to solve a large class of problems, it often makes the description of the algorithm concise and easy to understand.

The recursive algorithm solves the problem characteristic:

(1) Recursion is the invocation of itself in a procedure or function.
(2) When using a recursive strategy, there must be a definite recursive end condition called a recursive exit.
(3) Recursive algorithm is usually very concise, but the recursive algorithm is less efficient in solving problems. Therefore, the recursive algorithm is generally not advocated for the design of the program.
(4) in the process of recursive invocation, the system opens up a stack for each layer's return point, local quantity and so on to store. Too many recursion times can cause stack overflow and so on. Therefore, the recursive algorithm is generally not advocated for the design of the program.

For a chestnut: A number is evaluated in addition to 2 until it is less than or equal to 1 o'clock to exit and output the result

def divide (n,val):  n + = 1  print (val)  if VAL/2 > 1:    aa = Divide (N,VAL/2)    print (' The NUM is%D,AA i S%f '% (N,AA))  print (' The NUM is%d,val is%f '% (n,val))  return (val) divide (0,50.0)

The result is that (not return is equivalent to a nested loop, a layer of layers into a layer of exit):

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

2. Return at 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 was%d,val is%f '% (n,val))  return (val) divide (0,50.0)

The results are explained (the operation is terminated directly at return):

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

Recursive implementation of Fibonacci functions

def Feibo (first,second,stop,list):  If first >= stop or second >= stop:    return list  else:    sum = Firs T + 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 th E second number: '))  stop = Int (raw_input (' Please input the Stop number: '))  L = [First,second]  a = Feibo (fir st,second,stop,l)  Print (a)
  • 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.