Reputation: 15
Given a word of input, all in uppercase letters, print the numbers you would need to type on a standard mobile phone keypad to enter that word. Assume that the phone can perfectly predict the word you want, and there are no numbers or punctuation symbols in the word.
For example:
Enter word: HELLO
43556
43556
is printed out since HELLO
is entered by pressing 4, 3, 5, 5, 6
.
My Code:
# A dictionary containing the letter to digit phone keypad mappings.
KEYPAD = {
'A': '2', 'B': '2', 'C': '2', 'D': '3', 'E': '3',
'F': '3', 'G': '4', 'H': '4', 'I': '4', 'J': '5',
'K': '5', 'L': '5', 'M': '6', 'N': '6', 'O': '6',
'P': '7', 'Q': '7', 'R': '7', 'S': '7', 'T': '8',
'U': '8', 'V': '8', 'W': '9', 'X': '9', 'Y': '9',
'Z': '9',
}
word = input("Enter word: ")
word = "\n".join(word)
wordx = word.split("\n")
for c in wordx:
if c in wordx:
print(KEYPAD[c], end="")
I have managed to produce the correct output. However, the problem case states that a "trailing newline character" must be included. Please note that I want the code to be printed on one line, such as in example.
Upvotes: 1
Views: 1792
Reputation: 19414
You have a lot of unnecessary lines of code:
word = "\n".join(word)
wordx = word.split("\n")
This is not necessary. You insert newlines between the characters, just to split
them again by new-line to a list. These two lines are equivalent to list(word)
. But this conversion is not necessary as well because input()
returns a string which is iterable. Iterating over a string iterates over its characters.
for c in wordx:
if c in wordx:
...
It is not necessary to check if c in wordx
. It obviously is because you are iterating over wordx
...
A simplified version of your code would be:
word = input("Enter word: ")
for c in word:
print(KEYPAD[c], end="")
print()
Which can also be simplified further by using join
instead of end=
, just in a different way that you were using:
word = input("Enter word: ")
print(''.join(KEYPAD[c] for c in word)
Upvotes: 3