3

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?

vencra
  • 63
  • 7
  • 1
    Possible duplicate of [Python most common element in a list](http://stackoverflow.com/questions/1518522/python-most-common-element-in-a-list) – Kind Stranger Apr 28 '17 at 14:17

1 Answers1

2

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.

MSeifert
  • 145,886
  • 38
  • 333
  • 352
  • 1
    I did not expect to get such an explanatory and instructive answer. Thank you so much! And also thank you for teaching "key" usage. – vencra Apr 28 '17 at 19:51