proffreda

lab04_extra.py

Sep 15th, 2016
313
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. from lab04 import *
  2.  
  3. ## Extra Lists, Dictionaries Questions ##
  4.  
  5. #########
  6. # Lists #
  7. #########
  8.  
  9. # Q12
  10. def merge(lst1, lst2):
  11. """Merges two sorted lists.
  12.  
  13. >>> merge([1, 3, 5], [2, 4, 6])
  14. [1, 2, 3, 4, 5, 6]
  15. >>> merge([], [2, 4, 6])
  16. [2, 4, 6]
  17. >>> merge([1, 2, 3], [])
  18. [1, 2, 3]
  19. >>> merge([5, 7], [2, 4, 6])
  20. [2, 4, 5, 6, 7]
  21. """
  22. "*** YOUR CODE HERE ***"
  23.  
  24.  
  25. # Q13
  26. def mergesort(seq):
  27. """Mergesort algorithm.
  28.  
  29. >>> mergesort([4, 2, 5, 2, 1])
  30. [1, 2, 2, 4, 5]
  31. >>> mergesort([]) # sorting an empty list
  32. []
  33. >>> mergesort([1]) # sorting a one-element list
  34. [1]
  35. """
  36. "*** YOUR CODE HERE ***"
  37.  
  38.  
  39. # Q14
  40. def coords(fn, seq, lower, upper):
  41. """
  42. >>> seq = [-4, -2, 0, 1, 3]
  43. >>> fn = lambda x: x**2
  44. >>> coords(fn, seq, 1, 9)
  45. [[-2, 4], [1, 1], [3, 9]]
  46. """
  47. "*** YOUR CODE HERE ***"
  48. return ______
  49.  
  50.  
  51. # Q15
  52. def deck(suits, numbers):
  53. """Creates a deck of cards (a list of 2-element lists) with the given
  54. suits and numbers. Each element in the returned list should be of the form
  55. [suit, number].
  56.  
  57. >>> deck(['S', 'C'], [1, 2, 3])
  58. [['S', 1], ['S', 2], ['S', 3], ['C', 1], ['C', 2], ['C', 3]]
  59. >>> deck(['S', 'C'], [3, 2, 1])
  60. [['S', 3], ['S', 2], ['S', 1], ['C', 3], ['C', 2], ['C', 1]]
  61. >>> deck([], [3, 2, 1])
  62. []
  63. >>> deck(['S', 'C'], [])
  64. []
  65. """
  66. "*** YOUR CODE HERE ***"
  67. return ______
  68.  
  69.  
  70. ################
  71. # Dictionaries #
  72. ################
  73.  
  74. # Q16
  75. def counter(message):
  76. """ Returns a dictionary of each word in message mapped
  77. to the number of times it appears in the input string.
  78.  
  79. >>> x = counter('to be or not to be')
  80. >>> x['to']
  81. 2
  82. >>> x['be']
  83. 2
  84. >>> x['not']
  85. 1
  86. >>> y = counter('run forrest run')
  87. >>> y['run']
  88. 2
  89. >>> y['forrest']
  90. 1
  91. """
  92. word_list = message.split()
  93. "*** YOUR CODE HERE ***"
  94.  
  95.  
  96. # Q17
  97. def replace_all(d, x, y):
  98. """
  99. >>> d = {'foo': 2, 'bar': 3, 'garply': 3, 'xyzzy': 99}
  100. >>> replace_all(d, 3, 'poof')
  101.  
  102. >>> d == {'foo': 2, 'bar': 'poof', 'garply': 'poof', 'xyzzy': 99}
  103. True
  104. """
  105. "*** YOUR CODE HERE ***"
Advertisement
Add Comment
Please, Sign In to add comment