+ 2
Using dictionary comprehensions in functions
I'm trying to use dict comprehensions to define an occurrence function that counts how many times a character shows up in a string. The resulting dict should be made of (character : occurence), however in my case all the values are 1, any help ? The code below contains an occurence function defined the normal way, and a oneliner which doesn't work yet (occurrence_one) https://code.sololearn.com/c25wjc9yTBcZ/?ref=app
4 odpowiedzi
0
'''Younes L. you never defined the that count is anathema.
But why not I'm up for the challenge.
try this.
'''
def oc(s):
return({i:len(list(filter(lambda x:x==i,s))) for i in set(s)})
print(oc('aaaabbaccac'))
+ 1
'''
Jan Markus has a point, but I assume you want to understand dict comprehension.
this is how I would do it.
'''
def oc(s):
return({i:s.count(i) for i in set(s)})
print(oc('aaaabbaccac'))
0
thanks Louis , Jan Markus , but isn't there a way without the count function ?
0
Louis len is definitely a more straightforward approach than sum , thanks !
do you have any idea what makes my occurrence_one always return 1 as values for the returned dictionary...
apart from being named occurrence_one, of course 😂
in the article I linked in the code, it says dictionaries can eventually be used as alternative to lambda functions (kind of what I'm trying to achieve here)