我有整數串列,串列是回圈的。我想找到連續的重復項,而不是將重復數 1 放在起始位置。還需要這樣做,直到串列中沒有連續的重復項或串列為空。我嘗試了不同形式的 while 回圈,但無法達到我的目標。嘗試使用 回圈itertools.cycle,原因 -1 和 0 也是連續的,但無法洗掉或插入。找出何時停止也是問題,嘗試過int_list == list(set(int_list))但可能會有一些非連續的重復項,因此會造成無限回圈。下面是一個例子:
int_list = [1,1,1,2,3,4,5,6,7,7,8,8,9,10,8,11,4,12,15,13,14,14,15,16,1]
processed_list = [11,8,11,4,12,15,13,17]
編輯:
最初的問題出在這個Codewars kata 中。
uj5u.com熱心網友回復:
該deque是接近圓形名單,因為它允許旋轉串列。我在下面的代碼中利用了這一點。
該演算法將item[0]與下一項item[1]以及前一項(在回圈意義上)進行比較,item[-1]丟棄所有重復項并item[0]在發現任何重復項時增加原始項。
如果未找到重復項,則輪換串列并使用新的item[0].
如果有一個全長串列輪換但沒有找到重復,則該程序停止。
# Version 3
from collections import deque
def process(inp):
circ = deque(inp)
rcnt = 0 # rotations without finding a dup
while rcnt < len(circ):
n = circ[0]
isdup = False
while len(circ) >= 1 and circ[1] == n:
isdup = True
circ.popleft()
while len(circ) >= 1 and circ[-1] == n:
isdup = True
circ.pop()
if isdup:
circ[0] = n 1
rcnt = 0
else:
circ.rotate(1)
rcnt = 1
# print(list(circ)) # uncomment to watch the progress
return list(circ)
test = [1,1,1,2,3,4,5,6,7,7,8,8,9,10,8,11,4,12,15,13,14,14,15,16,1]
print(process(test))
使用未注釋的除錯print:
[2, 2, 3, 4, 5, 6, 7, 7, 8, 8, 9, 10, 8, 11, 4, 12, 15, 13, 14, 14, 15, 16]
[3, 3, 4, 5, 6, 7, 7, 8, 8, 9, 10, 8, 11, 4, 12, 15, 13, 14, 14, 15, 16]
[4, 4, 5, 6, 7, 7, 8, 8, 9, 10, 8, 11, 4, 12, 15, 13, 14, 14, 15, 16]
[5, 5, 6, 7, 7, 8, 8, 9, 10, 8, 11, 4, 12, 15, 13, 14, 14, 15, 16]
[6, 6, 7, 7, 8, 8, 9, 10, 8, 11, 4, 12, 15, 13, 14, 14, 15, 16]
[7, 7, 7, 8, 8, 9, 10, 8, 11, 4, 12, 15, 13, 14, 14, 15, 16]
[8, 8, 8, 9, 10, 8, 11, 4, 12, 15, 13, 14, 14, 15, 16]
[9, 9, 10, 8, 11, 4, 12, 15, 13, 14, 14, 15, 16]
[10, 10, 8, 11, 4, 12, 15, 13, 14, 14, 15, 16]
[11, 8, 11, 4, 12, 15, 13, 14, 14, 15, 16]
[16, 11, 8, 11, 4, 12, 15, 13, 14, 14, 15]
[15, 16, 11, 8, 11, 4, 12, 15, 13, 14, 14]
[14, 15, 16, 11, 8, 11, 4, 12, 15, 13, 14]
[15, 15, 16, 11, 8, 11, 4, 12, 15, 13]
[16, 16, 11, 8, 11, 4, 12, 15, 13]
[17, 11, 8, 11, 4, 12, 15, 13]
[13, 17, 11, 8, 11, 4, 12, 15]
[15, 13, 17, 11, 8, 11, 4, 12]
[12, 15, 13, 17, 11, 8, 11, 4]
[4, 12, 15, 13, 17, 11, 8, 11]
[11, 4, 12, 15, 13, 17, 11, 8]
[8, 11, 4, 12, 15, 13, 17, 11]
[11, 8, 11, 4, 12, 15, 13, 17]
[17, 11, 8, 11, 4, 12, 15, 13]
[13, 17, 11, 8, 11, 4, 12, 15]
the last line is the result:
[13, 17, 11, 8, 11, 4, 12, 15]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/382233.html
