我試圖創建一個生成器函數中:幫助與邏輯發生器功能
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/查詢。 –