简体   繁体   English

计算一个数字中一行中最多的零个数| Python

[英]Counting the most amount of zeros in a row in a number | Python

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).我想创建一个 function 请求一个数字,然后在一行中看到最多的零并返回其值(例如: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:编辑:这就是所需的 output 应该是:

zeros()
Write a number: 03500400004605605600
4

My current output is nothing, meaning it's not returning anything我当前的 output 什么都没有,这意味着它没有返回任何东西

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您的代码在内部 while 中陷入无限循环

To do it your way, you just need to keep track of whether the number is a 0 or not (ie to know if it is a row of zeros or if you need to restart the count).要按照自己的方式进行操作,您只需要跟踪数字是否为 0(即知道它是否是一排零,或者您是否需要重新开始计数)。 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. Output 如您所料。

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

Is this helpful to you..?这对你有帮助吗..? regex (Regular expression operations) is a very handy tool which could make your life easier. regex(正则表达式操作)是一个非常方便的工具,可以让您的生活更轻松。 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 output: 000


def zeros():
    num = input('Write a number: ') 
    return len(max(re.findall("(0+0)*", (num))))

output: 3 output: 3

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 )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM