You are not logged in.
Hello all and Happy New Year,
I have started learning python and I thought I would develop a program to find the modal class from a list of numbers. The modal class is the most frequent number in a list of numbers. My code is the following, (I leave out parts that are irrelevant to the problem and include only the part that calculates how frequent each number is):
# Find how frequently each number occurs, this only works with a sorted list
freqidx = []
freq = []
loopcount = 0
numbercount = 0
prevnumber = None
for number in numbers:
if number == prevnumber:
freq[loopcount] +=1
else:
freqidx.append(numbercount)
freq.append(1)
loopcount += 1
prevnumber = number
numbercount += 1
The numbers list was populated and sorted in ascending order earlier in the program so don't let that confuse you.
Now when I run the program I get the error:
Traceback (most recent call last):
File "Mode.py", line 54, in <module>
freq[loopcount] +=1
IndexError: list index out of range
line 54 is as you can see the suite of the if statement freq[loopcount] += 1. Does anyone know why this happens? The only thing that I could think was that the very first the for loop is run the freq list is empty and thus the error is produced but the very first time the for loop is run the if statement should be false thus the else statement should be executed instead. If I add a number in the freq list, the error is not produced, which is confusing.
Any help is appreciated.
Last edited by baion baion (2010-01-01 16:59:12)
Offline
Remembering lists in python are zero-indexed, you can see on the first iteration that the loopcount does not reflect the length of freq:
freq.append(1) loopcount += 1
freq will have a single element (i.e., an element at freq[0]), while loopcount will be 1. At the point you attempt to modify the count
freq[loopcount] +=1
loopcount will always exceed the length of the freq by 1, hence the IndexError.
The simplest adjustment would be to initialise `loopcount' to -1.
Last edited by chpln (2010-01-01 12:58:52)
Offline
Thank you very much for pointing out a rather dumb mistake. It works like a charm now.
Offline