def mode(given_list):
highest_list = []
highest = 0
index = 0
for x in range(0, len(given_list)):
occurrences = given_list.count(given_list[x])
if occurrences > highest:
highest = occurrences
highest_list[0] = given_list[x]
elif occurrences == highest:
highest_list.append(given_list[x])
The code is meant to work out the mode of a given list. I do not understand where I am going wrong.
Exact Error I am receiving.
line 30, in mode
highest_list[0] = given_list[x]
IndexError: list assignment index out of range
The problem is that you have an empty list originally:
highest_list = []
And then in the loop you try to access it at index 0:
highest_list[0] = ...
It's impossible, because it's an empty list and so is not indexable at position 0.
A better way to find the mode of a list is to use a collections.Counter
object:
>>> from collections import Counter
>>> L = [1,2,3,3,4]
>>> counter = Counter(L)
>>> max(counter, key=counter.get)
3
>>> [(mode, n_occurrences)] = counter.most_common(1)
>>> mode, n_occurrences
(3, 2)
As far as getting the mode, you can just use a Counter from the collections library
from collections import Counter
x = [0, 1, 2, 0, 1, 0] #0 is the mode
g = Counter(x)
mode = max(g, key = lambda x: g[x])
At that point, at the start of the loop, highest_list
is empty, so there's no first index. You can initialize highest_list
as [0]
so that there is always at least one "highest value."
That said, you can accomplish this more simply as follows:
def mode(given_list):
return max(set(given_list), key=given_list.count)
This will find the highest item in the passed given_list
, based on each item's count()
in it. Making a set
first ensures that each item is only counted once.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.