Skip to content

Telephone keypad combinations

Problem: Given a sequence of numbers, show all possible letter combinations in a telephone keypad.

Recursive solution in Python:
[python]
keyboard = {
‘1’: [],
‘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’],
‘0’: []
}

def printkeys(numbers, prefix=""):
if len(numbers)==0:
print prefix
return

for letter in keyboard[numbers[0]]:
printkeys(numbers[1:], prefix+letter)

printkeys("234")
[/python]

Output:

adg
adh
adi
aeg
aeh
aei
afg
afh
afi
bdg
bdh
bdi
beg
beh
bei
bfg
bfh
bfi
cdg
cdh
cdi
ceg
ceh
cei
cfg
cfh
cfi
Published inenglish

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *