python列表中最长的连续重复序列 [英] Longest sequence of consecutive duplicates in a python list

查看:75
本文介绍了python列表中最长的连续重复序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如前所述,运行是连续重复值的序列.实现一个名为longest_run的Python函数,该函数获取一个数字列表并返回最长运行时间的长度.例如,按顺序: 2、7、4、4、2、5、2、5、10、12、5、5、5、5、6、20、1 最长运行的长度为 4 .然后,在主程序中,程序应要求用户输入列表,然后应调用longest_run函数并打印结果.

As mentioned, a run is a sequence of consecutive repeated values. Implement a Python function called longest_run that takes a list of numbers and returns the length of the longest run. For example in the sequence: 2, 7, 4, 4, 2, 5, 2, 5, 10, 12, 5, 5, 5, 5, 6, 20, 1 the longest run has length 4. Then, in the main, your program should ask the user to input the list, then it should call longest_run function, and print the result.

这是我尝试过的方法,但只返回1,我不明白为什么.我无法为此问题导入任何模块.

This is what I tried but it only returns 1 and I don't understand why. I can't import any modules for this question.

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

推荐答案

你的代码最大的错误是将 bucket=[] (这是一个列表)设置为一个整数.

The biggest mistake of your code is to set bucket=[] (which is a list) and later to an integer.

此外,您需要存储最长的序列和当前的序列长度(初始化为1)以及最后看到的值,因此存储的变量比存储的更多.

Also, you need to store the longest sequence and the current sequence length (initialized to 1) and the last seen value, so more variables than you're storing.

每个时间值与以前相同,增加计数器.如果不同,请在检查计数值是否不超过最大值后将其复位.最后,以防万一最长的序列(经典错误)再次执行最大测试

Each time value is the same as before, increase counter. If it's different, reset counter after having checked if it's not greater than the max. In the end perform the max test again just in case the longest sequence is in the end (classic mistake)

像这样:

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 并计算序列长度的最大值:

When you're finally allowed to use python batteries, use itertools.groupby and compute the max of the sequence lengths:

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

这篇关于python列表中最长的连续重复序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆