[Python][Coding Pattern] Most Frequent Letter

Most Frequent Letter

Purpose

This function analyzes a string and identifies the most frequently occurring letter.

It returns:

- A single letter as a string, if only one letter has the highest frequency.

- A list of letters, if there is a tie for the highest frequency.

- An empty string, if there are no letters to evaluate.

Key Constraints

- Only alphabetic characters are considered.

- The comparison is case-sensitive — for example, "A" and "a" are treated as different letters.

- If the input is empty or contains no letters, the function returns an empty string.

Step-by-step Logic

1. Initial Check for Empty Input

The function first checks whether the input string is empty.

If so, it immediately returns an empty string to avoid unnecessary computation.

2. Prepare a Result Container

A list is initialized to store one or more letters that will be returned at the end.

This is where the most frequent letter or letters will be collected.

3. Filter Non-Letter Characters

The input string is cleaned using str.isalpha(), which filters out any non-alphabetical characters, such as spaces, numbers, or punctuation.

The remaining letters are joined back together into a new string.

4. Check for Valid Letters

If the cleaned string is empty after filtering, the function returns an empty string, as there are no letters to evaluate.

5. Count Frequencies

A dictionary is used to count how many times each letter appears in the cleaned string.

The dict.get() method is used during iteration to increment counts.

If a character has not been seen before, it starts at zero.

6. Determine the Maximum Frequency

The function finds the maximum value from the dictionary using the built-in max() function applied to the dictionary’s .values().

7. Identify Letters Matching the Maximum

The function then loops through the dictionary using .items() and adds any letter whose count matches the maximum frequency into the result list.

8. Return the Result

- If there is only one letter in the result list, it returns that letter as a string.

- If there are multiple letters tied for the highest frequency, it returns the list of those letters.

Standard Library Methods Used

- str.isalpha() to identify alphabetic characters only

- ''.join() to reassemble characters into a string

- dict.get() to simplify conditional counting

- max() to retrieve the highest frequency

- dict.values() and dict.items() for iterating over frequency data

def most_frequent_letter(text: str) -> str | list[str]:
    # return the most frequent char
    # return a list of the most frequent chars
    # filter out non alphabetical chars
    # case-sensitive
    # return '' for empty or no letter input

    if not text:
        return ''

    targets = []
    cleaned_text = ''.join(char for char in text if char.isalpha())
   
    if not cleaned_text:
        return ''
   
    freq_checker = {}

    for char in cleaned_text:
        freq_checker[char] = freq_checker.get(char, 0) + 1

    max_freq = max(freq_checker.values())
    for char, freq in freq_checker.items():
        if freq == max_freq:
            targets.append(char)

    return targets[0] if len(targets) == 1 else targets

   


if __name__ == '__main__':
    assert most_frequent_letter("hello world") == "l"
    assert most_frequent_letter("aabbbc") == "b"
    assert most_frequent_letter("aabbcc") == ["a", "b", "c"]
    assert most_frequent_letter("aaAAAAAAAbbcc") == "A"

Comments