On Wed, 28 Mar 2007 20:40:22 -0700, [EMAIL PROTECTED] wrote:

> Hi
> 
>  How can I find out the modal value in an array. That is the value
> which occurs maximum time in the sequence ..
> 
> e.g. if my array has values like [2,3,2,2,2,4,2,2]  definitely the
> maximum time 2 occurs in the array. so this function should be able to
> return 2 as a result ..
> 
> So is there any function in built in python which can do that ?

No. You need to create a frequency table, then do a reverse-lookup on the
frequency table. Assuming your data is small, this should be plenty fast
enough.

def mode(data):
    # create a frequency table
    freq = {}
    for x in data:
        freq[x] = freq.get(x, 0) + 1
    # find the maximum frequency
    F = max(freq.values())
    # return the items (one or more) with that frequency
    modes = []
    for x, f in freq.items():
        if f == F:
            modes.append(x)
    return modes

>>> mode([2,3,2,2,2,4,2,2])
[2]
>>> mode([2,3,2,3,2,3,4,1])
[2, 3]


-- 
Steven.

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to