Jul-03-2018, 08:59 PM
(Jul-03-2018, 01:13 PM)DeaD_EyE Wrote:import string def count_func(s): return sum(1 for c in s if c in set(string.digits))
It may be re-written as
def count_func(s): return sum(c in set(string.digits) for c in s)You can add booleans as integers.
Still, major loser to @ichabod801
Output:In [8]: %timeit dead_eye_count_func(my_string)
31.8 ms ± 1 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
In [9]: %timeit ick_count(my_string)
467 µs ± 12 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
With a little tweak - making set
of digits "static"Output:In [12]: def frozen_set_count_func(s, _digits=frozenset(string.digits)):
...: return sum(c in _digits for c in s)
...:
In [13]: %timeit frozen_set_count_func(my_string)
5.7 ms ± 264 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Test everything in a Python shell (iPython, Azure Notebook, etc.)
- Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
- Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
- You posted a claim that something you did not test works? Be prepared to eat your hat.