题解 | #简单密码#
简单密码
https://www.nowcoder.com/practice/7960b5038a2142a18e27e4c733855dac
def transform_password(pw): # 九键键盘映射 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", } # 变换密码 transformed_pw = "" for c in pw: if c.isalpha(): # 如果是字母 if c.isupper(): # 大写字母转小写并移位 c = c.lower() if c == "z": transformed_pw += "a" # 特殊处理Z else: transformed_pw += chr(ord(c) + 1) # 往后移一位 else: # 小写字母转换为数字 transformed_pw += keypad.get(c, c) # 使用get方法处理不在映射中的字符 else: # 数字和其它符号不变 transformed_pw += c return transformed_pw # 读取输入并输出变换后的密码 if __name__ == "__main__": passwords = input().split() # 假设输入可以有多个密码,以空格分隔 for pw in passwords: print(transform_password(pw))
定义了一个transform_password
函数,它接受一个密码字符串作为输入,并返回变换后的密码字符串。函数内部使用了一个字典keypad
来映射小写字母到对应的九键键盘数字。对于大写字母,函数将其转换为小写,然后根据规则进行移位。数字和其他符号保持不变。