So the task is rather simple. Read in a string and store each character and its frequency in a dictionary then return the dictionary. I did it rather easily with a for loop.
def getInputFreq():
txt = input('Enter a string value: ')
d = dict()
for c in txt:
d[c] = d.get(c,0) + 1
return d
The issue is that I need to rewrite this statement using a map and lambda. I've tried a few things, early attempts returned empty dictionaries ( code has been lost in the attempts ).
My latest attempt was ( in place of the for loop in above )
d = map((lambda x: (d.get(x,0)+1)),txt)
which returns a map object address.
Any suggestions?
First, in python 3, you have to force list iteration on map
Then, your approach won't work, you'll get all ones or zeroes, because the expression doesn't accumulate the counts.
You could use str.count
in a lambda, and map the tuples to a dictionary, that works:
txt = "hello"
d = dict(map(lambda x : (x, txt.count(x)), set(txt)))
result:
{'e': 1, 'l': 2, 'h': 1, 'o': 1}
But once again, collections.Counter
is the preferred way to do that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With