首页 > 解决方案 > 如何每 3 个地方收集一个列表中的元素,直到没有剩余

问题描述

这是我必须做的:

[1,2,3,4,5,6,7] - 初始序列

[1,2,4,5,6,7] => 3 被计数并进入结果 [3]

[1,2,4,5,7] => 6 被计入结果 [3,6]

[1,4,5,7] => 2 被计入结果 [3,6,2]

[1,4,5] => 7 被计入结果 [3,6,2,7]

[1,4] => 5 被计入结果 [3,6,2,7,5]

[4] => 1 被计入结果 [3,6,2,7,5,1]

[] => 4 被计数并进入结果 [3,6,2,7,5,1,4]

标签: algorithm

解决方案


让我们考虑以下python代码:

s=[1,2,3,4,5,6,7]

result=[] 
cur_idx=0
while 1:
  print s,result
  if(len(s))==0:
    break
  if cur_idx<len(s)-2:
    cur_idx=cur_idx+2
  else:
    cur_idx= (len(s)-2+cur_idx) % len(s) -1
  result.append(s[cur_idx])
  del s[cur_idx]

几乎可以满足您的需求:

[1, 2, 3, 4, 5, 6, 7] []
[1, 2, 4, 5, 6, 7] [3]
[1, 2, 4, 5, 7] [3, 6]
[1, 4, 5, 7] [3, 6, 2]
[1, 4, 5] [3, 6, 2, 7]
[4, 5] [3, 6, 2, 7, 1]
[4] [3, 6, 2, 7, 1, 5]
[] [3, 6, 2, 7, 1, 5, 4]

实际上,区别在于7删除的时间,因为您考虑的是“虚拟索引”。我找到了一个繁琐的解决方案来管理这个:

s=[1,2,3,4,5,6,7]

result=[] 
cur_idx=0
while 1:
  print s,result,cur_idx,len(s)
  if(len(s))==1:
    result.append(s[0])
    s=[]
    print "final result:", result
    break
  if cur_idx<len(s)-2:
    cur_idx=cur_idx+2
  else:
    cur_idx= len(s)-cur_idx
    if cur_idx==len(s):
      cur_idx=0
  result.append(s[cur_idx])
  del s[cur_idx]
  if cur_idx==len(s):
      cur_idx=0

结果是:

[1, 2, 3, 4, 5, 6, 7] [] 0 7
[1, 2, 4, 5, 6, 7] [3] 2 6
[1, 2, 4, 5, 7] [3, 6] 4 5
[1, 4, 5, 7] [3, 6, 2] 1 4
[1, 4, 5] [3, 6, 2, 7] 0 3
[1, 4] [3, 6, 2, 7, 5] 0 2
[4] [3, 6, 2, 7, 5, 1] 0 1
final result: [3, 6, 2, 7, 5, 1, 4]


推荐阅读