题解 | #HJ21 简单密码#
简单密码
https://www.nowcoder.com/practice/7960b5038a2142a18e27e4c733855dac
解法1-条件判断
这题思路非常清晰,最直接的方式就是通过条件判断来转换每个字符。
def char_to_num(char): if char == 'Z': return 'a' if char.isupper(): char = chr(ord(char.lower()) + 1) return char if char in 'abc': return '2' elif char in 'def': return '3' elif char in 'ghi': return '4' elif char in 'jkl': return '5' elif char in 'mno': return '6' elif char in 'pqrs': return '7' elif char in 'tuv': return '8' elif char in 'wxyz': return '9' else: return char line = input() s = "".join(char_to_num(char) for char in line) print(s)
解法2-字典映射
看到A, B这两个整齐对应的序列,第一时间就想到了zip,分分钟帮你映射成字典,再结合列表生成式,更简洁了!
A = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' B = '22233344455566677778889999bcdefghijklmnopqrstuvwxyza' mapping = dict(zip(A, B)) s = ''.join([mapping[c] if c in A else c for c in input()]) print(s)