Find the most common digit in the list

I am trying to solve the following problem:

Make a function that accepts a list of individual digits (entered on the command line when the program starts) and find the most frequently used digit.

For example, the following command:

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

As a result, you should return 3

I decided that I could solve this problem using a recursive function and a for loop, but my attempt does not give 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?

+4
source share
1 answer

Probably the easiest way is to use collections.Counterand just go to sys.argv:

frequency.py file:

import collections
import sys

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

This gives the 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?

, . , max key ( ) frequency. :

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

[0] - .

+3

Source: https://habr.com/ru/post/1675916/


All Articles