Search code examples
pythonstringpermutation

python - get all possible permutations with replacement without recursion


In python, how can I write a function that get some number n and print all possible words(a-z) permutations(with replacement) when length=n.

Without using recursion and without using external functions like itertools.permutations, itertools.combinations etc..

For example: n=2 should print

aa ba ... za
ab bb ... zb
...
az bz ... zz

n=3

aaa baa ... zaa
aba aca ... aza
aab aac ... aaz
abb abc ... abz
acb acc ... acz
...
azz bzz ... zzz  

Solution

  • Basically you are counting. Here is an example. A tried to keep it simple so it is easy to follow:

    def get_string(idxlist, item_list):
        return ''.join([item_list[i] for i in idxlist])
    
    def increment_vector(idxlist, max_count):
        idxlist[0] += 1
        for i in xrange(len(idxlist)-1):
            if idxlist[i] < max_count:
                break
            idxlist[i]=0
            idxlist[i+1] += 1
    
    def generate(n, item_list):
        max_count = len(item_list)
    
        idxlist = [0] * n
        while idxlist[-1] < max_count:
            print ( get_string( idxlist, item_list )),
            increment_vector(idxlist, max_count)
            if idxlist[0]==0:
                print 
    
    item_list = map(chr, range(97, 123)) # letters from a-z
    
    generate(3, item_list)
    

    The only point where you really work with your items is in get_string.

    EDIT: small adjustment so the output is formatted like in your question