-
Notifications
You must be signed in to change notification settings - Fork 7
/
pair_counter.py
60 lines (46 loc) · 1.35 KB
/
pair_counter.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
from collections import defaultdict
class PairCounter(object):
def __init__(self):
self._dict = defaultdict(int)
def add(self, a, b):
assert a != b
if a < b:
self._dict[(a, b)] += 1
else:
self._dict[(b, a)] += 1
def addSorted(self, a, b):
assert a < b
self._dict[(a, b)] += 1
def addset(self, s):
ss = sorted(s)
for i, a in enumerate(ss):
for b in ss[i+1:]:
self._dict[(a, b)] += 1
def addallcombinations(self, bins):
# XXX HOTSPOT
for i, bin in enumerate(bins):
for a in bin:
for bin2 in bins[i+1:]:
for b in bin2:
if a != b:
self.add(a, b)
def get(self, a, b):
assert a != b
if a < b:
return self._dict.get((a, b), 0)
else:
return self._dict.get((b, a), 0)
def __len__(self):
return len(self._dict)
def __nonzero__(self):
return len(self) != 0
def __str__(self):
return str(self._dict)
def __repr__(self):
return repr(self._dict)
def __iter__(self):
return iter(self._dict)
def __contains__(self, o):
assert False
def containsSorted(self, a, b):
return (a, b) in self._dict