Start the marathon: find the most common character in a string.
You count the characters and you take the one with the biggest count. Here is the whole thing in six lines.
from collections import Counter
def most_common_char(text):
counts = Counter(text)
return max(counts, key=counts.get)
And how does it work? The class Counter takes any collection and counts how often each item appears. And then the function max takes the dictionary and a key function, and it returns the item with the biggest value for that function. The key function here is counts.get, which gives back the count of an item.
the text the counts the answer
-------------- ------------- ---------
"banana" a:3, b:1, n:2 a
"programming" various the most common letter
And there is one detail worth knowing about. The class Counter is a dictionary, and the function max takes the first item it finds with the biggest value when there is a tie. So the answer with a tie is the one that comes first in the order of the dictionary.
And there is one edge case to handle. An empty string has no characters, so the counts are empty and the function max would fail. You check for that first.
from collections import Counter
def most_common_char(text):
if not text:
return None
counts = Counter(text)
return max(counts, key=counts.get)
And the complexity is O of n for the time, where n is the length of the text, and O of k for the space, where k is the number of different characters.
So the rule to remember is this. Count them all, then take the biggest count.
The next two questions in this topic are the middle and the hard one of the marathon.