-
Notifications
You must be signed in to change notification settings - Fork 63
/
doubles.py
59 lines (39 loc) · 1.06 KB
/
doubles.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
import re
import string
import random
import itertools
def count_doubles(val):
total = 0
for c1, c2 in zip(val, val[1:]):
if c1 == c2:
total += 1
return total
def count_doubles_once(val):
total = 0
chars = iter(val)
c1 = next(chars)
for c2 in chars:
if c1 == c2:
total += 1
c1 = c2
return total
def count_doubles_itertools(val):
c1s, c2s = itertools.tee(val)
next(c2s, None)
total = 0
for c1, c2 in zip(c1s, c2s):
if c1 == c2:
total += 1
return total
double_re = re.compile(r'(?=(.)\1)')
def count_doubles_regex(val):
return len(double_re.findall(val))
val = ''.join(random.choice(string.ascii_letters) for i in range(1000000))
def test_pure_python(benchmark):
print(benchmark(count_doubles, val))
def test_itertools(benchmark):
print(benchmark(count_doubles_itertools, val))
def test_pure_python_once(benchmark):
print(benchmark(count_doubles_once, val))
def test_regex(benchmark):
print(benchmark(count_doubles_regex, val))