I have a file called !input.txt containing multiple lines, each line is a random integer from 0 to 10.
I want to write a program that reads the file and calculate how many times each integer (0-10) appears in the file. For example, if there are four “0”, two “3” and five “7” in my input file, the program will print out something like this:
Number of occurrences of 0: 4
Number of occurrences of 1: 0
Number of occurrences of 2: 0
Number of occurrences of 3: 2
Number of occurrences of 4: 0
Number of occurrences of 5: 0
Number of occurrences of 6: 0
Number of occurrences of 7: 5
Number of occurrences of 8: 0
Number of occurrences of 9: 0
Number of occurrences of 10: 0
Here is my code:
mylist = [0,1,2,3,4,5,6,7,8,9,10]
countlist = []
inFile = open("!input.txt", "r")
count = 0
for digit in mylist:
for line in inFile:
if digit == int(line):
count = count + 1
countlist.append(count)
count = 0
#Print out the result#
for i in range(11):
print("Number of occurrences of {0}: {1}".format(i, countlist[i]))
The result comes out like this:
Number of occurrences of 0: 4
Number of occurrences of 1: 0
Number of occurrences of 2: 0
Number of occurrences of 3: 0
Number of occurrences of 4: 0
Number of occurrences of 5: 0
Number of occurrences of 6: 0
Number of occurrences of 7: 0
Number of occurrences of 8: 0
Number of occurrences of 9: 0
Number of occurrences of 10: 0
I guess there’s something wrong with my nested for loop, but I couldn’t figure out what it is. Please help.
One problem with your loop is that you can only loop over
inFileonce, because it’s an open file object. After you’ve read through it on the first pass, you’re at the end of the file, and there are no more lines to read. So the variantshould work. However, this requires both reading all the lines into memory, and doing a loop for each digit. More efficient would be to preallocate the space and do one pass:
Better still, use a
defaultdictorCounter:leading up to the semi-magical:
PS: don’t forget to close your file objects. I’m too lazy to go back and do it myself, but you should. :^)