4 return sqrt(sum((x**2 for x in p)))
6 # Pairwise distances between the elements of `points` with respect to some `norm`
7 class PairwiseDistances:
8 def __init__(self, points, norm = l2):
13 return len(self.points)
15 def __call__(self, p1, p2):
16 return self.norm((x - y for (x,y) in zip(self.points[p1], self.points[p2])))
18 # Caches all distances specified by `distances`
19 class ExplicitDistances:
20 def __init__(self, distances):
21 self.len = len(distances)
23 for i in xrange(self.len):
24 self.distances.append([])
25 for j in xrange(self.len):
26 self.distances[-1].append(distances(i,j))
31 def __call__(self, p1, p2):
32 return self.distances[p1][p2]
34 # Generator of all points in a file `filename` with one point per line
35 def points_file(filename):
37 for line in fd.xreadlines():
38 if line.startswith('#'): continue 39 yield map(float, line.strip().split())