1

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  
8
  • 3
    See the code in the documentation docs.python.org/3/library/itertools.html#itertools.combinations Commented Feb 27, 2016 at 17:14
  • I think it is important that you say 'with replacement'... at least that is what you are doing in your examples Commented Feb 27, 2016 at 17:17
  • 1
    The correct link for combinations_with_replacement is here: docs.python.org/3/library/… Commented Feb 27, 2016 at 17:19
  • @mtk99 this examples doenst print the opposite (print "ab" but doesnt print "ba"). I can use "reverse" but I'm pretty sure there is better way Commented Feb 27, 2016 at 17:25
  • itertools.permutations Commented Feb 27, 2016 at 17:27

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.