Practice Mode: Functions: Intermediate Practice Problems. Page 7/8

Screen Link:

My Code:

 def most_least_frequent(values):
    d = {x:values.count(x) for x in values}
    max_freq = None
    min_freq = None
    max_freq_list, min_freq_list = [], []
    for k, v in d.items():
        if max_freq == None or d[k] > max_freq:
            max_freq = d[k]
            if max_freq == d[k]:
                max_freq_list.append(k)
           
        if min_freq == None or d[k] < min_freq:
            min_freq = d[k]
            if min_freq == d[k]:
                min_freq_list.append(k)
    return max_freq_list, max_freq, min_freq_list, min_freq

What I expected to happen:

to return the output: [10], 3, [20], 1 when values = [10,20,30,10,30,10]

What actually happened:
my function’s output was instead: [10], 3, [10, 20], 1

Replace this line with the output/error

When I look at the solution, I can’t understand where my code has gone wrong.

I would be grateful if someone could take a look and my code and give me some insight.

Many thanks

Take your dictionary d, assume the first key, k, is 10 and think what max_freq_list and min_freq_list should contain when k=10.

Then go through your for loop code assuming k=10 and check whether at the end of the first iteration (with k=10) the two lists max_freq_list and min_freq_list contain the same values/items as you thought or not.

That should start to help you get an insight into where your code logic starts to fail. Feel free to ask more questions after you have done the above.