Python function recursion and generator

Source: Internet
Author: User

First, what is recursion

If a function contains a call to itself, the function is recursive. Recursion is an algorithm widely used in programming language, it usually transforms a large and complex problem layer into a small scale problem similar to the original problem to solve, the recursive strategy needs a few programs to describe the process of solving the problem of repeated computations, greatly reducing the code of the program. For example, to calculate the product of 1-9 of 9-bit numbers, the intuitive algorithm is 1*2*3*4*5*6*7*8*9, if you want to calculate the product of 1-10000, the intuitive algorithm is difficult to achieve, and recursion can be very simple implementation. Take a look at the example:

1 def fact (n):# calculates the product of a given number to one 2     if n<=1:3         return 14     else:5         return N * Fact (n-1 )  6Print (fact (7))

The result is: 5040

Let's take a look at the recursive execution process using the example:

1 def Calc (n): 2     Print (n) 3     if n/2 > 1:4         res = calc (n/2)5     return N 6 Calc (8)

The result is:

1 82 4.03 2.0

Look again at this example:

1 defCalc (n):2     Print(n)3     ifN/2 > 1:4res = Calc (n/2)5         Print('Res:', Res)6     Print("N:", N)7     returnN8Calc (8)

The result is:

1 82 4.03 2.04 n:2.05 res:2.06 n:4.07 res:4.08 N:8

Second, generator

The generator is a function with a yield statement. A function or subroutine is returned only once, but a generator can pause execution and return an intermediate result, returning a value to the caller and pausing execution. When the next () method of the generator is called, it will proceed exactly from where it left off

Here's a look at the example:

1 deffunc ():2     Print('11111111')3     yield[1]4     Print(2222222222)5     yield26     Print(3333333333)7     yield38 9ret=func ()TenR1=ret.__next__() One Print(R1) AR2=ret.__next__() - Print(R2) -R3=ret.__next__() the Print(R3)

The result is:

1 111111112 [1]3 22222222224 25 33333333336 3

Because Python's for Loop has next () calls and handles to stopiteration, using a for loop instead of a manual iteration through a generator (or an iterator of that sort) is always a lot more concise and beautiful. Cases:

1 deffunc ():2     Print('11111111')3     yield[1]4     Print(2222222222)5     yield26     Print(3333333333)7     yield38ret=func ()9  forIinchret:Ten     Print(i)

The result is the same as before.

These simple examples should give you a little idea of how the generator works. In addition to next () to get the next generated value, the user can return the value to the generator [Send ()], throw an exception in the generator, and require the generator to exit [Close ()]

Here is a simple example that shows these features.

 1  def  counter (start_at=0):  2  count = Start_at  3  while   4  val = (yield  count) if  Val is   None:  5  count = val  6  else  :  7  count + = 1 

The generator comes with an initialized value, with a 1 cumulative count for each call to the generator [next ()]. The user has the option to reset this value if they really want to call send with a new value () instead of calling next (). This generator is always running, so if you want to end it, call the Close () method. If we run this code interactively, we will get the following output:

1>>> count = Counter (5)2>>>Count.next ()354>>>Count.next ()566>>> Count.send (9)798>>>Count.next ()910Ten>>>count.close () One>>>Count.next () A Traceback (most recent): -File"<stdin>", Line 1,inch<module> -Stopiteration

Python function recursion and generator

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.