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
#11
(Jul-03-2018, 11:27 AM)gruntfutuk Wrote: I didn't run time it.
import timeit
import string

my_string = 'DS80A98SD09a8SD098ASD098A09sd8c0a9SCNAfsdg8fbvdfad098098f00A'*1000

def count_func(s):
    return sum(c.isdigit() for c in s)


def smart_count_digits(my_string):
    orig_length = len(my_string)
    for digit in string.digits:
        my_string = my_string.replace(digit, '')
    return orig_length - len(my_string)

elapsed = timeit.timeit('count_func(my_string)', number=1000, setup='from __main__ import count_func, my_string')
print( 'count_func took {:.3f} sec'.format(elapsed))

elapsed = timeit.timeit('smart_count_digits(my_string)', number=1000, setup='from __main__ import smart_count_digits, my_string')
print('smart_count_digits took {:.3f} sec'.format(elapsed))
Output:
count_func took 15.112 sec smart_count_digits took 1.181 sec
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Messages In This Thread
RE: How to exclude characters when counting digits - by buran - Jul-03-2018, 11:59 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Counting the number of occurrences of characters in a string nsadams87xx 1 1,954 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