Stack Overflow Asked by Evgeniy Golovin on February 13, 2021
I wrote this block of code, but it doesn’t work because of SyntaxError
.
def char_freq(message):
d = dict()
for ch in message:
d[ch] += 1 if ch in d else d[ch] = 1
return d ^ SyntaxError: End of statement expected
I don’t know how to rewrite the expression in order to keep if-else in one line and to get it to work.
I know it is possible to implement the function as a simple for
loop, but I don’t understand, why my if-else one-liner results in SyntaxError
?
As you asked to keep the if/else
Do
d[ch] = (d[ch] + 1) if ch in d else 1
But the dict.get()
syntax is nicer d[ch] = d.get(ch, 0) + 1
Or a collections.defaultdict
with int
factory
def char_freq(message):
d = defaultdict(int)
for ch in message:
d[ch] += 1
return d
Correct answer by azro on February 13, 2021
Turn d
into a defaultdict and then you can just ignore the statement altogether
from collections import defaultdict
def char_freq(message):
d = defaultdict(int)
for ch in message:
d[ch] += 1
return d
It also looks like you're just counting characters so you could just use a counter
from collections import Counter
def char_freq(message):
return Counter(message)
Answered by Sayse on February 13, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP