so I’m trying to open a text file with a poem and see how many times I can spell the word “GOOD” with the letter in the text file in each line, but I get the following error:
Traceback (most recent call last):
File "./soup.py", line 11, in <module>
print( "\n".join( [("Case #%d: %d" % (i, parse(file[i]))) for i in range(1, len(file))]))
File "./soup.py", line 7, in parse
d['O'] /= 2
KeyError: 'O'
source:
#!/usr/bin/python
def parse(string):
d = {'G' : 0, 'O' : 0, 'D' : 0}
d = {s: string.count(s) for s in string if s in d }
d['O'] /= 2
return min(d.values())
file = open("poem.txt").read().split('\n')
print( "\n".join( [("Case #%d: %d" % (i, parse(file[i]))) for i in range(1, len(file))]))
Are you sure your line 7 reads d[‘O’]?
The error message suggests it reads d[‘C’]
The problem is that if the line contains no ‘O’ characters then ‘O’ will not be in d and this gives an error.
The second time d is defined will create a new dictionary which will not include the ‘O’ key.
(You might find it more efficient to do d = {s: string.count(s) for s in d })
(I also love the alternative suggestion of using collections.Counter. However, if you are interested in speed then my timing measurements show that for a 10 million character string it takes 3 seconds to make the Counter object, but only 0.012 seconds per call to string.count)