In the following piece of code I'm trying to find the most used character in a given sentence. I've used list unpacking, and I've seen different ways of solving this. My question is, is this a good way to do it? or it's too complicated and not clean?
Input
sentence = "This is a common interview question"
characters = list(
{
(char, sentence.count(char))
for char in sentence if char != ' '
}
)
characters.sort(
key=lambda char: char[1],
reverse=True
)
print(f"'{characters[0][0]}' is repeated {characters[0][1]} times")
Output
'i' is repeated 5 times
You can use collections
package:
import collections
s = "This is a common interview question"
print(collections.Counter(s).most_common(1)[0])