Stqrosta
Stqrosta

Reputation: 350

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

I'm making a project in Python, and it involves a function that returns all possible combinations out of letters given as a parameter, but not all of the letters have to be used. This is my current function:

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']))

But it returns only the combinations that have all the letters given in them. It doesn't return combinations like:

abc
cba
de
ad

etc. Can anyone help me?

Upvotes: 0

Views: 108

Answers (2)

Mit
Mit

Reputation: 716

With the least possible changes to your code, the below should work:

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']))

Upvotes: 1

David
David

Reputation: 8318

You can do the following:

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']))))

This will generate any combination starting from length 1 till 5

Upvotes: 1

Related Questions