infile = open('numbers.txt','r')
c = 0
for i in infile:
if int(i) > c:
c = int(i)
hist = [0]*c
for i in infile: #checking
ii = int (i)-1
hist[ii] += 1 # problem area seemingly
for i in range(c):
print(str(i+1),':',end=' ')
print(str(hist[i]))
The purpose of the code above is to open number.txt, which has a 100 numbers, all within range(1,101), all with '\n' characters at their ends, and to count the number of times each number has been encountered.
First the greatest number in the file is found, then a list with the number of element equals the greatest number in the file, is made with all elements initially set to zero. Then the numbers are checked. All numbers in file are integers.
If the greatest number contained in the file is 100, then the hist[] list has initially 100 elements which are all 0.
During checking, say if a number 78 is encountered, the element with index [77] ie hist[77] is updated from value 0 to 1. If 78 is encountered again, hist[77] is changed from 1 to 2.
This way whatever number occurs in the file, each occurring number has a counter (also numbers that don't appear but are less that the greatest occurring no. have counters but thats not a problem).
Having checked that the correct file is being opened, the hist list is initially being set up properly, the problem is that the values of the hist[] list are not getting increment when the corresponding number is being encountered. When i print the list at the end, all values are still zero.
I am using Python 3.4.3. Both the script and 'numbers.txt' are on my desktop. Any help appreciated.