DEV Community is a community of 788,395 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

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

I like how we can write python like psuedocode with few lines.

count element in an element

=> Counter(s)

Though it can be hard to understand and remember all the shortcuts. tommy-3

Thank you for the comment!

I learned quite a lot from this code. I really appreciate it. Below is just for my understanding:

import operator
from collections import Counter

c = Counter('abbb')
print(c)    # prints: Counter({'b': 3, 'a': 1})
print(c.items())    # prints: dict_items([('a', 1), ('b', 3)])

item = list(c.items())
print(item)    # prints: ('a', 1)
print(item)    # prints: a
print(item)    # prints: 1

itemgetter_1 = operator.itemgetter(1)
print(itemgetter_1(['x', 'y', 'z']))    # prints: y
print(itemgetter_1(item))    # prints: 1

print(max(c.items(), key=operator.itemgetter(1)))    # prints: ('b', 3)
print(max(c.items(), key=operator.itemgetter(1)))    # prints: b

Actually we can make it more concise with the way I used above for the max function:

import operator
from collections import Counter

def max_char(s):
c = Counter(s)
try:
return max(c, key=c.get)
except ValueError:
return "" 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) 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)     # ('c', 7)
Counter(s).most_common(1)  # 'c