avatar Bite 375. Find All Letter Combinations of a Phone Number

The typical phone keypad (pictured) features numbers (0 - 9), letters mapped to some of those numbers (2 - 9, inclusive), and two non-numeric characters (* and #).

Now imagine it's the 1950s, you live in a small village with 900 other villagers, any of whom you can reach simply by dialing the last four digits of their telephone number (in other words, you only need to dial "5309" to reach Jenny, not "867-5309").

Given a string of up to four digits, return a list of strings where each string represents a valid combination of letters that can be formed from the input.

Raise a ValueError if the input digits string contains non-digit characters or more than four digits.

Example 1:

>>> from  combinations import generate_letter_combinations
>>> digits =  "24"
>>> generate_letter_combinations(digits)
['ag', 'ah', 'ai', 'bg', 'bh', 'bi', 'cg', 'ch', 'ci']

Example 2:

>>> from  combinations import generate_letter_combinations
>>> digits =  "79"
>>> generate_letter_combinations(digits)
['pw', 'px', 'py', 'pz', 'qw', 'qx', 'qy', 'qz', 'rw', 'rx', 'ry', 'rz', 'sw', 'sx', 'sy', 'sz']

Example 3:

>>> from  combinations import generate_letter_combinations
>>> digits =  "232"
>>> generate_letter_combinations(digits)
[
    "aaa", "aab",  "aac", "aba", "abb", "abc",
    "aca", "acb", "acc", "baa", "bab", "bac",
    "bba", "bbb", "bbc", "bca", "bcb", "bcc",
    "caa", "cab", "cac", "cba", "cbb", "cbc",
    "cca", "ccb", "ccc"
]

Assumptions:

- The strings contained in the list returned by your function can be in any order.

- Since the digits 1 and 0 are not associated with any letters, the phone number should include only digits 2 - 9, inclusive.

Hints:

- There are different ways to solve this problem.

- One way is to use Python's itertools module.

Keep calm and code in Python!

Login and get coding
go back Intermediate level
Bitecoin 3X

16 out of 16 users completed this Bite.
Will you be Pythonista #17 to crack this Bite?
Resolution time: ~34 min. (avg. submissions of 5-240 min.)

Focus on this Bite hiding sidebars, turn on Focus Mode.

Ask for Help