Constraints
- Your function can only have one parameter
- You can't have default parameters
Strategy
We change accum into a stack (i.e. list) that contains the values it would
have at various levels of a recursive function
Meets Constraints
def combine(terms):
last = (len(terms) == 1)
n = len(terms[0])
for i in range(n):
# use top value in accum stack i.e. accum[-1]
item = accum[-1] + terms[0][i]
if last:
combinations.append(item)
else:
# append to accum stack
# (similar to what woould happen if we where passing it as a recursive parameter)
accum.append(item)
combine(terms[1:])
accum.pop() # returning from recursive function so remove top
# value from stack
Usage
# Initializations
a = [['ab','cd','ef'],['12','34','56']]
combinations = []
accum = [''] # stack which will hold accum for diferent levels of recursion
combine(a)
print(combinations)
Output
['ab12', 'ab34', 'ab56', 'cd12', 'cd34', 'cd56', 'ef12', 'ef34', 'ef56']
Caveat
I don't understand your constraint, but the function is simpler written as follows.
def combine(terms, accum = None, combinations = None):
# Assign values for default parameters
if accum is None:
accum = ''
if combinations is None:
combinations = []
last = (len(terms) == 1)
n = len(terms[0])
for i in range(n):
item = accum + terms[0][i]
if last:
combinations.append(item)
else:
combine(terms[1:], item, combinations)
return combinations # we return the combinations rather than using an external global
Test
a = [['ab','cd','ef'],['12','34','56']]
print(combine(a))
# ['ab12', 'ab34', 'ab56', 'cd12', 'cd34', 'cd56', 'ef12', 'ef34', 'ef56']