get method

James Mills prologic at shortcircuit.net.au
Mon Dec 29 20:51:18 EST 2008


On Tue, Dec 30, 2008 at 11:43 AM, James Mills
<prologic at shortcircuit.net.au> wrote:
> On Tue, Dec 30, 2008 at 11:38 AM, Ross <ross.jett at gmail.com> wrote:
>> I realize the code isn't counting, but how am I to do this without
>> using an if statement as the problem instructs?
>
> I just gave you a hint :)

Ross:

This exercise is a simple exercise dealing with:
 * assignments
 * functions
 * dictionaries
 * looping
 * attributes and methods

>>> def histogram(s):
...     d = dict()
...     for c in s:
...             d[c] = d.get(c, 0) + 1
...     return d
...
>>> histogram("Hello World!")
{'!': 1, ' ': 1, 'e': 1, 'd': 1, 'H': 1, 'l': 3, 'o': 2, 'r': 1, 'W': 1}

Note the 3rd line of the function ?
1. Get the value (with a default of 0) of the key c from the dictionary d
2. Add 1 to this value
3. Store in d with key c

Hope this helps.

cheers
James



More information about the Python-list mailing list