Usually, if you have an algorithm that will actually need an arbitrary number of loops inside each other, you use just recursive functions.
You place a single loop in the recursive function - and, if necessary, it calls it again.
In that case, it could be:
def combine_sequences(sequences, combination=(), result=None):
if result is None:
result = []
if not sequences:
if combination:
result.append(combination)
return result
for element in sequences[0]:
combine_sequences(sequences[1:], combination + (element,), result)
return result
So the logic basically is: if the received sequence containing the other subsequences is empty, return the current result. The key is to pass to the function itself the partial result of the "above" executions - in this case the composition combination + (element,)
.
In the case of this algorithm, however, it is possible to do interactively as well - just keep the partial results of each sub-sequence, and for each element in the next sequence, also process all previous partial results. You only need 2 bows.
def combine_seq(seq):
result = []
for subseq in seq:
if not result:
for element in subseq:
result.append((element,))
else:
new_result = []
for element in subseq:
for combination in result:
new_result.append(combination + (element,))
result = new_result
return new_result
And finally, again, for this specific algorithm, as well as some others, Python has the function ready in the standard library.
The way itertools
allows this (under the name of product
) and various other combinations of elements - in this case:
In [230]: import itertools
In [232]: list(itertools.product(*[(1,2), (3,4, 5), (5, 6)]))
Out[232]:
[(1, 3, 5),
(1, 3, 6),
(1, 4, 5),
(1, 4, 6),
(1, 5, 5),
(1, 5, 6),
(2, 3, 5),
(2, 3, 6),
(2, 4, 5),
(2, 4, 6),
(2, 5, 5),
(2, 5, 6)]
I don’t understand your point. Is there any example of how you would want to use this structure?
– Jefferson Quesado
It smells like recursiveness to me, but it’s really not clear what you want to know.
– Woss
You need to generate all possible combinations?
– Woss
yes, this is a piece of a Joy Force.
– Joao
If N varies, it is case of recursion or some kind of stacking.
– Bacco