Python列表中连续重复项的最长序列

3
如前所述,运行是指连续重复值的序列。实现一个名为longest_run的Python函数,它接受一个数字列表并返回最长运行的长度。例如,在以下序列中: 2, 7, 4, 4, 2, 5, 2, 5, 10, 12, 5, 5, 5, 5, 6, 20, 1 最长运行的长度为4。然后,在主程序中,您的程序应该要求用户输入列表,然后调用longest_run函数并输出结果。
这是我尝试的代码,但它只返回1,我不知道为什么。在此问题中,无法导入任何模块。
def longest_run(aList):
  '''(list)->int
  Returns length of the longest run
  Precondition: aList is a list of a len of at least 2 and elements of list are ints
  '''
  count=0
  bucket=[]
  for i in aList:
    if bucket==i:
        count=count+1
    else:
        bucket=i
        count=1
  return count
4个回答

6
您的代码中最大的错误是设置bucket=[](即一个列表)并稍后将其设置为整数。
此外,您需要存储最长序列、当前序列长度(初始化为1)和上次出现的值,因此需要比您目前存储的变量更多。
每当值与以前相同时,增加计数器。如果不同,请在检查它是否不大于最大值之后重置计数器。最后再次执行最大测试,以防最长序列在结尾(经典错误)。
像这样:
seq = [2, 7, 4, 4, 2, 5, 2, 5, 10, 12, 5, 5, 5, 5, 6, 20, 1]

result=1
max_result=0
last_seen=seq[0]

for v in seq[1:]:
    if v==last_seen:
        result += 1
    else:
        if result > max_result:
            max_result = result
        last_seen = v
        result = 1

# just in case the longest sequence would be at the end of your list...
if result > max_result:
    max_result = result

print(max_result)

当你最终被允许使用Python标准库时,可以使用itertools.groupby函数并计算序列长度的最大值:

max(sum(1 for x in v) for _,v in itertools.groupby(seq))

0

所以你想要在列表中找到最长的相同数字序列?因为你之前写的代码有点令人困惑。

你应该保留两个版本的计数器:maxCount(你将要返回的)和actualCount(你将要递增的),遍历整个列表并比较当前数字和下一个数字。如果它们相同,actualCount += 1,否则,在每次迭代结束时,actualCount = 0,比较maxCountactualCount,如果actualCount大于maxCount = actualCount

def longest_run(aList):

    maxCount = 1
    actualCount = 1

    for i in range(len(aList)-1):
        if aList[i] == aList[i+1]:
            actualCount += 1
        else:
            actualCount = 1
        if actualCount > maxCount:
            maxCount = actualCount

    return(maxCount)

然后我会发布一个简单的代码,请告诉我它是否有效。 - Alessandro Petric

0

当您的循环处于最后一次迭代时,您会得到1

bucket = 20i = 1,这意味着bucket!= i,因此循环进入else子句并分配count = 1,退出并返回函数返回值,即1。

建议:

1)当您遇到此类错误时,请尝试手动运行代码/逻辑-它有助于解决问题。

2)对于这个问题,每当一个运行结束时,您都会忘记最后一个运行长度,请考虑如何“记住”最长的运行时间。


0
您可以使用以下方法:(每个数字的重复次数)
mylist = [2, 7, 4, 4, 2, 5, 2, 5, 10, 12, 5, 5, 5, 5, 6, 20, 1]
my_dict = {i:mylist.count(i) for i in mylist}
mylist = list(dict.fromkeys(mylist))
R_list=[]
for i in mylist:
    print("%s repeated %s" %(i,my_dict[i]))
    R_list = R_list+[my_dict[i]]
print(R_list)
print(max(R_list))  

OP 询问的是“最长重复长度”,而不是出现次数的总数。 - eliu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接