给定一个输入单词,全部用大写字母显示在标准手机键盘上输入该单词所需要输入的数字。假设电话可以完美地预测您想要的单词,并且单词中没有数字或标点符号。
例如:
Enter word: HELLO
43556
43556
由于HELLO
按进入,因此被打印出来4, 3, 5, 5, 6
。
我的代码:
# 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="")
我设法产生正确的输出。但是,问题案例指出必须包含“尾随换行符”。请注意,我希望将代码打印在一行上,例如示例。
您有很多不必要的代码行:
word = "\n".join(word)
wordx = word.split("\n")
这不是必需的。您在字符之间插入换行符,只是split
通过换行符再次插入到列表中。这两行等效于list(word)
。但是,由于input()
返回的字符串是可迭代的,因此也不必进行此转换。遍历字符串将遍历其字符。
for c in wordx:
if c in wordx:
...
没有必要检查if c in wordx
。显然是因为您正在迭代wordx
...
您的代码的简化版本为:
word = input("Enter word: ")
for c in word:
print(KEYPAD[c], end="")
print()
也可以使用join
代替来进一步简化end=
,只是使用与您使用的方式不同:
word = input("Enter word: ")
print(''.join(KEYPAD[c] for c in word)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句