0

I made a frequency table to count items from a given list. Example input: list[1, 2, 1, 1, 0, 8, 8]

frequencyTable() returns a dict. of items from the list with their occurence counted. printTable() prints that return. With my example it would be sth. like:

1 : 3
8 : 2
2 : 1
0 : 1

And lastly (and where I'm stuck) the function mostFrequentValues() is supposed to output the n most frequent numbers of the returned frequency table in a list. The return of my example with n = 2 should be [1, 8]. My version returns tuples but I need just a list of the values, without anything else. Since I'm new to Python I did not find any way to filter the rest out yet.

def frequencyTable(list):
    freq_table = {}
    for items in list:
        freq_table[items] = list.count(items) 
    return freq_table
def printTable(freq_table):
    for key, value in freq_table.items():
        print(key, ' : ', value)
def mostFrequentValues(freq_table, n):
    most_frequent = Counter(freq_table).most_common(n)
    return most_frequent
Moepius
  • 17
  • 4
  • 1
    I'm not sure why you write these functions, when `Counter` already has all this functionality. is it just for learning ? – Rabinzel Apr 23 '22 at 13:29
  • https://docs.python.org/3/library/collections.html#collections.Counter in case you wonder what `Counter` is, and where you get it from. – Carlos Horn Apr 23 '22 at 13:38
  • Yes, it's only for learning purpose (an exercise from a python course to be precise) – Moepius Apr 23 '22 at 16:59

1 Answers1

0

You can do list comprehension to return the first element of the tuples:

from collections import Counter
def mostFrequentValues(freq_table, n):
    most_frequent = Counter(freq_table).most_common(n)
    return [i[0] for i in most_frequent]

Output (with n = 2):

[1, 8]
Nin17
  • 2,821
  • 2
  • 4
  • 14