2011/08/10

python tips: use of chain generator

The book titled "Expert Python Programming" introduces pipeline of generators.
This concept is very useful for dividing loop codes to small parts.
Below is my example code that prints digit pyramid.

def change_value():
    for step in range(1, 10):
        yield step

def create_box(steps):
    for step in steps:
        yield (' ').join( str(step) for i in range(2 * step - 1) )

def create_pyramid(height):
    boxes = create_box(change_value())
    for step, box in enumerate(boxes):
        if step == height:
            break
        else:
            print ('').join(' ' for i in range((height - step)*2)) + box

Result of above code is ...

>>> create_pyramid(9)
                  1
                2 2 2
              3 3 3 3 3
            4 4 4 4 4 4 4
          5 5 5 5 5 5 5 5 5
        6 6 6 6 6 6 6 6 6 6 6
      7 7 7 7 7 7 7 7 7 7 7 7 7
    8 8 8 8 8 8 8 8 8 8 8 8 8 8 8
  9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9

No comments:

Post a Comment

100