i have following list:
list = ['abc', 'def', 'ghi']
what best way write recursive function pick 1 letter each group of 3 , return possible combinations/permutations:
e.g. output follows:
a, ad, adg, adh, adi, aeg, aeh, aei, afg, afh, afi
b, bd, bdg, bdh, bdi, beg, beh, bei, bfg, bfh, bfi
c, cd, cdg, cdh, cdi, ceg, ceh, cei, cfg, cfh, cfi
d, dg, dga, dgb, dgc, dha, ... , on ...
i'm learning recursive functions. have spend 7 straight hours on problem far , still near. appreciated!
consider empty list, result empty list (this 'base case'), i.e.
f([]) == ""
for non-empty list, take each character of first list element (the 'head' of list) , prepend each string returned recursively applying function remainder (the 'tail') of list (this 'recursive case'):
f(['abc']) == 'a' + f([]), 'b' + f([]), 'c' + f([]) == 'a' + '', 'b' + '', 'c' + '' == 'a', 'b', 'c' f(['abc', def']) == 'a' + f(['def']), 'b' + f(['def']), 'c' + f(['def']) == 'a' + 'd' + f([]), 'a' + 'e' + f([]), 'a' + 'f' + f([]), 'b' + 'd' + f([]) ... == 'ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf'
in python, expressed (somewhat inefficient , verbose, point show algorithm):
def f(xs): if not xs: yield '' else: head = xs[0] tail = xs[1:] char in head: yield char s in f(tail): yield char + s
calling function like
print list(f(['abc', 'def', 'ghi']))
prints
['a', 'ad', 'adg', 'adg', 'adh', 'adh', 'adi', 'adi', 'ae', 'aeg', 'aeg', 'aeh', 'aeh', 'aei', 'aei', 'af', 'afg', 'afg', 'afh', 'afh', 'afi', 'afi', 'b', 'bd', 'bdg', 'bdg', 'bdh', 'bdh', 'bdi', 'bdi', 'be', 'beg', 'beg', 'beh', 'beh', 'bei', 'bei', 'bf', 'bfg', 'bfg', 'bfh', 'bfh', 'bfi', 'bfi', 'c', 'cd', 'cdg', 'cdg', 'cdh', 'cdh', 'cdi', 'cdi', 'ce', 'ceg', 'ceg', 'ceh', 'ceh', 'cei', 'cei', 'cf', 'cfg', 'cfg', 'cfh', 'cfh', 'cfi', 'cfi']
Comments
Post a Comment