|
|
|
|
|
by dr_zoidberg
3138 days ago
|
|
Good numpy implementation of the algorithm. If, for whatever reason, numpy isn't available, you can also pull it with a good comprehension: def count_doubles2(val):
return sum(1 for c1, c2 in zip(val, val[1:]) if c1 == c2)
Which will also allow you to avoid a function call entirely, if it was useful in some way: In [56]: %timeit count_doubles(val)
198 ms ± 13.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [57]: %timeit count_doubles2(val)
189 ms ± 21.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [58]: %timeit sum(1 for c1, c2 in zip(val, val[1:]) if c1 == c2)
135 ms ± 3.86 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
In [59]: %timeit count_double_chars_np(val)
6.95 ms ± 782 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
(Numpy still beats it, for long strings). |
|