DEV Community

Discussion on: Learning Algorithms with JS, Python and Java 4: MaxChar

Collapse
 
pbouillon profile image
Pierre Bouillon

I would have done this that way and using the built in 'max' method for the Counter object

from collections import Counter

def max_char(s):
    return Counter(s).most_common(1)[0][0] if s else ''

To explain a little bit to non Python dev:
if s is a valid chain, I build a Counter object with it, get the list of the n (letter, count) elements, getting the first one and returning only the letter.

Step by step:

s = 'abcccccccd'
Counter(s).most_common(1)        # [('c', 7)]
Counter(s).most_common(1)[0]     # ('c', 7)
Counter(s).most_common(1)[0][0]  # 'c
Collapse
 
tommy3 profile image
tommy-3

Wow, this looked enigmatic at first, but I understood how it works. Thank you!