DEV Community

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

Collapse
 
ryselis profile image
Karolis Ryselis

Python could do it even better.

import operator
from collections import Counter

def max_char(s):
    c = Counter(s)
    try:
        return max(c.items(), key=operator.itemgetter(1))[0]
    except ValueError:
        return ""
Collapse
 
rattanakchea profile image
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.

Collapse
 
tommy3 profile image
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())[0]
print(item)    # prints: ('a', 1)
print(item[0])    # prints: a
print(item[1])    # 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))[0])    # 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 ""
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!