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 ""
I like how we can write python like psuedocode with few lines.
=> Counter(s)
Though it can be hard to understand and remember all the shortcuts.
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:
max
import operator from collections import Counter def max_char(s): c = Counter(s) try: return max(c, key=c.get) except ValueError: return ""
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.
s
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!
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Python could do it even better.
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.
Thank you for the comment!
I learned quite a lot from this code. I really appreciate it. Below is just for my understanding:
Actually we can make it more concise with the way I used above for the
max
function:I would have done this that way and using the built in 'max' method for the Counter object
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:
Wow, this looked enigmatic at first, but I understood how it works. Thank you!