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. :)

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}
"""

Hi,
Thank You.

Wonder when such things will get into my little head !

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.