pythonintermediate10 minutes

Refactor a Function to Compute Unique Elements Frequency

Improve the provided Python function that calculates the frequency of unique elements in a list. Refactor the code for better readability, efficiency, and Pythonic style without changing its behavior.

Challenge prompt

You are given a Python function that takes a list of elements and returns a dictionary with the frequency count of each unique element. The current function works correctly but is verbose and not optimized. Your task is to refactor the code for clarity, conciseness, and performance, using best Python practices while preserving the original functionality.

Guidance

  • Consider using Python collections or built-in library functions to simplify frequency counting.
  • Avoid unnecessary loops or repeated operations like multiple .count() calls on the list.
  • Make sure the output dictionary key order is maintained if possible, or clearly document if it changes.

Hints

  • Look into the collections.Counter class for an efficient frequency dictionary.
  • Try to avoid counting elements multiple times by iterating the list once.
  • Consider readability improvements such as meaningful variable names and removing redundant code.

Starter code

def count_frequencies(lst):
    freq = {}
    for item in lst:
        if item not in freq:
            freq[item] = lst.count(item)
    return freq

Expected output

{'apple': 3, 'banana': 2, 'orange': 1} # e.g. input ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']

Core concepts

dictionarycollections.Countercode refactoringalgorithm efficiency

Challenge a Friend

Send this duel to someone else and see if they can solve it.