如何用字母做出所有可能的组合,但又不是所有的字母都需要用到?

How to make all possible combinations out of letters, but not all of the letters need to be used?

我正在 Python 中做一个项目,它涉及一个函数,该函数 return 将所有可能的字母组合作为参数,但并非所有字母都必须是用过的。 这是我当前的功能:

from itertools import product
def algorithm(letters):
    possible = [''.join(combination) for combination in product(letters, repeat=len(letters))]
    return possible
print(algorithm(['a','b','c','d','e']))

但它 return 只是其中包含所有字母的组合。它不会 return 组合,例如:

abc
cba
de
ad

等 谁能帮帮我?

您可以执行以下操作:

import itertools

def generate(vals):
    return ("".join(x) for x in itertools.chain.from_iterable(itertools.permutations(vals,i+1) for i in range(0,len(vals))))

print(list(generate("".join(['a','b','c','d','e']))))

这将生成从长度 1 到 5 的任意组合

只要对您的代码进行尽可能少的更改,下面的代码应该可以工作:

def algorithm(letters):
    allPoss = list()
    for i in range(1, len(letters)+1):
        possible = [''.join(combination) for combination in product(letters, repeat= i)]
        allPoss.append(possible)
    return allPoss
print(algorithm(['a','b','c','d','e']))