Friday 5 October 2012

Generators In Python

  

Generators


         A generator is a special routine that can be used to control the iteration behavior of a loop.A generator is similar to a function returning an array. A generator has parameters, it can be called and it generates a sequence of numbers. But unlike functions, which return a whole array, a generator yields one value at a time. This requires less memory.

Generators in Python

  • Are defined with the def keyword.
  • Use the yield keyword.
  • May use several yield keywords.
  • Return an iterator.
This is an example of generators used in a python program


                 def gen():
                    x, y = 1, 2
                    yield x, y
                    x += 1
                    yield x, y


                 it = gen()

                 print it.next()
                 print it.next()

                 try:
                    print it.next()
                 except StopIteration:
                    print "Iteration finished"
 

Representing infinite sequences

       
     Generators present us with some fun ways to manipulate infinite sequences
  
                 from __future__ import generators

                 def foo():
             i = 0
             while 1:
         yield i
         i = i 
 

Recursive Generators

     
     Generator functions can call themselves recursively.
 
                from __future__ import generators

                def abc():
            a = deff()
            for i in a:
     yield i
            yield 'abc'

               def deff():
           a = ijk()
           for i in a:
       yield i
              yield 'deff'

               def ijk():
           for i in (1,2,3):
       yield i
              yield 'ijk'

 

No comments:

Post a Comment