Advertisement
Mars83

9-2

Oct 9th, 2011
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.00 KB | None | 0 0
  1. #! /usr/bin/env python3.2
  2. # -*- coding: utf-8 -*-
  3.  
  4. # main.py
  5. """ Task: Exercise 9.2
  6.    Dictionaries have a method called get that takes a key and a default value.
  7.    If the key appears in the dictionary, get returns the corresponding value;
  8.    otherwise it returns the default value. For example:
  9.    
  10.    >>> h = histogram('a')
  11.    >>> print h
  12.    {'a': 1}
  13.    >>> h.get('a', 0)
  14.    1
  15.    >>> h.get('b', 0)
  16.    0
  17.    
  18.    Use get to write histogram more concisely. You should be able to eliminate
  19.    the if statement.
  20.    
  21.    def histogram(s):
  22.        d = dict()
  23.        for c in s:
  24.            if c not in d:
  25.                d[c] = 1
  26.            else:
  27.                d[c] = d[c] + 1
  28.        return d
  29. """
  30.  
  31. ''' Functions '''
  32. def histogram(s):
  33.     d = dict()
  34.     for c in s:
  35.         d[c] = d.get(c, 0) + 1  # if c does not exist in d, it will be inserted
  36.                                 # with the value of 0+1 = 1
  37.     return d
  38.  
  39. ''' Test '''
  40. h = histogram('brontosaurus')
  41. print(h)
  42.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement