我试图创建一个生成器函数中:帮助与逻辑发生器功能
def combinations(iterable, r, maxGapSize):
maxGapSizePlusOne = maxGapSize+1
pool = tuple(iterable)
n = len(pool)
if r > n:
return
indices = list(range(r))
while True:
for i in reversed(range(r)):
if indices[i] != i + n - r:
break
else:
return
indices[i] += 1
for j in range(i+1, r):
indices[j] = indices[j-1] + 1
previous = indices[0]
for k in indices[1:]:
if k-previous>maxGapSizePlusOne:
isGapTooBig = True
break
previous = k
else:
isGapTooBig = False
if not isGapTooBig:
print(indices)
combinations(("Aa","Bbb","Ccccc","Dd","E","Ffff",),2,1)
我打印出来,我想用它来选择所谓的“迭代”的说法元素的索引调试目的。这给了我:
[0, 2] [1, 2] [1, 3] [2, 3] [2, 4] [3, 4] [3, 5] [4, 5]
,因为这是其他地方生产的忽略[0,1]
...
这正是我想要的,但我猜我的代码,它过于复杂,效率低下。 iterable
的大小很可能是成千上万,而且很可能是maxGapSize < 5
。
任何提示,以帮助我做得更好?
你没有解释它应该做什么。 – agf
如果您的代码已经正常工作,但您希望使其更好,则可以在http://codereview.stackexchange.com/查询。 –