Saturday, August 22, 2015

Python: Generator (1)

Abstract: easy examples related to generator

Generator instead of list when get returns of the functions. Returned generator use less memory than returned list directly when the the list is huge. Here, I present two examples about return odd numbers and Fabonacci numbers.

The script:
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 22 09:05:55 2015

@author: yuan
"""

#yield return number
def generator_1(start,end):
    x=start
    while x<=end:
        if x%2==1:
            yield x
        x +=1
#
def generator_2(start,end):
    x=start
    while x<=end:
        if x%2==1:
            yield str(x) + ' rpm'
        x +=1
#
def generator_3(start,end):
    x=start
    while x<=end:
        if x%2==1:
            y=yield x
            print 'odd=', y
        x +=1

def fabonacci(number):
    n,a,b=1,0,1
    while n<=number:
        yield a
        a,b=b,a+b
        n +=1
       
if __name__=="__main__":
    #return odd number
    gt=generator_1(10,100)
    print 'The first:', next(gt)
    for i in gt:
        print i

    #return odd string
    gt=generator_2(10,100)
    for i in gt:
        print i

    #return odd
    gt=generator_3(10,100)
    print 'The first:', next(gt)
    print 'Send:', gt.send(34)
   
    #return fabonacci
    gt=fabonacci(10)
    for i in gt:
        print i
   
    print 'ok'

No comments:

Post a Comment