proffreda

utils.py

Sep 25th, 2016
493
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1. """Utilities for Maps"""
  2.  
  3. from math import sqrt
  4. from random import sample
  5.  
  6. # Rename the built-in zip (http://docs.python.org/3/library/functions.html#zip)
  7. _zip = zip
  8.  
  9. def map_and_filter(s, map_fn, filter_fn):
  10. """Return a new list containing the result of calling map_fn on each
  11. element of sequence s for which filter_fn returns a true value.
  12.  
  13. >>> square = lambda x: x * x
  14. >>> is_odd = lambda x: x % 2 == 1
  15. >>> map_and_filter([1, 2, 3, 4, 5], square, is_odd)
  16. [1, 9, 25]
  17. """
  18. # BEGIN Question 0
  19. "*** REPLACE THIS LINE ***"
  20. return ['REPLACE THIS WITH YOUR LIST COMPREHENSION']
  21. # END Question 0
  22.  
  23. def key_of_min_value(d):
  24. """Returns the key in dict d that corresponds to the minimum value of d.
  25.  
  26. >>> letters = {'a': 6, 'b': 5, 'c': 4, 'd': 5}
  27. >>> min(letters)
  28. 'a'
  29. >>> key_of_min_value(letters)
  30. 'c'
  31. """
  32. # BEGIN Question 0
  33. "*** REPLACE THIS LINE ***"
  34. return min('REPLACE THIS WITH YOUR SOLUTION')
  35. # END Question 0
  36.  
  37. def zip(*sequences):
  38. """Returns a list of lists, where the i-th list contains the i-th
  39. element from each of the argument sequences.
  40.  
  41. >>> zip(range(0, 3), range(3, 6))
  42. [[0, 3], [1, 4], [2, 5]]
  43. >>> for a, b in zip([1, 2, 3], [4, 5, 6]):
  44. ... print(a, b)
  45. 1 4
  46. 2 5
  47. 3 6
  48. >>> for triple in zip(['a', 'b', 'c'], [1, 2, 3], ['do', 're', 'mi']):
  49. ... print(triple)
  50. ['a', 1, 'do']
  51. ['b', 2, 're']
  52. ['c', 3, 'mi']
  53. """
  54. return list(map(list, _zip(*sequences)))
  55.  
  56. def enumerate(s, start=0):
  57. """Returns a list of lists, where the i-th list contains i+start and the
  58. i-th element of s.
  59.  
  60. >>> enumerate([6, 1, 'a'])
  61. [[0, 6], [1, 1], [2, 'a']]
  62. >>> enumerate('five', 5)
  63. [[5, 'f'], [6, 'i'], [7, 'v'], [8, 'e']]
  64. """
  65. # BEGIN Question 0
  66. "*** REPLACE THIS LINE ***"
  67. # END Question 0
  68.  
  69. def distance(pos1, pos2):
  70. """Return the Euclidean distance between pos1 and pos2, which are pairs.
  71.  
  72. >>> distance([1, 2], [4, 6])
  73. 5.0
  74. """
  75. return sqrt((pos1[0] - pos2[0]) ** 2 + (pos1[1] - pos2[1]) ** 2)
  76.  
  77. def mean(s):
  78. """Return the arithmetic mean of a sequence of numbers s.
  79.  
  80. >>> mean([-1, 3])
  81. 1.0
  82. >>> mean([0, -3, 2, -1])
  83. -0.5
  84. """
  85. assert len(s) > 0, 'cannot find mean of empty sequence'
  86. return sum(s) / len(s)
Advertisement
Add Comment
Please, Sign In to add comment