Python 获取最小连续值计数(如果有)
我有一张单子Python 获取最小连续值计数(如果有),python,python-3.x,Python,Python 3.x,我有一张单子 [True, True, True, True, False, False, True, False, True, True, False] 我想知道最小计数是连续的,因此在这种情况下为1 或者在下面的列表中,它是2 [True, True, False, True, True, False, False, False, False, True, True, True] 谢谢你的帮助 以下是我(天真的)解决方案: list_1 = [True, True, True, Tru
[True, True, True, True, False, False, True, False, True, True, False]
我想知道最小计数是连续的,因此在这种情况下为1
或者在下面的列表中,它是2
[True, True, False, True, True, False, False, False, False, True, True, True]
谢谢你的帮助 以下是我(天真的)解决方案:
list_1 = [True, True, True, True, False, False, True, False, True, True, False]
list_2 = [True, True, False, True, True, False, False, False, False, True, True, True]
list_3 = [False, False, False]
list_4 = [True, True, True]
list_5 = [False, False, False, True, True]
def min_successive_val_count(list_of_vals):
list_of_runs = []
counter = 0
for val in list_of_vals:
if val:
counter+=1
else:
if counter != 0:
list_of_runs.append(counter)
counter = 0
if list_of_runs:
return min(list_of_runs)
elif counter == len(list_of_vals):
return counter
elif list_of_vals[-1]:
return counter
else:
return "No True's in your list"
print(min_successive_val_count(list_1))
print(min_successive_val_count(list_2))
print(min_successive_val_count(list_3))
print(min_successive_val_count(list_4))
print(min_successive_val_count(list_5))
输出:
1
2
No True's in your list
3
2
祝你好运(希望是我最后一次编辑;)来自,但使用max->min
import itertools
lst = [True, True, True, True, False, False, True, False, True, True, False]
x = min(sum(1 for _ in l) for n, l in itertools.groupby(lst))
>>> x
1
当我们遍历此列表时,让我们使用字典来记录真正的计数器
list = [True, True, False, True, True, False, False, False, False, True, True, True]
currentCounter = 0
record = []
def getMin (list):
for x in list:
if x:
currentCounter[0] = currentCounter[0]+1
else:
record.append(currentCounter)
currentCounter = 0
return secondSmallest(record)
#we need to get the second smallet number because always the smallest is equal 0
def secondSmallest(numbers):
m1, m2 = float('inf'), float('inf')
for x in numbers:
if x <= m1:
m1, m2 = x, m1
elif x < m2:
m2 = x
return m2
list=[True,True,False,True,False,False,False,False,True,True,True]
currentCounter=0
记录=[]
def getMin(列表):
对于列表中的x:
如果x:
currentCounter[0]=currentCounter[0]+1
其他:
record.append(当前计数器)
currentCounter=0
返回(记录)
#我们需要得到第二个smallet数,因为最小的总是等于0
def(数字):
m1,m2=浮点('inf'),浮点('inf'))
对于数字中的x:
如果x请分享您已尝试的内容,您可以获得中给出的列表值的最小值,该列表完全由False
组成,当您试图计算空列表的最小值时,该列表将崩溃,给我一分钟来编辑这篇文章,也完全失败了一个完全由<代码>真的< /代码>组成的列表。如果你正在考虑:考虑测试案例<代码> [false,false,false,true,true ] < /> >:DBtw:我注意到了这些事情,因为我现在正在编码的解决方案也在第一次尝试中失败了……这并不关心最短序列是由False
还是True
组成。例如,[True,True,True,False]
将产生x=1