题解 | #字符串加密#
字符串加密
https://www.nowcoder.com/practice/e4af1fe682b54459b2a211df91a91cf3
思路:创建一个字典,将标准字母表映射到加密字母表
写法1
def encrypt(key, s): alphas = ''.join([chr(ord('a')+i) for i in range(26)]) new_alphas = "" for c in key: if c not in new_alphas: new_alphas += c for c in alphas: if c not in new_alphas: new_alphas += c dic = dict(zip(alphas, new_alphas)) result = "".join([dic.get(c, c) if c.islower() else dic.get(c.lower(), c).upper() for c in s]) return result key = input().lower() s = input() print(encrypt(key, s))
写法2
letter_list = [chr(ord('a') + i) for i in range(26)] new_list = [] while True: try: key = input().lower() s = input() for i in key: if i not in new_list: new_list.append(i) for j in letter_list: if j not in new_list: new_list.append(j) m = dict(zip(letter_list, new_list)) res = [] for c in s: if not c.isalpha(): res.append(c) elif c.lower(): res.append(m[c]) else: res.append(m[c.lower()].upper()) print(''.join(res)) except: break
【牛客站内】华为机试题解 文章被收录于专栏
【牛客站内】 分享个人刷题的思路和解法