[Tutor] variable numbers of for loops

Jose Amoreira ljmamoreira at gmail.com
Tue Nov 23 14:16:46 CET 2010


Hi,
This is a somewhat algorithmic question, not strictly pythonic. I was writing 
a program to generate all possible n-letter words with letters taken from an 
alphabet (I mean, if the alphabet is ['a','b'] the one-letter words are 'a' 
and 'b', the two letter words are 'aa', 'ab', 'ba', 'bb' and so on).

I wrote a recursive function that does the job easy enough, but I read 
somewhere that for any recursive algorithm there is a sequential one that is 
equivalent, in the sense that the same output is produced for the same inputs. 
Now the easiest way to solve my n-letter problem sequentially is to, for each 
of the n letters that compose the word, cycle through all the possibilities 
allowed for in the alphabet. However, in this solution the value of n (the 
length of the words) is hardwired, you have to write different programs (with 
different numbers of for loops) for each value of n.

I managed to work around that problem by writing the following function, that 
generates different programs, depending on the value of n,exec's it and 
returns the results:

def allwrds(alphabet,n):
    ind = '    '
    prog = "listOfWords=[]\n"
    for i in range(n):
        prog += i*ind + 'for l' + str(i) + ' in alphabet:\n'
    prog += n*ind + 'word = "".join([eval("l"+str(i)) for i in range(n)])\n'
    prog += n*ind + 'listOfWords.append(word)\n'
    #print prog   #Uncomment to see the generated program
    exec(prog)
    return listOfWords

This works fine (comments are welcome, of course) but I find this approach (to 
write programs that write programs that solve the problem) somehow twisted (to 
say the least).

Is there a more straightforward way of solving my specific problem or, better 
yet, a general solution to the need of a variable number of for loops?  
Thanks
Jose


More information about the Tutor mailing list