vendredi 8 janvier 2021

`SyntaxError` in if-else one-liner

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'm curious, how to get if-else one-liner to work in this case?

Aucun commentaire:

Enregistrer un commentaire