Python: Get all possible two digit letter combinations from a digit string
Two-Digit Letter Combos
Write a Python program to get all possible two-digit letter combinations from a 1-9 digit string.
string_maps = {
"1": "abc",
"2": "def",
"3": "ghi",
"4": "jkl",
"5": "mno",
"6": "pqrs",
"7": "tuv",
"8": "wxy",
"9": "z"
}
Visual Presentation:
Sample Solution:
Python Code:
# Define a function 'letter_combinations' that generates letter combinations based on input digits.
def letter_combinations(digits):
# Check if the input string is empty.
if digits == "":
return []
# Define a mapping of digits to corresponding letters.
string_maps = {
"1": "abc",
"2": "def",
"3": "ghi",
"4": "jkl",
"5": "mno",
"6": "pqrs",
"7": "tuv",
"8": "wxy",
"9": "z"
}
# Initialize the result list with an empty string.
result = [""]
# Iterate through each digit in the input string.
for num in digits:
# Create a temporary list to store new combinations.
temp = []
# Iterate through each existing combination in the result list.
for an in result:
# Append each letter corresponding to the current digit to create new combinations.
for char in string_maps[num]:
temp.append(an + char)
# Update the result list with the new combinations.
result = temp
# Return the final list of letter combinations.
return result
# Define input digit strings and print the corresponding letter combinations.
digit_string = "47"
print(letter_combinations(digit_string))
digit_string = "29"
print(letter_combinations(digit_string))
Sample Output:
['jt', 'ju', 'jv', 'kt', 'ku', 'kv', 'lt', 'lu', 'lv'] ['dz', 'ez', 'fz']
Explanation:
The above Python code defines a function called "letter_combinations()" that generates letter combinations based on input digits. Here's a brief explanation:
- The function takes a string of digits ('digits') as input.
- If the input string is empty, it returns an empty list.
- It defines a mapping ('string_maps') of each digit to a string of corresponding letters.
- It initializes a result list with an empty string.
- It iterates through each digit in the input string.
- For each existing combination in the result list, it appends each letter corresponding to the current digit to create new combinations.
- It updates the result list with new combinations.
- The function returns the final list of letter combinations.
Flowchart:
Python Code Editor :
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to create all possible permutations from a given collection of distinct numbers.
Next: Write a Python program to add two positive integers without using the '+' operator.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics