pydsa.counting¶
Multiset ¶
Bases: Counter
A Counter whose keys vanish when their count hits 0.
m[k] += 1 and m[k] -= 1 are the whole interface. With a plain
Counter, m[k] -= 1 leaves the key behind at 0, so len(m) and
k in m stop meaning what a sliding window needs them to mean.
Negative counts are kept: only an exact 0 deletes.
Source code in pydsa/counting.mu
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | |
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | |
update ¶
update(*args, **kwds) -> None
Source code in pydsa/counting.mu
18 19 20 21 22 23 | |
20 21 22 23 | |
count_pairs ¶
count_pairs(
xs: Iterable[Any],
key: Optional[Callable[[Any], Any]] = None,
lookup: Optional[Callable[[Any], Any]] = None,
) -> int
Count the index pairs i < j with key(xs[i]) == lookup(xs[j]), in one pass.
key(x) is the key x is stored under and lookup(x) is the key x looks up. With key left out the key is x itself; with lookup left out it is key, so plain count_pairs(xs) counts the pairs of equal values.
count_pairs([1, 2, 3, 1, 1, 3]) 4 count_pairs([1, 6, 3, 11, 8], key=lambda x: x % 5) 4 count_pairs([3, 1, 4, 6, 3], lookup=lambda x: x - 2) 2
Source code in pydsa/counting.mu
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | |
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | |
count_subarrays ¶
count_subarrays(
xs: Iterable[Any],
key: Callable[[Any], bool],
pairs: bool = False,
) -> int
Count the subarrays of xs in which every element passes key, or, with pairs, every adjacent pair (a, b) passes key(a, b).
A maximal block that passes holds n * (n + 1) // 2 subarrays for its length n; the running count adds the current block length at each step. With pairs, a single element has no pair, so a block starts at length 1.
count_subarrays([1, 3, 2, 5, 4], lambda v: v % 2 == 1) 4 count_subarrays([3, 2, 1, 4], lambda a, b: b == a - 1, pairs=True) 7
Source code in pydsa/counting.mu
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | |
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | |