Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
6 solutions, different speed (fastest with map) solution in Speedy category for Count Digits by CDG.Axel
def count_digits(text: str) -> int:
# your code here
return sum(map(str.isdigit, text))
"""
timing for diffrent soultions:
return sum(idx.isdigit() for idx in text) --> 1.87 sec
return sum([idx.isdigit() for idx in text]) --> 1.63 sec
return sum(1 for idx in text if idx.isdigit()) --> 1.34 sec
return sum([1 for idx in text if idx.isdigit()]) --> 1.25 sec
return len([1 for idx in text if idx.isdigit()]) --> 1.19 sec
return sum(map(str.isdigit, text)) --> 1.08 sec
"""
if __name__ == '__main__':
print("Example:")
print(count_digits('hi'))
# These "asserts" are used for self-checking and not for an auto-testing
assert count_digits('hi') == 0
assert count_digits('who is 1st here') == 1
assert count_digits('my numbers is 2') == 1
assert count_digits('This picture is an oil on canvas '
'painting by Danish artist Anna '
'Petersen between 1845 and 1910 year') == 8
assert count_digits('5 plus 6 is') == 2
assert count_digits('') == 0
print("Coding complete? Click 'Check' to earn cool rewards!")
Aug. 29, 2021
Comments: