repeatCount function does not give me the right answer. Why does this happen?

Jorgan

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'))
gipsy

You program will start giving you correct output if you re-set your dict for each line. ie. move d = {} to inside of your outer for loop. It will then work for your current input. But your inner for loop is still buggy as it is not ignoring the already counted duplicate words. Try again and show us your next iteration!

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related