Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #! /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)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement