1
votes

When I run this code I don't get all the possible combinations of 3 characters:

def comb(iterable, r):
    pool = tuple(iterable)
    n = len(pool)
    for indices in permutations(range(n), r):
        if sorted(indices) == list(indices):
            yield tuple(pool[i] for i in indices)
def start():
    for x in comb("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ12234567890!@#$%^&*?,()-=+[]/;",3):
        print x

Instead it skips some. When I repeated the characters 3 times, I got all the combinations I needed, but I get some multiple times. This takes triple the time and isn't what I want. I'm going to be calculating millions of of combinations so I need to to know an alternative to repeating the characters.

1
Lets say you wanted length 2 instead of instead of 3, and you had abcd as your string. What would you want the output to be? ab, ac, ad, bc, bd, cd? aa, ab, ac, ad, bb, bc, bd, cc, cd, dd? aa, ab, ac, ad, ba, bb, bc, bd, ca, cb, cc, cd, da, db, dc, dd? ab, ac, ad, ba, bc, bd, ca, cb, cd, da, db, dc? Something else? - agf
aa, ab, ac, ad, ba, bb, bc, bd, ca, cb, cc, cd, da, db, dc, dd is the output I'm looking for. - Noah R
In case you do not find a way to do w/o the long string literal, you may want to look at what you can import from string. E.g., from string import printable print printable yields 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;<=>?@[\]^_{|}~` without error (in your example 2 is listed twice, and other characters might be missing) Smaller specific subsets are available too, like ascii_lowercase, ascii_uppercase, punctuation and digits - Levon
People would be having a hard time understanding the question. This requires rewording. - Abhijit
@Abhijit all the info we needed was in his comment :) - agf

1 Answers

7
votes

You're looking for itertools.product(characters, repeat = 3).

See the itertools.product docs.

>>> ' '.join(''.join(x) for x in itertools.product('abcd', repeat = 2))
aa ab ac ad ba bb bc bd ca cb cc cd da db dc dd