I know that you need a single liner, but what if you had to repeat this task many times or process really long sentences? I do not know the specific use case here, but it may be worth your time, given the complexity of the space and time of the algorithm.
In your solution, for example, you repeat the sentence many times more than necessary using sentence.count() , which takes O(n * number of unique characters) . After that, you again go through an ordered disk to find max (another operation O(number of unique characters) ).
In the decision we make, we ultimately need to define a new class (which violates your liner btw requirement) and create new objects with a lot of templates and functionality that you probably will not need every time you want to complete your task.
If you don't mind having a few more lines of code (again, I know this is not what the question is asking), we can build a reusable function that should only iterate through the line once and use constant and minimal space:
from collections import defaultdict def most_common_char(sentence): if not sentence: return '' max_count = 1 max_char = sentence[-1] char_counts = defaultdict(int) char_counts[max_char] = 1 for i in xrange(len(sentence) - 2, -1, -1): char = sentence[i] char_counts[char] += 1 if char_counts[char] >= max_count: max_count = char_counts[char] max_char = char return max_char
We track the character with the maximum number as , we go through the line and spit it out at the end of the iteration. Please note that we are iterating backwards, since you need the first letter (i.e. the last updated victory).
source share