You can use itertools.product for Cartesian products in general. Specifically, I would implement your algorithm in two separate steps:
- Parse the input string (e.g.
"1 0^ 1* 0^ 1"
) into a list of lists of integers; and
- Produce the product of the list of lists.
A relatively simple generator-based implementation, with a helper function for clarity, would look like:
def algorithm(input_):
# Step 1
instructions = []
for s in input_.split():
try:
instructions.append([int(s)])
except ValueError:
instructions.append(list(values(s)))
# Step 2
for prod in itertools.product(*instructions):
yield prod
def values(s):
RULES = {'*': 4, '^': 2}
n = int(s[:-1])
for x in range(RULES[s[-1]]):
yield n + x
For example:
>>> print("\n".join(" ".join(map(str, t)) for t in algorithm("1 0^ 1* 1")))
1 0 1 1
1 0 2 1
1 0 3 1
1 0 4 1
1 1 1 1
1 1 2 1
1 1 3 1
1 1 4 1
You will have to tinker with it to get the precise order (you appear to have an operator, rather than left-to-right, precedence) and formatting (e.g. spaces between groups) you're looking for.