user300
user300

Reputation: 465

Finding the mode and frequency of items in a Python list

How would you find the mode and frequency of items in a Python list?

This is what I have so for:

elif user_option == 7:
    for score in scores_list:
        count = scores_list.count(score)
        print ("mode(s), occuring" + str(count) + ":")
        print(score)

What I need to do is print out the scores that appear the most if the user inputs a set of scores where 2 appear at the same amount of time and I also have to display the actual score. But this is what I get when I test it:

Select an option above:7
mode(s), occuring2:
45.0
mode(s), occuring2:
45.0
mode(s), occuring1:
67.0

Upvotes: 0

Views: 5550

Answers (2)

Taruchit
Taruchit

Reputation: 5

#Here is a method to find mode value from given list of numbers
#n : number of values to be entered by the user for the list
#x : User input is accepted in the form of string
#l : a list is formed on the basis of user input

n=input()
x=raw_input()
l=x.split()
l=[int(a) for a in l]  # String is converted to integer
l.sort() # List is sorted
[#Main code for finding the mode
i=0
mode=0
max=0
current=-1
prev=-1
while i<n-1:
 if l\[i\]==l\[i+1\]:
   mode=mode+1
     current=l\[i\]
 elif l\[i\]<l\[i+1\]:
   if mode>=max:
     max=mode
     mode=0
     prev=l\[i\]
 i=i+1
if mode>max:
    print current
elif max>=mode:
    print prev][1]

'''Input
8
6 3 9 6 6 5 9 3

Output
6
'''

Upvotes: 0

Serial
Serial

Reputation: 8043

if you are trying to count frequency of an item of a list try this:

from collections import Counter
data = Counter(your_list_in_here)
data.most_common()   # Returns all unique items and their counts
data.most_common(1)  # Returns the highest occurring item

Upvotes: 2

Related Questions