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

numeric keypad with letter equivalents

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 == []:
    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")


1 Answer 1


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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.