Recursion doesn't really make sense for your simple case with two strings. A pair of nested loops would be much easier.
It would make more sense to use recursion if you were trying to solve a more general problem of making combinations of an arbitrary number of strings. Then the general structure of recursion combined with iteration would make sense.
I'd do it like this, with a loop over the first string, and the recursion working on the remaining strings. A prefix
keyword-only argument (defaulting to an empty string) would get passed along to tell the code what characters had already been added, and the whole prefix would be printed when there were no strings left to pick characters from:
def combinations(*strings, prefix=""):
if not strings: # base case, no strings left to pick from
print(prefix)
return
for char in strings[0]: # iterate over the first string
combinations(*strings[1:], prefix=prefix+char) # recurse on the other strings
This would work for your current case combinations("ABC", "DEF")
, but would also work for more strings:
>>> combinations("AB", "CD", "EF", "GH")
ACEG
ACEH
ACFG
ACFH
ADEG
ADEH
ADFG
ADFH
BCEG
BCEH
BCFG
BCFH
BDEG
BDEH
BDFG
BDFH
If you didn't want to print the strings directly in the function, but rather return them to the caller, I'd write a recursive generator instead, which wouldn't need the prefix
stuff:
def combinations_gen(*strings):
if not strings:
yield ""
return
for char in strings[0]:
for rest in combinations_gen(*strings[1:]):
yield char + rest
You'd use this by iterating over its return value:
for val in combinations_gen("ABC", "DEF"):
print(val)