简体   繁体   English

在列表中找到最大的重复数字序列

[英]finding the biggest sequence of repeating numbers in a list

The problem to solve is to find the biggest sequence of repeating numbers in a list.要解决的问题是在列表中找到最大的重复数字序列。 For example if the list was [2,3,4,4,4,5,4,7,6] and I was looking for the largest sequence of 4's, I would return 3.例如,如果列表是[2,3,4,4,4,5,4,7,6]并且我正在寻找最大的 4 序列,我将返回 3。

So far, I've only come up with a loop that counts the number of the specified number in a row but you have to account for the other numbers and also have a way to compare say, 3 "4's" in a row versus 2 "4's".到目前为止,我只提出了一个循环来计算连续指定数字的数量,但您必须考虑其他数字,并且还有一种方法可以比较连续 3 个“4”与 2 “4”。 any help would be appreciated任何帮助,将不胜感激

def find(list):
    x = [2,3,4,4,5,5,5,5,6,7,8]  
    print(find(x))

the code above is just the basic layout.上面的代码只是基本布局。 I don't need the answer to the whole function but just the main logic and explanations我不需要整个 function 的答案,只需要主要逻辑和解释

If you're trying to implement this in Python, you should use groupby .如果你想在 Python 中实现这个,你应该使用groupby itertools.groupby , by default, groups objects into tuples of (object_name, list_of_objects) , so: itertools.groupby默认情况下将对象分组为(object_name, list_of_objects)的元组,因此:

a = [1, 0, 1, 1, 2, 2, 2, 3]
groupby(a) ~ [(1, [1]), (0, [0]), (1, [1, 1]), (2, [2, 2, 2]), (3, [3])]
# I use "~" here because it's not actually a list, it's a generator, but meh

You can easily use a list comprehension to grab what you need.您可以轻松地使用列表推导来获取您需要的内容。

from itertools import groupby
repeat_lengths = [sum(1 for _ in group) for _, group in groupby(x)]
# the `sum(1 for _ in group)` is a workaround for the fact that `group` is not a list and has no length

Then just find the max of that list.然后只需找到该列表的最大值。

You need to keep track of two variables, the current count (count) of the consecutive values and the maximum count (max_count) so far.您需要跟踪两个变量,连续值的当前计数(count)和迄今为止的最大计数(max_count) When you observe a different value, you reset count and update max_count and continue the loop.当您观察到不同的值时,您重置count并更新max_count并继续循环。

def get_longest_seq(l, val):
  count = 0
  max_count = 0
  for e in l:
    if e == val:
      count += 1
    elif count > 0:
      max_count = max(max_count, count)
      count = 0
  max_count = max(max_count, max) # case when the sequence is at the end
  return max_count

l = [2,2,3,2,2,2,2,3,3,4,4,4,5,4,4,7,6]
print(get_longest_seq(l, 4))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM