On Tue, Nov 23, 2010 at 2:16 PM, Jose Amoreira <[email protected]> wrote:
> 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?
If you need a variable number of loops, put the loops themselves in a
loop, which you go through the required number of times. In your case
I would do:
def allwrds(alphabet,n):
result = [""] # for n=0, we have a single empty string
for _ in range(n):
result = [w+letter for letter in alphabet for w in result]
return result
Or, in case you are not comfortable with list comprehension (or want
easy translation to a language without such a powerful tool):
def allwrds(alphabet,n):
result = [""] # for n=0, we have a single empty string
for _ in range(n):
tempwrds = []
for w in result:
for letter in alphabet:
tempwrds.append(w+letter)
result = tempwrds
return result
--
André Engels, [email protected]
_______________________________________________
Tutor maillist - [email protected]
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor