只需检查奇偶性是否保持最小序列长度(在此处为3)。
def determine(list_, in_a_row=3):
prv, cntr = None, 1
for v in list_:
cur = bool(v % 2)
if prv is cur:
cntr += 1
else:
cntr = 1
prv = cur
if cntr >= in_a_row:
return True
return False
dataexp = [
([2, 1, 3, 5],True),
([2, 1, 2, 5],False),
([2, 4, 2, 5],True),
([],False),
]
for li, exp in dataexp:
got = determine(li)
msg = "exp:%s:%s:got for %s" % (exp, got, li)
if exp == got:
print("good! %s" % msg)
else:
print("bad ! %s" % msg)
输出
good! exp:True:True:got for [2, 1, 3, 5]
good! exp:False:False:got for [2, 1, 2, 5]
good! exp:True:True:got for [2, 4, 2, 5]
good! exp:False:False:got for []