vencra
vencra

Reputation: 63

Find the most frequently occurring digit in a list

I'm trying to solve the following problem:

Compose a function that takes a list of single digits (entered at the command-line when running the program) and find the digit entered most frequently.

For example, the following command:

$ python frequency.py 4 6 7 7 0 5 9 9 4 9 8 3 3 3 3

Should return 3 as the result

I figured I could solve this problem using a recursive function and a for loop, but my attempt is not providing the correct result.

def frequency2(a):
    a[0:1] = []
    b = a
    if a == []:
        return []
    else:
        return [[a[0]] + [b.count(a[0])]] + frequency2(a[1:])

aa = sys.argv

print frequency2(aa)

What am I doing wrong?

Upvotes: 3

Views: 1207

Answers (1)

MSeifert
MSeifert

Reputation: 152795

Probably the easiest way is to use collections.Counter and simply pass in sys.argv:

frequency.py file:

import collections
import sys

print(collections.Counter(sys.argv).most_common(1)[0][0])

This gives a correct answer when called from the command line:

$ python frequency.py 1 2 3 4 5 6 7 8 9 1 2 3 1 2 1
1

What am I doing wrong?

You do build a list of values and counts but you don't make any attempt to get the maximum of it. You could for example use max with a key (because you want the maximum count) after calling the frequency function. Just change your last line to:

print(max(frequency2(aa), key=lambda x: x[1])[0])

The [0] is to get the actual item of the item-frequency sublist.

Upvotes: 2

Related Questions