我需要在字符串中找到所有系列零的位置,而且我很难实现一个python函数。
它的输出需要如下所示:
输入: 100010001
输出: [(7,5), (3,1)]
因为在输入字符串的索引7到5和3到1处有一系列的零。
输入: 11000010101
输出: [(8,5)]
位置1和3的零被忽略,因为它们是单独的(不是在一个序列中)。
发布于 2022-02-08 08:53:44
您可以使用这样的东西,我们继续递增i,一旦我们看到一个0,我们就开始寻找从0开始的所有0。如果连续零点数大于1,则将它们添加到列表中-
def get_zeroes(s):
zeroes = []
i = 0
while i < len(s):
digit = s[i]
i += 1
if digit != '0':
continue
start = i - 1
while i < len(s) and s[i] == '0':
i += 1
if i - start > 1:
zeroes.append((len(s) - start - 1, len(s) - i))
return zeroes>>> get_zeroes('100010001')
[(7, 5), (3, 1)]
>>> get_zeroes('11000010101')
[(8, 5)]
>>> get_zeroes('10001000')
[(6, 4), (2, 0)]
>>> get_zeroes('00001000')
[(7, 4), (2, 0)]https://stackoverflow.com/questions/71030587
复制相似问题