我如何在数字对列表中找到最长的子列表,其差异为 1。所以“数字邻居”可以是元素 1 和 2 或元素 7 和 6。
如果列表是 [7, 1, 2, 5, 7, 6, 5, 6, 3, 4, 2, 1, 0],那么所需的输出应该是 4。子列表将是 [7, 6、5、6]。
这就是我现在所拥有的。for 循环公式真的坏了,我不知道如何解决这个问题。
list = [7, 1, 2, 5, 7, 6, 5, 6, 3, 4, 2, 1, 0]
sublist = []
for i in list:
if list[i] - list[i+1] == 1 or list[i] - list[i+1] == -1:
sublist.append(i)
print(sublist)
print(len(sublist))
最好将这些类型的问题分解成各个部分
这里的主要问题是获取所有顺序序列
def get_sequences_iter(an_array):
# start a new sequence with first value (or empty)
sequence = an_array[:1]
# check each index with the value that comes before
for idx in range(1,len(an_array)):
if an_array[idx] - an_array[idx-1] in {1,-1}:
# this is part of a run append it
sequence.append(an_array[idx])
else:
# run is broken
yield sequence
# start a new run
sequence = [an_array[idx]]
#capture final sequence
yield sequence
一旦你有了这个,你可以在 O(n) 时间内得到一个列表中的所有运行
sequences = get_sequences_iter([7, 1, 2, 5, 7, 6, 5, 6, 3, 4, 2, 1, 0])
for sequence in sequences:
print(sequence)
希望有了这些信息,您可以弄清楚如何解决您的实际问题
但以防万一
print(max(sequences,key=len))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句