Suppose I have a list:
a = [1, 1, 2, 2, 3, 4, 5, 6]
There are 2 modes here, 1 and 2. How would I make it so my function returns either 1 or 2 at random so it would return 1 sometimes and 2 the other times. Or if there were 3 or more modes in the list it would return 1 of these at random. I already have a function which returns the mode from this list but it returns 1 every time.
def my_mode(alist):
counter = dict()
highest = -1
high_item = []
for item in alist:
if item not in counter:
counter[item] = 1
else:
counter[item] = counter[item] + 1
if counter[item] > highest:
highest = counter[item]
high_item = item
return high_item
or alternatively you can use statistics.mode(a) but this still doesn't randomize the output between 1 and 2.
Aucun commentaire:
Enregistrer un commentaire