I have done this question before for my homework assignment using the Counter. Now, I am studying this same question for finals. I would like to memorize dictionaries and not Counters for this final. I tried solving this problem using a dictionary instead.
So the problem was to create function name repeatCount. The purpose of the function is to read each line of the input file, identify the number of words on the line that occur more than once, and write that number to a line in the output file.
The input file text is this:
Woke up this morning with an ache in my head
I splashed on my clothes as I spilled out of bed
I opened the window to listen to the news
But all I heard was the Establishment Blues
My output file should look like this:
0
2
3
2
The correct output is:
0
1
2
0
So here is my code now. What particular part of my code causes Python to produce me the wrong answer?:
def repeatCount(inFile, outFile):
inF = open(inFile, 'r')
outF = open(outFile, 'w')
d = {}
for line in inF.readlines():
count = 0
words = line.split()
for word in words:
if word not in d:
d[word] = 1
elif word in d:
d[word] += 1
if d[word] > 1:
count += 1
outF.write(str(count) + "\n")
print(repeatCount('inputFile.txt', 'outputFile.txt'))