Why is my generator implementation incorrect in Python?
<p>So basically i am writing a program where i need to take in a file that contains uppercase letters, that may or may not be seperated by white space or new lines, and return a generator over the letters in the file.</p>

<p>For example: </p>

<pre><code>Z FM
TM  CC
</code></pre>

<p>Would return a generator with an output of "Z","F","M","T","M","C","C"</p>

<p>The function should be a generator, so it will only load in letters at a time instead of the entire file.</p>

<p>Anyways, here is what i have so far. ANyone tell me where i went wrong?</p>

<pre><code>def buildGen:
    with open(filename) as sample:
        for word in sample:
           for ch in word:
               yield ch
</code></pre>

<p>There are a number of problems with your code:</p>

<ol>
<li><p>You're defining a function with the wrong syntax (<code>def buildGen:</code> &lt;- Parenthesis should follow).</p></li>
<li><p>Your description of the output implies that you need to address whitespace characters.</p></li>
</ol>

<p>The following outputs the output in your example (assuming your file is <code>stuff.txt</code>):</p>

<pre><code># Note `buildGen` takes now `filename`.
def buildGen(filename): 
    with open(filename) as sample:
        for word in sample:
           for ch in word:
               # Only yield non-whitespace.
               if ch.strip():
                   yield ch

print list(buildGen('stuff.txt'))
</code></pre>

python generator