re: Learning Algorithms with JS, Python and Java 4: MaxChar VIEW POST

VIEW PARENT COMMENT VIEW FULL DISCUSSION

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

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

code of conduct - report abuse