Need Mode program without using dictionary

This is the place for queries that don't fit in any of the other categories.

Need Mode program without using dictionary

Postby john727377 » Thu Apr 03, 2014 1:22 am

Could anybody help me in writing the mode program without using dictionary in lists:
Below is the program with dictionaries:

Code: Select all

def mode(alist):
    countdict={}
    for item in alist:
        if item in countdict:
            countdict[item]=countdict[item]+1
        else:
            countdict[item]=1
    countlist=countdict.values()
    maxcount=max(countlist)
    modelist=[]
    for item in countdict:
        if countdict[item]==maxcount:
            modelist.append(item)
    return modelist

john727377
 
Posts: 4
Joined: Tue Feb 04, 2014 3:42 am

Re: Need Mode program without using dictionary

Postby Mekire » Thu Apr 03, 2014 2:53 am

I would probably do something like this, but it is still technically using a dictionary. You need to do it without a dictionary?

Code: Select all
from collections import Counter

def my_mode(alist):
    count = Counter(alist)
    highest_count = max(count.values())
    return [item for item in count if count[item]==highest_count]

-Mek
User avatar
Mekire
 
Posts: 1018
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan

Re: Need Mode program without using dictionary

Postby stranac » Thu Apr 03, 2014 6:53 am

An alternative way to get max count might be using max in combination with list.count
That would be pretty inefficient, but if you can't use a dict...(I'm guessing homework?)
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
stranac
 
Posts: 1212
Joined: Thu Feb 07, 2013 3:42 pm


Return to General Coding Help

Who is online

Users browsing this forum: Baidu [Spider] and 4 guests