1 回答

TA貢獻1827條經驗 獲得超8個贊
這是一種適合遞歸解決方案的問題,因此這里有一個可能的替代實現。(抱歉,我還沒有嘗試掌握您的代碼,也許其他人會。)
def sequences(a, b, start_index=0, min_val=None):
"""
yields a sequence of lists of partial solutions to the original
problem for sublists going from start_index to the end of the list
subject to the constraint that the first value cannot be less than
min_val (if not None)
Example: with a=[3,4,5,6], b=[6,5,0,4], start_index=2, minval=4,
it is looking at the [5,6] and the [0,4] part, and it would yield
[4,5] [4,6] and [5,6]
If the start index is not already the last one, then it uses a
recursive call.
"""
limits = a[start_index], b[start_index]
lower = min(limits)
higher = max(limits)
if min_val is not None and min_val > lower:
lower = min_val # impose constraint
options = range(lower, higher + 1)
is_last = start_index == len(a) - 1
for val in options:
if is_last:
yield [val]
else:
# val followed by each of the lists from the recursive
# callback - passing min_val=val+1 imposes the constraint
# of strictly increasing numbers
for seq in sequences(a, b, start_index+1, min_val=val+1):
yield [val, *seq]
for seq in sequences([1,3,1,6], [6,5,4,4]):
print(seq)
這給出:
[1, 3, 4, 5]
[1, 3, 4, 6]
[2, 3, 4, 5]
[2, 3, 4, 6]
請注意,我并不是說上面的方法特別有效:遞歸函數可能會使用相同的參數被調用不止一次——例如,無論您是從 1,3 還是 2,3 開始,它都會進行相同的計算來工作了解接下來會發生什么——因此您可能希望在將其用于大型列表之前實施某種緩存。顯然,緩存有內存開銷,因此制定最佳整體策略來應對這一問題可能是一個相當困難的問題。
添加回答
舉報