Create every possible string combination by the abc

Viewed 159

I'm trying to create something that will generate every possible combination for a word until 4 chars.

for example will start as a,b,c...aa,ab,ac...aaa,aab,aac...aaaa,aaab,aaac....zzzx,zzzy,zzzz

closest thing that i cam close to, was this:

import itertools
for i in range(4):
    for combination in itertools.combinations('abcdefghijklmnopqrstuvwxyz-([{0123456789', i):
        word = str(combination).replace("'", '').replace("(", '').replace(")", '').replace(" ", '').replace(",", '')
        print(word)

the problem with this, is that it does not create combinations with same characters, like aa,bb,cc.

2 Answers

Just use combinations_with_replacement instead of combinations.

from itertools import combinations_with_replacement

list(combinations_with_replacement('abc', 3))
[('a', 'a', 'a'),
 ('a', 'a', 'b'),
 ('a', 'a', 'c'),
 ('a', 'b', 'b'),
 ('a', 'b', 'c'),
 ('a', 'c', 'c'),
 ('b', 'b', 'b'),
 ('b', 'b', 'c'),
 ('b', 'c', 'c'),
 ('c', 'c', 'c')]

Since order is meaningful- itertools.product is the way to go:

import itertools
for i in range(4):
    for combination in itertools.product('abcdefghijklmnopqrstuvwxyz-([{0123456789', repeat=i):
        word = ''.join(combination)
        print(word)
Related