Find all letter combinations of a phone number
Level: Intermediate (score: 3)
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)
[
'ada', 'adb', 'adc', 'aea', 'aeb', 'aec', 'afa', 'afb', 'afc',
'bda', 'bdb', 'bdc', 'bea', 'beb', 'bec', 'bfa', 'bfb', 'bfc',
'cda', 'cdb', 'cdc', 'cea', 'ceb', 'cec', 'cfa', 'cfb', 'cfc'
]
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!