Python recursion -
i have generate possible combinations of letters represents number sequence in telephone... example: if entry '423', output should be:
gad gae gaf gbd gbe gbf gcd gce gcf had hae haf hbd hbe hbf hcd hce hcf iad iae iaf ibd ibe ibf icd water ice icf
i must utilize recursion solve this... started using dictionary this:
dic = {'2' : 'abc', '3' : 'def', '4' : 'ghi', '5' : 'jkl', '6' : 'mno', '7' : 'pqrs', '8' : 'tuv', '9' : 'wxyz'}
but don't know how can utilize recursion here... help?
i thought start with:
def telephonesequence(str): in range (len(str)): homecoming dic[str[i]]
i think you're looking itertools.product
:
>>> import itertools >>> list(itertools.product('ghi','abc','def')) [('g', 'a', 'd'), ('g', 'a', 'e'), ('g', 'a', 'f'), ('g', 'b', 'd'), ('g', 'b', 'e'), ('g', 'b', 'f'), ('g', 'c', 'd'), ('g', 'c', 'e'), ('g', 'c', 'f'), ('h', 'a', 'd'), ('h', 'a', 'e'), ('h', 'a', 'f'), ('h', 'b', 'd'), ('h', 'b', 'e'), ('h', 'b', 'f'), ('h', 'c', 'd'), ('h', 'c', 'e'), ('h', 'c', 'f'), ('i', 'a', 'd'), ('i', 'a', 'e'), ('i', 'a', 'f'), ('i', 'b', 'd'), ('i', 'b', 'e'), ('i', 'b', 'f'), ('i', 'c', 'd'), ('i', 'c', 'e'), ('i', 'c', 'f')]
this gives bunch of tuples, can ''.join
them easily.
>>> list(''.join(p) p in itertools.product('ghi','abc','def')) ['gad', 'gae', 'gaf', 'gbd', 'gbe', 'gbf', 'gcd', 'gce', 'gcf', 'had', 'hae', 'haf', 'hbd', 'hbe', 'hbf', 'hcd', 'hce', 'hcf', 'iad', 'iae', 'iaf', 'ibd', 'ibe', 'ibf', 'icd', 'ice', 'icf']
of course, isn't recursive , won't help out if have other constraining forces (a professor perhaps?). leave reply demonstrate how powerful python standard library , show recursion isn't best tool sort of problem (at to the lowest degree not in python).
python recursion
No comments:
Post a Comment