Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions

  




 

 

Generator Example

Let's look at an example which summarizes some details, yielding the summaries. Assume we have the following list of tuples. We want to know how many red spins separate a black spin, on average. We need a function which will yield the count of gaps as it examines the spins. We can then call this function repeatedly to get the gap information.

Example 18.1. generator.py

spins = [('red', '18'), ('black', '13'), ('red', '7'), 
    ('red', '5'), ('black', '13'), ('red', '25'), 
    ('red', '9'), ('black', '26'), ('black', '15'), 
    ('black', '20'), ('black', '31'), ('red', '3')]

def countReds( aList ):
    count= 0
    for color,number in aList:
        if color == 'black':
            yield count
            count= 0
        else:
            count += 1
    yield count
    
gaps= [ gap for gap in countReds(spins) ]
print gaps
1

The spin variable defines our sample data. This might be an actual record of spins.

2

We define our gapCount( aList ) function. This function initializes count to show the number of non-black's before a black. It then steps through the individual spins, in the order presented. For non-black's, the count is incremented.

3

For black spins, however, we yield the length of the gap between the last black. When we yield a result, the generator produces a result value, and also saves all the other processing information about this function so that it can be continued from this point.

When the function is continued, it resumes right after the yield statement: the count will be reset, and the for loop will advance to examine the next number in the sequence.

4

When the sequence is exhausted, we also yield the final count. The first and last gap counts may have to be discarded for certain kinds of statistical analysis.

5

This shows how we use the generator created by a function with a yield statement. In this case, we create a list comprehension; the for clause will step through the values yielded by the generator until the it exits normally. This sequence of values is collected into a list that we can the use for statistical analysis.


 
 
  Published under the terms of the Open Publication License Design by Interspire