[英]Python: Longest Plateau Problem: to find the length and location of the longest contiguous sequence of equal values
[英]How to find the longest length adjacent integer values in a sequence
对于这个问题,我想在一个序列中获得最长的相邻整数。 我觉得我接近答案,但不知道如何解决它。 谁能帮帮我?
输入: [1, 2, 5, 5, 5, 6, 6, 6, 8, 8]
预期 Output: 12(555)66688
我的 output: 12(555)6(66)8
我的代码:
L = [1, 2, 5, 5, 5, 6, 6, 6, 8, 8]
print(L)
inRun = False
last = None
max_value = 0
count = 0
for i in range(len(L) - 1):
if inRun:
if L[i] != L[i - 1]:
if count > max_value:
max_value = count
last = i
print(')', end='')
inRun = False
count = 0
else:
count += 1
else:
if L[i] == L[i + 1]:
count += 1
print('(', end='')
inRun = True
print(L[i], end='')
if inRun:
print(')'
编辑
使用 collections 的简化代码。 此外,我添加了序列中元素的第一个和最后一个索引。
from collections import Counter
L = [1, 2, 5, 5, 5, 6, 6, 6, 8, 8, 8]
print(L)
cnt = Counter(L)
value, max_value = cnt.most_common(1)[0]
firstIndex = L.index(value)
before_seq = ''.join(str(n) for n in L[:firstIndex])
seq = ''.join(str(n) for n in L[firstIndex : firstIndex + max_value])
after_seq = ''.join(str(n) for n in L[firstIndex + max_value:])
print("{}({}){}".format(before_seq, seq, after_seq))
print("first index: {}\nlast index: {}".format(firstIndex, firstIndex + max_value - 1))
上一个答案
我为您准备了两个解决方案,因为我不知道您所说的“最长运行”到底是什么意思,而且我也不知道您的代码中哪里有问题。 在第一个代码中,您有一个 output: 12(555)(666)88。 在第二个你有:12(555)66688。 我希望我有所帮助:)
第一: Output 12(555)66688
L = [1, 2, 5, 5, 5, 6, 6, 6, 8, 8]
print(L)
max_value = 0
count = 1
for i in range(len(L)):
for j in range(i + 1, len(L)):
if L[i] == L[j]:
count = count + 1
else:
if max_value < count:
max_value = count
count = 1
break
if max_value < count:
max_value = count
count = 1
index = 0
count = 1
for i in range(len(L)):
for j in range(index + 1, len(L)):
if L[index] == L[j]:
count = count + 1
else:
break
if count == max_value:
print('(', end='')
for k in range(index, index + max_value):
print(L[k], end='')
print(')', end='')
index = index + max_value
count = 1
max_value = max_value + 1
else:
for k in range(index, index + count):
print(L[k], end='')
index = index + count
count = 1
if index >= len(L):
break
第二Output 12(555)(666)88
L = [1, 2, 5, 5, 5, 6, 6, 6, 8, 8]
print(L)
max_value = 0
count = 1
for i in range(len(L)):
for j in range(i + 1, len(L)):
if L[i] == L[j]:
count = count + 1
else:
if max_value < count:
max_value = count
count = 1
break
if max_value < count:
max_value = count
count = 1
index = 0
count = 1
for i in range(len(L)):
for j in range(index + 1, len(L)):
if L[index] == L[j]:
count = count + 1
else:
break
if count == max_value:
print('(', end='')
for k in range(index, index + max_value):
print(L[k], end='')
print(')', end='')
index = index + max_value
count = 1
else:
for k in range(index, index + count):
print(L[k], end='')
index = index + count
count = 1
if index >= len(L):
break
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.