Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
a bundle of looping solution in Creative category for End Zeros by PythonWithPI
def end_zeros_while(num: int) -> int:
if num == 0:
return 1
zeros = 0
while not num % 10:
num //= 10
zeros += 1
return zeros
#Don't do this
from itertools import takewhile, repeat
def end_zeros_takewhile(num: int) -> int:
return (
1
if (num := num * 10) == 0
else (
sum(
takewhile(
lambda x: x and num > 0,
(
not (num := num // 10) % 10
for _ in repeat(1)
)
)
)
)
)
def end_zeros_recursive(num: int) -> int:
return 1 if num == 0 else (
0 if num % 10 else (
1 + end_zeros_recursive(num // 10)
)
)
def end_zeros_tail_recursive(num: int, pre_zeros: int=0) -> int:
return pre_zeros + 1 if num == 0 else (
pre_zeros if num % 10 else (
end_zeros_tail_recursive(num // 10, pre_zeros + 1)
)
)
def end_zeros_string_strip(num: int) -> int:
num = str(num)
return len(num) - len(num.rstrip('0'))
import re
zeros_starting = re.compile('0+').match
def end_zeros_string_re(num: int) -> int:
num = str(num)[::-1]
match = zeros_starting(num)
return len(zeros_starting(num)[0]) if match else 0
from time import perf_counter
def end_zeros(num: int) -> int:
answer = None
for name, value in globals().items():
if name.startswith('end_zeros_'):
start = perf_counter()
for i in range(100000):
if answer is None:
answer = value(num)
else:
assert answer == value(num)
end = perf_counter()
print(name, end - start, answer)
return answer
#Speediest varies between recursive, string_strip, and while
if __name__ == '__main__':
print("Example:")
print(end_zeros(0))
print(end_zeros(10))
# These "asserts" are used for self-checking and not for an auto-testing
assert end_zeros(0) == 1
assert end_zeros(1) == 0
assert end_zeros(10) == 1
assert end_zeros(101) == 0
assert end_zeros(245) == 0
assert end_zeros(100100) == 2
print("Coding complete? Click 'Check' to earn cool rewards!")
Feb. 27, 2020
Comments: