12
\$\begingroup\$

Task

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

\$\endgroup\$
18
\$\begingroup\$

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

KEYPAD = {
                 '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'))
\$\endgroup\$
  • \$\begingroup\$ Brilliant. Sadly I actually had no idea what a cartesian product was so thanks for educating me :) \$\endgroup\$ – EML Jun 2 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\$ – 200_success Jun 2 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 Jun 3 at 4:53
  • \$\begingroup\$ Beautiful code :) \$\endgroup\$ – JollyJoker Jun 3 at 7:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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