Back to Freecodecamp

Challenge 132: Purge Most Frequent

curriculum/challenges/english/blocks/daily-coding-challenges-python/691f7773cddba1caf1bf5ecb.md

latest1.9 KB
Original Source

--description--

Given an array of values, remove all occurrences of the most frequently occurring element and return the resulting array.

  • If multiple values are tied for most frequent, remove all of them.
  • Do not change any of the other elements or their order.

--hints--

purge_most_frequent([1, 2, 2, 3]) should return [1, 3].

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(purge_most_frequent([1, 2, 2, 3]), [1, 3])`)
}})

purge_most_frequent(["a", "b", "d", "b", "c", "d", "c", "d", "c", "d"]) should return ["a", "b", "b", "c", "c", "c"].

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(purge_most_frequent(["a", "b", "d", "b", "c", "d", "c", "d", "c", "d"]), ["a", "b", "b", "c", "c", "c"])`)
}})

purge_most_frequent(["red", "blue", "green", "red", "blue", "green", "blue"]) should return ["red", "green", "red", "green"].

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(purge_most_frequent(["red", "blue", "green", "red", "blue", "green", "blue"]), ["red", "green", "red", "green"])`)
}})

purge_most_frequent([5, 5, 5, 5]) should return [].

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(purge_most_frequent([5, 5, 5, 5]), [])`)
}})

purgeMostFrequent([10, 12, 7, 3, 7, 7, 12, 12]) should return [10, 3].

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(purge_most_frequent([10, 12, 7, 3, 7, 7, 12, 12]), [10, 3])`)
}})

--seed--

--seed-contents--

py
def purge_most_frequent(arr):

    return arr

--solutions--

py
def purge_most_frequent(arr):
    freq = {}
    for val in arr:
        freq[val] = freq.get(val, 0) + 1

    max_freq = max(freq.values())
    to_remove = {val for val, count in freq.items() if count == max_freq}

    return [val for val in arr if val not in to_remove]