fork(5) download
  1. # -*- coding: utf-8 -*-
  2. # MIT OCW 6.189 Homework 3
  3. # Exercise 3.4 – More About Dictionaries
  4. # Mechanical MOOC
  5. # Judy Young
  6. # July 24, 2013
  7.  
  8. # These lists match up, so Alice’s age is 20, Bob’s age is 21, and so on.
  9. # Write a function combine_lists that combines these lists into a dictionary
  10. # (hint: what should the keys, and what should the values, of this dictionary be?).
  11. # Then, write a function people that takes in an age and returns the names of
  12. # all the people who are that age.
  13.  
  14. NAMES = ['Alice', 'Bob', 'Cathy', 'Dan', 'Ed', 'Frank',
  15. 'Gary', 'Helen', 'Irene', 'Jack', 'Kelly', 'Larry']
  16. AGES = [20, 21, 18, 18, 19, 20, 20, 19, 19, 19, 22, 19]
  17.  
  18. # Define your functions here
  19. def combine_lists(list_1, list_2):
  20. comb_dict = {}
  21. for item_1, item_2 in zip(list_1, list_2):
  22. comb_dict[item_1] = item_2
  23. return comb_dict
  24.  
  25. combined_dict = combine_lists(NAMES, AGES)
  26.  
  27. def people(age):
  28. # Use combined_dict within this function...
  29. match_list = []
  30. for each in combined_dict.items():
  31. if age in each:
  32. match_list.append(each[0])
  33. return match_list
  34.  
  35. # Test Cases for Exercise 3.4 (all should be True)
  36. print 'Dan' in people(18) and 'Cathy' in people(18)
  37. print 'Ed' in people(19) and 'Helen' in people(19) and\
  38. 'Irene' in people(19) and 'Jack' in people(19) and 'Larry'in people(19)
  39. print 'Alice' in people(20) and 'Frank' in people(20) and 'Gary' in people(20)
  40. print people(21) == ['Bob']
  41. print people(22) == ['Kelly']
  42. print people(23) == []
  43.  
Success #stdin #stdout 0.08s 8840KB
stdin
Standard input is empty
stdout
True
True
True
True
True
True