-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
85 lines (65 loc) · 2.12 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
"""Utilities for Maps"""
from math import sqrt
from random import sample
# Rename the built-in zip (http://docs.python.org/3/library/functions.html#zip)
_zip = zip
def map_and_filter(s, map_fn, filter_fn):
"""Return a new list containing the result of calling map_fn on each
element of sequence s for which filter_fn returns a true value.
>>> square = lambda x: x * x
>>> is_odd = lambda x: x % 2 == 1
>>> map_and_filter([1, 2, 3, 4, 5], square, is_odd)
[1, 9, 25]
"""
map_and_filtered=[map_fn(i) for i in s if filter_fn(i)]
return map_and_filtered
def key_of_min_value(d):
"""Returns the key in dict d that corresponds to the minimum value of d.
>>> letters = {'a': 6, 'b': 5, 'c': 4, 'd': 5}
>>> min(letters)
'a'
>>> key_of_min_value(letters)
'c'
"""
return min(d, key=lambda x: d[x] )
def zip(*sequences):
"""Returns a list of lists, where the i-th list contains the i-th
element from each of the argument sequences.
>>> zip(range(0, 3), range(3, 6))
[[0, 3], [1, 4], [2, 5]]
>>> for a, b in zip([1, 2, 3], [4, 5, 6]):
... print(a, b)
1 4
2 5
3 6
>>> for triple in zip(['a', 'b', 'c'], [1, 2, 3], ['do', 're', 'mi']):
... print(triple)
['a', 1, 'do']
['b', 2, 're']
['c', 3, 'mi']
"""
return list(map(list, _zip(*sequences)))
def enumerate(s, start=0):
"""Returns a list of lists, where the i-th list contains i+start and the
i-th element of s.
>>> enumerate([6, 1, 'a'])
[[0, 6], [1, 1], [2, 'a']]
>>> enumerate('five', 5)
[[5, 'f'], [6, 'i'], [7, 'v'], [8, 'e']]
"""
return zip(range(start, start+len(s)), s)
def distance(pos1, pos2):
"""Return the Euclidean distance between pos1 and pos2, which are pairs.
>>> distance([1, 2], [4, 6])
5.0
"""
return sqrt((pos1[0] - pos2[0]) ** 2 + (pos1[1] - pos2[1]) ** 2)
def mean(s):
"""Return the arithmetic mean of a sequence of numbers s.
>>> mean([-1, 3])
1.0
>>> mean([0, -3, 2, -1])
-0.5
"""
assert len(s) > 0, 'cannot find mean of empty sequence'
return sum(s) / len(s)