0

I am creating a program to generate a list of numbers in lexicographical order and I need nested for loops based on the number of elements in the input. I'd like to dynamically allocate/create nested for loops based on the number of elements in the input.

def bounded_lists(upper_bounds):            
    res = []
    for i in range(0,max(upper_bounds) + 1):
        for j in range(0,max(upper_bounds) + 1):
            for k in range(0,max(upper_bounds) + 1):
                if i<=upper_bounds[0] and j<=upper_bounds[1] and k<=upper_bounds[2]:
                    res.append([i,j,k])
    return res

This code gives me the right result and is straightforward if I know that the number of elements in the input is 3.

  • The answer to the problem, as you formulated it here: https://stackoverflow.com/questions/52456836/dynamically-generating-a-flexible-number-of-nested-for-loops/52457417#52457417 - The solution better is to use `itertools` though. – Reblochon Masque May 03 '19 at 01:17
  • `itertools.product`. Or, looking at your problem, a more cleverly written recursive solution would work without needing the `if` to filter... – Mateen Ulhaq May 03 '19 at 01:18
  • @MateenUlhaq A point just for the `if`. The `max(upper_bounds)` code should be replaced with `upper_bounds[0]`, `upper_bounds[1]` ... respectfully. Therefore the `if` statement is no longer required. – Rockybilly May 03 '19 at 01:33

1 Answers1

0

You are looking for itertools.product.

An example of this in action might be

from itertools import product

def bounded_lists(inlists):
    return list(product(*inlists))

arr = [[1, 2], [3, 4, 5], [6]]
print(bounded_lists(arr))
# This prints
# [(1, 3, 6), (1, 4, 6), (1, 5, 6), (2, 3, 6), (2, 4, 6), (2, 5, 6)]
# This is in lexicographical order according to the orders of the lists in arr.
davidlowryduda
  • 2,404
  • 1
  • 25
  • 29
  • As an addition, for the input given by the OP, product should be used as such: `lst = list(range(i + 1) for i in upper_bounds); return list(itertools.product(*lst))` – Rockybilly May 03 '19 at 01:34