Python Forum
Program to find Mode of a list
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Program to find Mode of a list
#1
I am currently making a program to find the Mode of a list by count() function.

Input =input("Please enter the data: ")
Data = Input.split(",")

#Storing all integers in this empty list
Data1 = []
#Converting all elements in list to integers
for x in Data:
    Data1.append(int(x))

#Arranging the list in ascending order
Data1.sort(reverse=False)
print(Data1)

#Getting the length of the list
Length = len(Data1)

#Finding Mode

for l in range(Length):
    Occurrence = Data1.count(Data1[l])
I figured out how to find the occurrence of each element of a list.

But I don't know how to compare them since all of the occurrences of each element will be stored in a single variable 'Occurence'.

Please help me with this project.

Thank you!
"He who conquers himself is the mightiest warriors" - Marcus Aurelius
Stay Positive, Work Hard!
Reply
#2
To fix some stuff and make it look better.
Try not to use capital letters for variables.
On line 2 make a list,so can use that list for rest of stuff to,no need to append to new list.
input_data = '1,2,3,1,2,2' #input("Please enter the data: ")
data = [int(i) for i in input_data.split(",")]
revers_data = reversed(data)
len_data = len(data)
Test.
>>> data
[1, 2, 3, 1, 2, 2]
>>> revers_data
<list_reverseiterator object at 0x000002D212ABD360>
>>> list(revers_data)
[2, 2, 1, 3, 2, 1]
>>> len_data
6
>>> # Count a value in list 
>>> data.count(2)
3
To count all occurrences in data list,can do it like this.
>>> from collections import Counter
>>> 
>>> count_data = Counter(data)
>>> count_data
Counter({2: 3, 1: 2, 3: 1})
>>> count_data.most_common(1)
[(2, 3)]
>>> count_data.most_common(2)
[(2, 3), (1, 2)]
So when do this most_common(1) it will find only the most common which is 2 that occur 3 times in data list.
Reply
#3
(Sep-11-2023, 02:43 PM)snippsat Wrote: To fix some stuff and make it look better.
Try not to use capital letters for variables.
On line 2 make a list,so can use that list for rest of stuff to,no need to append to new list.
input_data = '1,2,3,1,2,2' #input("Please enter the data: ")
data = [int(i) for i in input_data.split(",")]
revers_data = reversed(data)
len_data = len(data)
Test.
>>> data
[1, 2, 3, 1, 2, 2]
>>> revers_data
<list_reverseiterator object at 0x000002D212ABD360>
>>> list(revers_data)
[2, 2, 1, 3, 2, 1]
>>> len_data
6
>>> # Count a value in list 
>>> data.count(2)
3
To count all occurrences in data list,can do it like this.
>>> from collections import Counter
>>> 
>>> count_data = Counter(data)
>>> count_data
Counter({2: 3, 1: 2, 3: 1})
>>> count_data.most_common(1)
[(2, 3)]
>>> count_data.most_common(2)
[(2, 3), (1, 2)]
So when do this most_common(1) it will find only the most common which is 2 that occur 3 times in data list.

Oh ok this is how you do it. I had no idea about Counter()

Thanks for letting me know. I will use it!
"He who conquers himself is the mightiest warriors" - Marcus Aurelius
Stay Positive, Work Hard!
Reply
#4
Why are you converting the values to int? You aren't doing any arithmetic.

A way to do this without using any imports.
def mode(items):
    counts = {}
    for item in items:
        counts[item] = counts.get(item, 0) + 1
    return max(counts.items(), key=lambda x: x[1])[0]


while items := input("Enter values separated by comma: "):
    print("Mode = ", mode(item.strip() for item in items.split(",")))
Using a defaultdict.
from collections import defaultdict


def mode(items):
    counts = defaultdict(lambda: 0)
    for item in items:
        counts[item] += 1
    return max(counts.items(), key=lambda x: x[1])[0]


while items := input("Enter values separated by comma: "):
    print("Mode = ", mode(item.strip() for item in items.split(",")))
And using Counter.
from collections import Counter


def mode(items):
    return Counter(items).most_common[0]


while items := input("Enter values separated by comma: "):
    print("Mode = ", mode(item.strip() for item in items.split(",")))
Reply
#5
(Sep-11-2023, 03:30 PM)deanhystad Wrote: Why are you converting the values to int? You aren't doing any arithmetic.

A way to do this without using any imports.
def mode(items):
    counts = {}
    for item in items:
        counts[item] = counts.get(item, 0) + 1
    return max(counts.items(), key=lambda x: x[1])[0]


while items := input("Enter values separated by comma: "):
    print("Mode = ", mode(item.strip() for item in items.split(",")))
Using a defaultdict.
from collections import defaultdict


def mode(items):
    counts = defaultdict(lambda: 0)
    for item in items:
        counts[item] += 1
    return max(counts.items(), key=lambda x: x[1])[0]


while items := input("Enter values separated by comma: "):
    print("Mode = ", mode(item.strip() for item in items.split(",")))
And using Counter.
from collections import Counter


def mode(items):
    return Counter(items).most_common[0]


while items := input("Enter values separated by comma: "):
    print("Mode = ", mode(item.strip() for item in items.split(",")))

No actually it is required, since I will be finding Mean, Median and Mode.

I didn't want to put the whole code which includes Mean and Median.

So I converted all the elements in the list from string to integer
"He who conquers himself is the mightiest warriors" - Marcus Aurelius
Stay Positive, Work Hard!
Reply
#6
If you want to convert values to int then compute the mode fine. If you pass strings and convert the result to an int, fine. Mode doesn't care. If you want to convert the inputs to floats, oh, I guess mode would care.

You should write you code using functions.

You might want to learn about list comprehensions. This:
Input =input("Please enter the data: ")
Data = Input.split(",")
 
#Storing all integers in this empty list
Data1 = []
#Converting all elements in list to integers
for x in Data:
    Data1.append(int(x))
Becomes:
data = [int(x) for x in input("Please enter the data: ").split(",")]
Python naming convention does not use uppercase letters for variables UNLESS the variable is global, then the name should be all uppercase. Since you are just starting, might as well start using the conventions everyone else uses (PEP8).
Reply
#7
(Sep-11-2023, 04:13 PM)deanhystad Wrote: If you want to convert values to int then compute the mode fine. If you pass strings and convert the result to an int, fine. Mode doesn't care. If you want to convert the inputs to floats, oh, I guess mode would care.

You should write you code using functions.

You might want to learn about list comprehensions. This:
Input =input("Please enter the data: ")
Data = Input.split(",")
 
#Storing all integers in this empty list
Data1 = []
#Converting all elements in list to integers
for x in Data:
    Data1.append(int(x))
Becomes:
data = [int(x) for x in input("Please enter the data: ").split(",")]
Python naming convention does not use uppercase letters for variables UNLESS the variable is global, then the name should be all uppercase. Since you are just starting, might as well start using the conventions everyone else uses (PEP8).

Ohh, I didn't know that such a big code can be converted into just one line. I didn't know because I have only learnt about variables, operations, lists, tuples and loops. Now that I know, I will make sure to use them.

I even didn't know we shouldn't use Capital letter for Variables. I will make sure to write it all in lower case from next time

Thanks!
"He who conquers himself is the mightiest warriors" - Marcus Aurelius
Stay Positive, Work Hard!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  find random numbers that are = to the first 2 number of a list. Frankduc 23 3,252 Apr-05-2023, 07:36 PM
Last Post: Frankduc
  Find (each) element from a list in a file tester_V 3 1,238 Nov-15-2022, 08:40 PM
Last Post: tester_V
  read a text file, find all integers, append to list oldtrafford 12 3,617 Aug-11-2022, 08:23 AM
Last Post: Pedroski55
  find some word in text list file and a bit change to them RolanRoll 3 1,549 Jun-27-2022, 01:36 AM
Last Post: RolanRoll
  How to find the second lowest element in the list? Anonymous 3 2,029 May-31-2022, 01:58 PM
Last Post: Larz60+
  Python Program to Find the Total Sum of a Nested List vlearner 8 4,938 Jan-23-2022, 07:20 PM
Last Post: menator01
  Find the highest value of a list Menthix 4 1,896 Oct-29-2021, 02:32 PM
Last Post: Menthix
  things that work in terminal mode but not in sublime mode alok 4 2,897 Aug-11-2021, 07:02 PM
Last Post: snippsat
  Find Common Elements in 2 list quest 4 2,766 Apr-14-2021, 03:57 PM
Last Post: quest
  unable to find module in su mode? korenron 2 1,929 Jan-10-2021, 07:41 PM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020