python生成序列_Python:从具有字符限制的列表中生成所有可能的序列组合

一种方法是迭代输入列表并逐步构建组合.在每个步骤中,从输入列表中取出下一个字符并将其添加到先前生成的组合中.

from collections import defaultdict

def make_combinations(seq,maxlen):

# memo is a dict of {length_of_last_word: list_of_combinations}

memo = defaultdict(list)

memo[1] = [[seq[0]]] # put the first character into the memo

seq_iter = iter(seq)

next(seq_iter) # skip the first character

for char in seq_iter:

new_memo = defaultdict(list)

# iterate over the memo and expand it

for wordlen,combos in memo.items():

# add the current character as a separate word

new_memo[1].extend(combo + [char] for combo in combos)

# if the maximum word length isn't reached yet,add a character to the last word

if wordlen < maxlen:

word = combos[0][-1] + char

new_memo[wordlen+1] = newcombos = []

for combo in combos:

combo[-1] = word # overwrite the last word with a longer one

newcombos.append(combo)

memo = new_memo

# flatten the memo into a list and return it

return [combo for combos in memo.values() for combo in combos]

输出:

[['a','cd']]

对于短输入,此实现比天真的itertools.product方法慢:

input: a b c d

maxlen: 2

iterations: 10000

itertools.product: 0.11653625800136069 seconds

make_combinations: 0.1657387from collections import defaultdict

def make_combinations(seq,add a character to the last word

if wordlen < maxlen:

word = combos[0][-1] + char

new_memo[wordlen+1] = newcombos = []

for combo in combos:

combo[-1] = word # overwrite the last word with a longer one

newcombos.append(combo)

memo = new_memo

# flatten the memo into a list and return it

return [combo for combos in memo.values() for combo in combos]

41118 seconds

但是当输入列表更长时,它会快速恢复:

input: a b c d e f g h i j k

maxlen: 2

iterations: 10000

itertools.product: 6.9087735799985240 seconds

make_combinations: 1.2037671390007745 seconds

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值