HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Letter Combinations of a Phone Number

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
letternumberphonecombinations

Problem

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]))]

Solution

Solution overall seems nice, although:

  • casting to list in list comprehension is not needed



  • product returns iterator, so you also may want to generate iterator if you mainly plan to iterate over possibilities



  • I'd strongly advice using better names. Characters in source code costs nothing and maintaining code afterwards is much easier



My attempt would be:

import itertools

letters_map = {'2':'ABC', '3':'DEF', '4':'GHI', '5':'JKL', 
               '6':'MNO', '7':'PQRS', '8':'TUV', '9':'WXYZ'}

def possible_words(phone_number):
    letters_to_combine = (letters_map[digit] for digit in phone_number)
    for letters_group in itertools.product(*letters_to_combine):
        yield ''.join(letters_group)

print list(possible_words("23567"))

Code Snippets

import itertools

letters_map = {'2':'ABC', '3':'DEF', '4':'GHI', '5':'JKL', 
               '6':'MNO', '7':'PQRS', '8':'TUV', '9':'WXYZ'}

def possible_words(phone_number):
    letters_to_combine = (letters_map[digit] for digit in phone_number)
    for letters_group in itertools.product(*letters_to_combine):
        yield ''.join(letters_group)

print list(possible_words("23567"))

Context

StackExchange Code Review Q#82434, answer score: 5

Revisions (0)

No revisions yet.