I was asked to code a solution in Python in 15 mins. Print all possible word combinations for a given phone number. Numbers 0 and 1 will not be part of the phone number, the numbers can be repeated, phone numbers can be of any length. For example if the number is 245:
All combinations of 'ABC', 'GHI' and 'JKL" is: ['AGJ', 'AGK', 'AGL', 'AHJ', 'AHK', 'AHL', 'AIJ', 'AIK', 'AIL', 'BGJ', 'BGK', 'BGL', 'BHJ', 'BHK', 'BHL', 'BIJ', 'BIK', 'BIL', 'CGJ', 'CGK', 'CGL', 'CHJ', 'CHK', 'CHL', 'CIJ', 'CIK', 'CIL']
In 15 mins, all I could come up with was to combine 2 numbers at a time and then combine the result with the third number and so on.
numbs = {'2':'ABC', '3':'DEF', '4':'GHI', '5':'JKL', '6':'MNO', '7':'PQRS', '8':'TUV', '9':'WXYZ'}
def combo(phnum):
if len(phnum) == 1: return list(numbs[phnum[0]])
else: result = combo(phnum[:-1])
return [(ch1+ch2) for ch1 in result for ch2 in numbs[phnum[-1]]]
After I going home, I checked out itertools and found out about product. Came up with the following one liner. Is there a better way to solve this problem?
from itertools import product
def combo(phnum):
return [''.join(tup) for tup in list(product(*[numbs[ch] for ch in phnum]))]