![](/img/trans.png)
[英]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.