cswork / libraryOpen practice workspace

Coding questions · Apple

Implement most_frequent_key without using max()

This question evaluates proficiency in Python fundamentals and object-oriented inheritance, focusing on frequency aggregation using a precomputed dictionary, iteration over mappings, and correct handling of ties and empty inputs.

Problem (Python OOP)

You are given two classes. Parent precomputes frequency counts of items (as strings) from an input list.

class Parent:
    def __init__(self, l):
        self.l = l
        # set of all unique string forms
        self.lf = set(str(s) for s in self.l)

        # dict: key -> count
        self.ldf = {}
        for item in self.l:
            s = str(item)
            if s not in self.ldf:
                self.ldf[s] = 1
            else:
                self.ldf[s] += 1

class Child(Parent):
    def most_frequent_key(self):
        """Return the key(s) with the highest frequency.

        Constraints:
        - You may NOT use Python's built-in `max()`.
        - Use the precomputed `self.ldf` from `Parent`.

        Return:
        - A list of the most frequent key(s) (strings). If there is a tie, include all tied keys.
        - If the input list is empty, return an empty list.
        """
        # TODO: implement
        return output_list

Example

queries = ['park', 'Park', 'McDonalds', 'apple', 'Apple Park', 'park', 'Park']

x = Child(queries)
print("most frequent:", x.most_frequent_key())

Notes/clarifications

  • Counting is case-sensitive because keys are created via str(item).
  • The goal is to manually compute the highest frequency via iteration (no max()).

Implement most_frequent_key without using max()

You are given a Parent class that precomputes frequency counts of items from an input list. Each item is converted to a string before being counted, so counting is case-sensitive and based on str(item). Implement the Child class method most_frequent_key so that it returns all key strings with the highest frequency. You may not use Python's built-in max() function. For this coding platform, implement solution(items), which should create a Child instance and return the result of Child.most_frequent_key(). If multiple keys are tied for the highest frequency, return them in the order their string key first appeared in the input list. If the input list is empty, return an empty list.

Hints

  1. Keep track of the largest frequency seen so far while iterating through self.ldf.
  2. When you find a frequency larger than the current best, reset the output list. When you find an equal frequency, append the key.