algorithm - 如何每 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]
解决方案
让我们考虑以下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]
推荐阅读
- python - Arduino 和 Python 之间通过 UDP 进行通信
- swift - UITableViewCell 标题定位
- swift - SKSpriteNode 子类位置问题
- swift - 如何在其实现中替换 self
- php - 如何在不禁用操作按钮的情况下禁用列?
- python - python消除几乎重复的CSV
- django - NoReverseMatch 与 slug 变量,适用于硬编码值
- javascript - 如何使用javascript根据项目更改文本颜色?
- python - pynput 似乎无法处理大写锁定键
- python - 如何合并具有多个字符替换的两个字符串列表