Python Forum
How to exclude characters when counting digits
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to exclude characters when counting digits
#20
(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.
Reply


Messages In This Thread
RE: How to exclude characters when counting digits - by volcano63 - Jul-03-2018, 08:59 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Counting the number of occurrences of characters in a string nsadams87xx 1 2,024 Jun-16-2020, 07:22 PM
Last Post: bowlofred

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020