Python function recursion and generator, python recursive Generator

Source: Internet
Author: User

Python function recursion and generator, python recursive Generator

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:

1 def fact (n): # Calculate the product of a given number to one. 2 if n <= return 14 else: 5 return n * fact (n-1) 6 print (fact (7 ))

Result: 5040

The following example shows the Recursive Execution Process:

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

Result:

1 82 4.03 2.0

Let's look at this example again:

1 def calc(n):2     print(n)3     if n/2 > 1:4         res = calc(n/2)5         print('res:',res)6     print("N:",n)7     return n8 calc(8)

Result:

1 82 4.03 2.04 N: 2.05 res: 2.06 N: 4.07 res: 4.08 N: 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:

 1 def func(): 2     print('11111111') 3     yield [1] 4     print(2222222222) 5     yield 2 6     print(3333333333) 7     yield 3 8  9 ret=func()10 r1=ret.__next__()11 print(r1)12 r2=ret.__next__()13 print(r2)14 r3=ret.__next__()15 print(r3)

Result:

1 111111112 [1]3 22222222224 25 33333333336 3

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:

 1 def func(): 2     print('11111111') 3     yield [1] 4     print(2222222222) 5     yield 2 6     print(3333333333) 7     yield 3 8 ret=func() 9 for i in ret:10     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.

1 def counter(start_at=0):2   count = start_at3   while True:4     val = (yield count) if val is not None:5     count = val6   else:7     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:

 1 >>> count = counter(5) 2 >>> count.next() 3 5 4 >>> count.next() 5 6 6 >>> count.send(9) 7 9 8 >>> count.next() 9 1010 >>> count.close()11 >>> count.next()12 Traceback (most recent call last):13 File "<stdin>", line 1, in <module>14 StopIteration

 

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.