I have a task to write recursive func that will generate all combinations from input. Got dict
letters_numbers = {
2: ['a', 'b', 'c'],
3: ['d', 'e', 'f'],
4: ['g', 'h', 'i'],
5: ['j', 'k', 'l'],
6: ['m', 'n', 'o'],
7: ['p', 'q', 'r', 's'],
8: ['t', 'u', 'v'],
9: ['w', 'x', 'y', 'z'] }
The input format is:
23
Output shoud be:
ad ae af bd be bf cd ce cf
Abother example:
7884
Output:
pttg ptth ptti ptug ptuh ptui ptvg ptvh ptvi putg puth puti puug puuh puui puvg puvh puvi pvtg pvth pvti pvug pvuh pvui pvvg pvvh pvvi qttg qtth qtti qtug qtuh qtui qtvg qtvh qtvi qutg quth quti quug quuh quui quvg quvh quvi qvtg qvth qvti qvug qvuh qvui qvvg qvvh qvvi rttg rtth rtti rtug rtuh rtui rtvg rtvh rtvi rutg ruth ruti ruug ruuh ruui ruvg ruvh ruvi rvtg rvth rvti rvug rvuh rvui rvvg rvvh rvvi sttg stth stti stug stuh stui stvg stvh stvi sutg suth suti suug suuh suui suvg suvh suvi svtg svth svti svug svuh svui svvg svvh svvi
What i got so far:
letters_numbers = {
2: ['a', 'b', 'c'],
3: ['d', 'e', 'f'],
4: ['g', 'h', 'i'],
5: ['j', 'k', 'l'],
6: ['m', 'n', 'o'],
7: ['p', 'q', 'r', 's'],
8: ['t', 'u', 'v'],
9: ['w', 'x', 'y', 'z']
}
def combine(query, letters, letters2, n, k):
if n < len(letters):
query = letters[n]
for i in letters2:
combine(query i ' ', letters, letters2, n 1 , k 1)
else:
print(query)
def read_input():
n = input()
list = [int(x) for x in n]
return list
def main():
n = read_input()
letters = [letters_numbers[i] for i in n]
res = ''
combine(res, letters[0], letters[1], 0, 0)
if __name__ == "__main__":
main()
The output from input '23' is:
ad bd cd
ad bd ce
ad bd cf
ad be cd
ad be ce
ad be cf
ad bf cd
ad bf ce
ad bf cf
ae bd cd
ae bd ce
ae bd cf
ae be cd
ae be ce
ae be cf
ae bf cd
ae bf ce
ae bf cf
af bd cd
af bd ce
af bd cf
af be cd
af be ce
af be cf
af bf cd
af bf ce
af bf cf
So far only figured out how to do it with 2 lists input but not exactly how its needed to be, also i need to be able to input more lists into it somwhow
Sorry for my english and messed up code and thanks in advance
CodePudding user response:
Found out answer for that question, you have to combine on the backwards of recursion flow if it makes sense:
letters_numbers = {
2: ['a', 'b', 'c'],
3: ['d', 'e', 'f'],
4: ['g', 'h', 'i'],
5: ['j', 'k', 'l'],
6: ['m', 'n', 'o'],
7: ['p', 'q', 'r', 's'],
8: ['t', 'u', 'v'],
9: ['w', 'x', 'y', 'z']
}
def gen(phone_number):
if len(phone_number) == 1:
return list(letters_numbers[phone_number[0]])
else:
result = gen(phone_number[:-1])
return [(str1 str2) for str1 in result for str2 in letters_numbers[phone_number[-1]]]
def read_input():
n = input()
list = [int(x) for x in n]
return list
def main():
lists = read_input()
res = gen(lists)
for i in res:
print(i, end = ' ')
if __name__ == "__main__":
main()
Would be nice if someone can explain to me that line:
return [(str1 str2) for str1 in result for str2 in letters_numbers[phone_number[-1]]]