0

Hi friends,
I am trying to write a histogram function in Python. This is what I have managed so far:

def histogram(s):
    d={}
    for c in s:
        if c not in d:
            d[c]=1
        else:
            d[c]+=1
    return d


    

h=histogram('brontosaurus')
print h

However, I want to use the get() function in the dictionary module to re-write the above code. I also want to eliminate the 'if' statement. Can this be done?

Thank You.

PS: I am a Python newbie. :)

2
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by mcenley
0

Rewrite your code this way ...

def histogram(s):
    d={}
    for c in s:
        d[c] = d.get(c, 0) + 1
    return d


h=histogram('brontosaurus')
print h

"""
my result -->
{'a': 1, 'b': 1, 'o': 2, 'n': 1, 
's': 2, 'r': 2, 'u': 2, 't': 1}
"""

To better understand what is going on you can insert a temporay test print ...

def histogram(s):
    d = {}
    for c in s:
        # print for testing only 
        print c, d.get(c, 0)
        d[c] = d.get(c, 0) + 1
    return d


h = histogram('brontosaurus')
print h

"""
my result -->
b 0
r 0
o 0
n 0
t 0
o 1
s 0
a 0
u 0
r 1
u 1
s 1
{'a': 1, 'b': 1, 'o': 2, 'n': 1, 
's': 2, 'r': 2, 'u': 2, 't': 1}
"""
0

Hi,
Thank You.

Wonder when such things will get into my little head !

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.