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]