Python Programming Problem
Given a seven-digit telephone number (excluding 0 and 1), write a Python script that generates and prints the first 100 possible “words” that can be formed using the alphabetic characters corresponding to each digit on a telephone dial. The alphabetic correspondences of telephone dials are as follows:
2 – ABC
3 – DEF
4 – GHI
5 – JKL
6 – MNO
7 – PRS
8 – TUV
9 – WXY
Please ensure that the input number does not contain the digits 0 or 1. The generated “words” may not be real English words but can be any sequence of characters. The script should output the first 100 possible “words” that can be formed from the given number.
Steps
- Define a dictionary to map each digit to its corresponding alphabetic characters.
- Create a function to generate all possible combinations of characters for a given seven-digit number.
- Validate the input number to ensure it does not contain the digits 0 or 1.
- Generate and print the first 100 possible “words” that the number spells.
Expected output
SOLUTION
import itertools
# Define a dictionary to map digits to their corresponding alphabetic characters
digit_map = {
'2': 'ABC',
'3': 'DEF',
'4': 'GHI',
'5': 'JKL',
'6': 'MNO',
'7': 'PRS',
'8': 'TUV',
'9': 'WXY'
}
# Create a function to generate all possible combinations of characters for a given seven-digit number
def generate_words(phone_number):
possible_chars = [digit_map[digit] for digit in phone_number]
combinations = list(itertools.product(*possible_chars))
return [''.join(chars) for chars in combinations]
# Validate the input number to ensure it does not contain the digits 0 or 1
def validate_input(phone_number):
return all(digit in '23456789' for digit in phone_number)
# Generate and print the first 100 possible "words" that the number spells
def print_possible_words(phone_number):
if validate_input(phone_number):
words = generate_words(phone_number)
for word in words[:100]:
print(word)
else:
print("Input number should not contain the digits 0 or 1")
# Example usage:
input_number = "2345678"
print_possible_words(input_number)