
9-2
By:
Mars83 on
Oct 9th, 2011 | syntax:
Python | size: 1.00 KB | hits: 48 | expires: Never
#! /usr/bin/env python3.2
# -*- coding: utf-8 -*-
# main.py
""" Task: Exercise 9.2
Dictionaries have a method called get that takes a key and a default value.
If the key appears in the dictionary, get returns the corresponding value;
otherwise it returns the default value. For example:
>>> h = histogram('a')
>>> print h
{'a': 1}
>>> h.get('a', 0)
1
>>> h.get('b', 0)
0
Use get to write histogram more concisely. You should be able to eliminate
the if statement.
def histogram(s):
d = dict()
for c in s:
if c not in d:
d[c] = 1
else:
d[c] = d[c] + 1
return d
"""
''' Functions '''
def histogram(s):
d = dict()
for c in s:
d[c] = d.get(c, 0) + 1 # if c does not exist in d, it will be inserted
# with the value of 0+1 = 1
return d
''' Test '''
h = histogram('brontosaurus')
print(h)