我想制作一個回傳連續零數量的函式。
print(consecutive_zeros("0100100001"))
應該回傳 4
def consecutive_zeros(string):
zeros = 0
cache = 0
for elem in range(len(string)):
if string[elem] == "0":
zeros = 1
elif string[elem] == "1":
if zeros > cache:
zeros = cache
zeros = 0
return cache
如果我給它一個帶數字的字串,我的 func 總是回傳 0
for elem in range(len(string)):
if string[elem] == "0":
zeros = 1
這應該每 0 計數一次
elif string[elem] == "1":
if zeros > cache:
zeros = cache
這會在 1 出現時打破計數器,并檢查計數的連續零的數量是否比暫時保存的零更高
uj5u.com熱心網友回復:
我不是真正的 Python 人,但我只是在這里使用正則運算式。
txt = "0100100001"
# Find all sub strings with 2 or more consecutive zeros
matches = re.findall("00 ", txt)
# Compute string lengths
lengths = map(lambda x: len(x), matches)
# Find Longest
max_zeros = max(lengths);
print(max_zeros)
uj5u.com熱心網友回復:
這是您的代碼的修復:
def consecutive_zeros(string):
zeros = 0
cache = 0
for elem in string:
if elem == "0":
zeros = 1
if zeros > cache:
cache = zeros # this was inverted
else:
zeros = 0
return cache # this was wrongly indented
consecutive_zeros("01001000010")
輸出: 4
我個人會使用itertools.groupby和理解:
from itertools import groupby
s = '0100100001'
max(len(list(g)) for v,g in groupby(s) if v=='0')
輸出: 4
uj5u.com熱心網友回復:
您還需要在完成迭代后檢查當前計數,以防最大連續出現在最后一個序列中。
def consecutive_zeros(string):
curr = 0
max_consecutive_zeros = 0
for ch in string:
if ch == '0':
curr = 1
continue
else:
if curr >= max_consecutive_zeros:
max_consecutive_zeros = curr
curr = 0
if curr >= max_consecutive_zeros:
max_consecutive_zeros = curr
return maxmax_consecutive_zeros
max_consecutive_zeros = consecutive_zeros("0100100001")
print(max_consecutive_zeros)
>> 4
uj5u.com熱心網友回復:
請參閱@Nick B 以獲得出色(且快速!)的答案。
但是,如果您想使用您的解決方案;
- 您的函式在第一個回圈后回傳 - 移動您的函式
return,使其與您的for回圈對齊
def consecutive_zeros(string):
zeros = 0
cache = 0
for elem in range(len(string)):
if string[elem] == "0":
zeros = 1
elif string[elem] == "1":
if zeros > cache:
zeros = cache
zeros = 0
return cache #Aligned it such that data is returned at last
- 您的函式回傳
cache永遠不會更新;你需要更新
def consecutive_zeros(string):
zeros = 0
cache = 0
for elem in range(len(string)):
if string[elem] == "0":
zeros = 1
elif string[elem] == "1":
if zeros > cache:
cache = zeros #'zeros = cache' before
zeros = 0
return cache #Aligned it such that data is returned at last
- 您的代碼不會重置
zeros- 僅當zeros>cache. 移到zeros=0外面,if zeros > cache但仍然在elif string[elem] == "1"
def consecutive_zeros(string):
zeros = 0
cache = 0
for elem in range(len(string)):
if string[elem] == "0":
zeros = 1
elif string[elem] == "1":
if zeros > cache:
cache = zeros #'zeros = cache' before
zeros = 0 #Move it such that it's updated whenever we reset our counter
return cache #Aligned it such that data is returned at last
然后它起作用了
- 注意,使用
for elem in string代替for elem in range(len(string))
uj5u.com熱心網友回復:
如果您的字串只包含0和1's,您可以:
data = "0100100001"
print(max(len(x) for x in data.split('1')))
列印:
4
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/365102.html
下一篇:在保持先前繪圖的同時重新組合畫布
