# Print the string equivalents of a phone number

Old mobile phones had the ability to type characters by pressing a number. The letter a could be typed by pressing 2 once. The letter b could be typed by pressing 2 twice.

Given a sequence of numbers, give all possible letter combinations.

For example: The number 23 could give an output ad, ae, af, bd, be, bf, cd, ce, cf

My recursive solution to this problem is given below.

def num_to_char(value):
if value == 2: return ["a","b","c"]
if value == 3: return ["d","e","f"]
if value == 4: return ["g","h","i"]
if value == 5: return ["j","k","l"]
if value == 6: return ["m","n","o"]
if value == 7: return ["p","q","r","s"]
if value == 8: return ["t","u","v"]
if value == 9: return ["w","x","y","z"]

def convert_num(number, current_string = ""):
if number == []:
print(current_string)
return
get_list = num_to_char(int(number[0]))
for character in get_list:
current_string += character
convert_num(number[1:], current_string)
current_string = current_string[:-1]

num_to_covert = list("234")
convert_num(num_to_covert)



You're working way too hard:

• itertools.product() produces cartesian products.
• You don't need to convert strings to lists; you can iterate over strings directly.
• Lookups are better done using a dictionary than a chain of if statements.
from itertools import product

'2': 'abc',  '3': 'def',
'4': 'ghi',  '5': 'jkl',  '6': 'mno',
'7': 'pqrs', '8': 'tuv',  '9': 'wxyz',
}

def convert_num(number):
letters = [KEYPAD[c] for c in number]
return [''.join(combo) for combo in product(*letters)]

print(convert_num('234'))

• Brilliant. Sadly I actually had no idea what a cartesian product was so thanks for educating me :)
– EML
Jun 2 '19 at 20:48
• In general, any time you want to do some kind of fancy iteration in Python, look at itertools first. Jun 2 '19 at 20:55
• @200_success And if you don't find it in itertools, more_itertools might have it instead (although you need to install it separately). Jun 3 '19 at 4:53
• Beautiful code :) Jun 3 '19 at 7:51