Reputation:
I want to create a function that asks for a number and then sees the most amount of zeros in a row and returns its value (ex: 5400687000360045 -> 3 | 03500400004605605600 -> 4). So far this is all I got but it isn't working:
def zeros():
num = input('Write a number: ')
row = 0
result = 0
for i in num:
if i == '0':
while i == '0':
row += 1
if row > result:
result = row
return result
What's wrong?
EDIT: This is what the desired output should be:
zeros()
Write a number: 03500400004605605600
4
My current output is nothing, meaning it's not returning anything
Upvotes: 0
Views: 147
Reputation: 401
Is this helpful to you..? regex (Regular expression operations) is a very handy tool which could make your life easier. Please have look at Regular expression operations
import re
def zeros():
num = input('Write a number: ')
return max(re.findall("(0+0)*", (num)))
output : 000
def zeros():
num = input('Write a number: ')
return len(max(re.findall("(0+0)*", (num))))
output : 3
Upvotes: 1
Reputation: 26
I think this might work
num = input()
countOfZeros = 0
for i in range(len(num)-1):
curr = 0
if num[i] == num[i+1]:
curr = 0
if curr > countOfZeros:
countOfZeros = curr
else:
countOfZeros += 1
print(countOfZeros - 1 )
Upvotes: 0
Reputation: 3842
To do it your way, you just need to keep track of whether the number is a 0 or not (i.e. to know if it is a row of zeros or if you need to restart the count). Something like this would work:
def zeros():
num = input('Write a number: ')
row = 0
result = 0
for i in num:
if i != '0':
row = 0
else:
row += 1
if row > result:
result = row
return result
Output is as you would expect.
If you know regex, you could achieve this with much less code using:
import re
def zeros():
num = input('Write a number: ')
result = max(map(len, re.findall(r'0+', num)))
return result
Upvotes: 1
Reputation: 510
This should do it.
def zeros():
num = input('Write a number: ')
row = 0
count = 0
for i in num:
if i == '0':
count += 1
else:
row = max(row, count)
count = 0
row = max(row, count)
return row
Your code is getting stuck in an infinite loop in inner while
Upvotes: 2