python - 如何在恒定长度内找到两个字符串的所有可能排列

标签 python string combinations permutation python-itertools

我想在恒定长度 (5) 内找到两个字符串列表的所有可能排列。假设 list_1 = ["A"]list_2 = ["BB"]

所有可能的组合是:

A A A A A
A A A BB
A A BB A
A BB A A
BB A A A
A BB BB
BB A BB
BB BB A

我试图用下面的代码实现它,但我不确定如何为它定义长度 5。

import itertools 
from itertools import permutations 

list_1 = ["A"] 
list_2 = ["BB"] 
unique_combinations = [] 

permut = itertools.permutations(list_1, 5) 

for comb in permut: 
    zipped = zip(comb, list_2) 
    unique_combinations.append(list(zipped)) 

print(unique_combinations) 

最佳答案

使用递归:

list_1 = ["A"]
list_2 = ["BB"]
size = 5

strs = list_1 + list_2
res = []

def helper(strs, size, cur, res):
    if size == 0:
        res.append(cur)
        return
    if size < 0:
        return

    for s in strs:
        helper(strs, size-len(s), cur+[s], res)

helper(strs, size, [], res)
print(res)

无递归:

list_1 = ["A"]
list_2 = ["BB"]
size = 5

strs = list_1 + list_2
res = []

q = [[]]
while q:
    t = q.pop()
    for s in strs:
        cur = t + [s]
        cursize = len(''.join(cur))
        if cursize == size:
            res.append(cur)
        elif cursize < size:
            q.append(cur)
print(res)

关于python - 如何在恒定长度内找到两个字符串的所有可能排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64756919/

相关文章:

php - 按计算列循环时对数据排序

java - 递归组合生成器内存不足

python - 在python中生成鼠标键盘组合事件

python - 如何通过python连接以太网打印机?

python - 使用unittest和mock修补python函数中的变量

python - 在 Pandas 数据框中水平填充单元格值

c++ - 在 C++ 中将字符串作为函数调用

mysql - 将字符串添加到mysql结果

linux - GNU 并行组合,多次使用参数列表

python - BHV1750vi 数据库输入为 "Not all parameters were used in the SQL statement"