Podo
Podo

Reputation: 709

Stop printing of generator expression once empty

I have a fairly basic code that tests both generator functions and generator expressions. It works like a charm, but I can't figure out how to get the generator expression genPairs to stop printing once it reaches the final value. I have tried using for i in range (0, xyz) for xyz being a number of different len() calls, but I've gotten an error anytime I try to use the size of my generator expression. To save you time, my question is about the final 3 lines of the python code.

Code:

import re
def genLetters(string):

    for letter in string:
        yield letter


letterTable = {}
print("Input your string")
regex = re.compile('[^a-zA-Z]')
inStr = input()
newString = regex.sub("",inStr).lower()
test = genLetters(newString)

for i in range(0,len(newString)):
    temp = next(test)
    if temp  not in letterTable:
        letterTable[temp] = 1
    else:
        letterTable[temp] +=1


letterTable = iter(sorted(letterTable.items()))

genPairs = (item for item in letterTable)
while genPairs:
    print(next(genPairs))

Output:

    Input your string
porkpork
('k', 2)
('o', 2)
('p', 2)
('r', 2)
Traceback (most recent call last):
  File "hw2-1.py", line 27, in <module>
    print(next(genPairs))
StopIteration

What can I do to get it to not print the traceback...stop iteration nonsense? Is there a way to limit

Upvotes: 0

Views: 187

Answers (2)

jpp
jpp

Reputation: 164693

There appears to be a large amount of unnecessary code and generators which don't yield any benefit. I've cleaned it up for you below.

This solution removes the need for iterating generators, and includes collections.Counter to perform the counting for you.

from collections import Counter
import re

print('Input your string')
regex = re.compile('[^a-zA-Z]')
inStr = input()
newString = regex.sub('', inStr).lower()

letterTable = Counter(newString)

for k in sorted(letterTable):
    print((k, letterTable[k]))

Upvotes: 0

wim
wim

Reputation: 362776

A for loop will exhaust the generator and catch the StopIteration for you:

for element in genPairs:
    print(element)

Using the code while genPairs doesn't make sense, because the generator expression itself will always be truthy.

Upvotes: 2

Related Questions