Skip to content Skip to sidebar Skip to footer

How Can I Simplify These Nested For Loops?

I would like to make this simplified so that I can control how many nested for loops there are. Essentially this would be 3 for d1 in ['left','right','up','down']: for d2 in Cr

Solution 1:

You could pretty easily do this with a recursive generator function:

defgen(values, value_list_factory, depth):
    if depth == 0: # base caseyield ()
        returnfor x in values:
        for rest in gen(value_list_factory(x), value_list_factory, depth-1):  # recurse!yield x, *rest

You've not specified how your CreateDirectionList function works, so here's an example of my generator working with a factory function that removes the passed in value from the starting sequence of ['left','right','up','down'] (this means you never get the same value twice in a row).

directions = ['left','right','up','down']

defcreate(dir):
    return [x for x in directions if x != dir]

for d1, d2, d3 in gen(directions, create, 3):
    print(d1, d2, d3)

The output is:

leftrightleftleftright up
leftright down
left up leftleft up rightleft up down
left down leftleft down rightleft down up
rightleftrightrightleft up
rightleft down
right up leftright up rightright up down
right down leftright down rightright down up
up leftright
up left up
up left down
up rightleft
up right up
up right down
up down left
up down right
up down up
down leftright
down left up
down left down
down rightleft
down right up
down right down
down up left
down up right
down up down

Solution 2:

yeah recursion is your friend.

def CreateDirectionList(d):
    ifd== "left"ord== "right":
        return ['up','down']
    ifd== "up"ord== "down":
        return ['left','right']

def nMoreSteps(d,n):
    ifn== 0:
        return [[d]]
    else:
        results = []
        for k in CreateDirectionList(d):
            for k2 in nMoreSteps(k,n-1):
                results.append([d]+k2)
        return results

def nSteps(n):
    results = []
    for d1 in ['left','right','up','down']:
        results += nMoreSteps(d1,n-1)
    return(results)

for k in nSteps(4):
    print(k)

Post a Comment for "How Can I Simplify These Nested For Loops?"