[Tutor] variable numbers of for loops

Andre Engels andreengels at gmail.com
Tue Nov 23 14:47:27 CET 2010


On Tue, Nov 23, 2010 at 2:16 PM, Jose Amoreira <ljmamoreira at gmail.com> 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, andreengels at gmail.com


More information about the Tutor mailing list