Easier answer using dictionary

Screen Link: https://app.dataquest.io/m/1013/functions%3A-intermediate-practice-problems/6/most-frequent-and-least-frequent

easier answer

def most_least_frequent(values):
    d={}
    for v in values:
        if v not in d:
            d[values.count(v)]=v
    return max(d),min(d)
2 Likes

Hello @LindyHan Yes better, please also attach mission link with that.

Even though it passes the answer checker, this code may not be what you intended it to be.
It can cause error prone coding in future.

There are 2 unusual things:

  1. Assigning v to the dictionary value and counts to the dictionary key
  2. Checking if the v from values is in the keys of d using if v not in d
    .
def most_least_frequent(values):
    d={}
    for v in values:
        if v not in d:
            print('v not in d!')
            d[values.count(v)]=v
            print(d)
    return max(d),min(d)

Try adding the 2 prints and see that v is always not in d. This check will never return False (in this question). Because in checks amongst they keys in a dictionary, but you stored the v you are checking for in the values of the dictionary, so it can only be by coincidence that v matches the dictionary key.

>>> d = {}
>>> d['a'] = 1
>>> 'a' in d
True
>>> 'b' in d
False
>>> d.__contains__('a')
True
>>> d.__contains__('b')
False
>>> d.__contains__('1')
False

in membership is syntactic sugar for __contains__ (python has many other dunder methods which implement syntactic sugars. eg. [] for __getitem__ or __setitem__) . The above example is to show how in is called under the hood, and the last line of d.__contains__('1') proves that in will not check dictionary values, but keys instead.

Your solution ignores the values associated with the max and min counts, exactly what is required in this task, but the DQ answer which creates a dictionary with meaningful key-values could be more useful practically, and more extensible because the median, or other percentiles could be extracted too if required some day. Also, the values associated with those counts are stored intact in the keys.

If you ever needed the value associated with the counts only, max(set(values), key=values.count) or min is concise. It is required when building Decision Trees, where you want to find the majority appearing class at a leaf, and what the class is, is more important than the counts that made it the majority.

3 Likes