Python Builder and recursion

Source: Internet
Author: User
Tags for in range

Generator 1. Defining
    • Problem: Python will put objects into memory, we define variables, lists, etc. will occupy the corresponding address block in memory, so when the memory capacity is certain, the capacity of the list is limited by memory, and if we create a list of 2 million elements, not only will occupy a large address space, If we just need to access the previous elements, then the space behind the elements will be wasted. Based on this problem, the generator can be solved very well.
    • Workaround: The generator can generate an iterative object based on a particular algorithm, and when we call this object, we can continually extrapolate the subsequent elements during the loop, after the call terminates, no longer loops, and the subsequent elements are not created, which solves the problem above
    • Definition: A generator is a function that remembers the position of the last time it was returned in the body of the function. A second (or nth) call to the generator function jumps to the middle of the function, and all local variables that were last called remain unchanged. The generator not only "remembers" its data state; the generator also "remembers" its location in flow control constructs (in imperative programming, this construct is not just a data value).
    • Generator Features: The generator is a function, and the parameters of the function are preserved. When iterating to the next invocation, the parameters used are left for the first time, that is, the parameters of all function calls are preserved the first time they are called, not the newly created
2. Create

In a function, if you use the keyword yield, this function is a generator, his execution will be different from other ordinary functions, the function returns an object, not a result value, if you need to get the result value, you need to call the next () function
As follows:

# define a generator func def func ():     Print (111)     # Print the results of each loop using print for easy      viewing yield 1    print(222)      Yield 2    print(333)    yield 3= func ()

Start the loop below

Method 1: Use a For loop

 for inch Res: Print (i) output:111 # Generator First Pring1 #yield returned object value 222 # Generator Second Pring2 #yield returned object value 333 # Generator Third Pring3 #yield return the object value


Method 2: Use Next () iteration

Print("1". Center (10,'*')) R1= Res.__next__()#Enter the function to find yield, and go to the data behind yieldPrint(R1)Print("2". Center (10,'*')) R2= Res.__next__()#Enter the function to find yield, and go to the data behind yieldPrint(R2)Print("3". Center (10,'*')) R3= Res.__next__()#Enter the function to find yield, and go to the data behind yieldPrint(R3) output results:1*****1111****2*****2222****3*****3333

The ps:for loop automatically calls the next () method, and whenever the next function of the iterator is called, the generator function runs to yield, returns the value after yield and pauses in this place, and all States are held until the next function is called. or an abnormal loop exits, so if a yield in a generator is iterated, the next yield is read Next, so the for loop and next function cannot be mixed

    • Builder application Examples: permutations and combinations
#!/usr/bin/env python#-*-coding:utf-8-*-#pyversion:python3.5#Owner:fuzj#Combination BuilderdefPerm (items, n =None):ifN isnone:n=len (items) forIinchRange (len (items)): v= Items[i:i+1] # Use string shards to take the elementsifN==1: # If it is the first loop, print the first character and the second characteryieldvElse: Rest= Items[:i] + items[i+1:] #i+1 indicates that the value of the last running state i is sliced, taking the following value character forPinchPerm (Rest, n-1): # recursive call to this generator, loop, this is the specific rule described earlieryieldV +P#Permutation generatorsdefComb (items, n =None):ifN isnone:n=len (items)Else:         forIinchRange (len (items)): v= Items[i:i+1] # Use string shards to take the elementsif1 = =N: # first loop, print first and second charactersyieldvElse: Rest= Items[i+1:]                    forCinchComb (rest, n-1): # recursive call to this generator, loop, this is the specific rule described earlieryieldV +CP= Perm ('ABCD', 2) C= Comb ('ABCD', 2)Print('Combination'. Center (10,"=")) forIinchP:Print(i)Print('Arrange'. Center (10,"=")) forIinchC:Print(i) Output effect:= = = Combination = =ABACADBABCBDCACBCDDADBDCOrder = = = = =ABACADBCBDCD

Recursive

The understanding of recursion can be analyzed slowly from a requirement

    • Requirement: Calculate 1*2*3* .... The value of the *1000

This is a simple calculation of the need for stacking, and you can use a function to implement it if you do not contact recursion.

def func (ARG):    res = arg    for in range (1, arg):        *= 1     return Res

This function passes the number within the loop arg, and then multiplies the final return result, which is simpler if the recursive method is used

def Fun (ARG):     if arg = =1        :return  arg    return arg * FUN (ARG-1)

    • This function finds that the function eventually return the expression of the function itself, and if it calculates the factorial within 5, he runs as follows:
      1) Fun (5) Call function fun () function, at this time arg = 5,5>1, so will return 5 * Fun (4)
      2) Fun (4) will call the fun () function, at this time arg=4,4>1, so will return 4 * Fun (3)
      3) Fun (3) will call the fun () function, at this time arg=3,3>1, so will return 3 * Fun (2)
      4) Fun (2) will call the fun () function, at this time arg=2,2>1, so will return 2 * Fun (1)
      5) Fun (1) will call the fun () function, at this time arg=1,1=1, so will return 1
      6) when fun (1) returns the value to Fun (2), then Fun (2) =fun (1) *2=2, continue back up to Fun (3)
      7) when fun (2) returns the value to Fun (3), then Fun (3) =fun (2) *3=6, continue back up to fun (4)
      8) when fun (3) returns the value to Fun (4), then Fun (4) =fun (3) *4=24, continue back up to fun (5)
      9) when fun (4) returns the value to Fun (5), this time fun (5) =fun (4) *5=120, and finally the result

    • Characteristics

Create a condition for recursion

1. A baseline condition: the condition of a recursive termination, which needs to be processed at the beginning of recursion.
2. A series of rules: make every call to a recursive function go up to this baseline condition

Recursion can improve the readability of your code, but it is less efficient to run. In the process of recursive invocation, the system opens up a stack for each layer's return point, local quantity and so on. Too many recursion times can cause stack overflow and so on.

Python Builder and recursion

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.