Python function recursion and generator

Source: Internet
Author: User
The following small series will bring you an in-depth understanding of python function recursion and generator. I think this is quite good. now I will share it with you and give you a reference. Let's take a look at it with Xiaobian. 1. what is recursion?

If a function contains a call to itself, the function is recursive. Recursion is an algorithm widely used in programming languages. it usually converts a large and complex problem into a small problem similar to the original problem to solve it, the recursive strategy can describe the repeated computing required for the problem-solving process with only a small number of programs, greatly reducing the amount of code in the program. For example, to calculate the product of 9-digit numbers from 1 to 9, the intuitive algorithm is 1*2*3*4*5*6*7*8*9, if you want to calculate the product of 1-00, intuitive algorithms are difficult to implement, and recursion can be very simple. See the example:

Def fact (n): # calculate the product of a given number to one. if n <= 1: return 1 else: return n * fact (n-1) print (fact (7 ))

Result: 5040

The following example shows the recursive execution process:

def calc(n):   print(n)   if n/2 > 1:     res = calc(n/2)   return n calc(8)

Result:

84.02.0

Let's look at this example again:

def calc(n):  print(n)  if n/2 > 1:    res = calc(n/2)    print('res:',res)  print("N:",n)  return ncalc(8)

Result:

84.02.0N: 2.0res: 2.0N: 4.0res: 4.0N: 8

II. generator

The generator is a function with yield statements. A function or sub-program returns only once, but a generator can pause execution and return an intermediate result. a value is returned to the caller and the execution is paused. When the next () method of the generator is called, it will accurately continue from the departure location

The following is an example:

def func():  print('11111111')  yield [1]  print(2222222222)  yield 2  print(3333333333)  yield 3ret=func()r1=ret.__next__()print(r1)r2=ret.__next__()print(r2)r3=ret.__next__()print(r3)

Result:

11111111[1]2222222222233333333333

Because python's for loop includes the next () call and the processing of StopIteration, a for loop is used instead of a manual iteration to pass through a generator (or the iterator of That Thing) it is always more concise and beautiful. Example:

def func():  print('11111111')  yield [1]  print(2222222222)  yield 2  print(3333333333)  yield 3ret=func()for i in ret:  print(i)

The result is the same as the previous one.

These simple examples should help you understand how the generator works. In addition to next (), you can return the value to the generator [send ()], throw an exception in the generator, and require the generator to exit [close ()].

The following is a simple example of these features.

def counter(start_at=0):  count = start_at  while True:    val = (yield count) if val is not None:    count = val  else:    count += 1

The generator has an initialization value. each call to the generator [next ()] is incremented by 1. You can reset this value if you want to use a new value to call send () instead of next (). This generator runs forever, so if you want to terminate it, call the close () method. If we run this code interactively, we will get the following output:

>>> count = counter(5)>>> count.next()5>>> count.next()6>>> count.send(9)9>>> count.next()10>>> count.close()>>> count.next()Traceback (most recent call last):File "
 
  ", line 1, in 
  
   StopIteration
  
 

The above in-depth understanding of python function recursion and generator is all the content shared by the editor. I hope to give you a reference and support for PHP.

For more python function recursion and generator related articles, please follow the PHP Chinese network!

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.