华为机试HJ36字符串加密
题目:
给定一个钥匙字符串,和要加密的字符串,将钥匙字符串去重后将字符表中其他字符按顺序加入钥匙字符之后,将要加密的字符串按钥匙字符串中的对应字符进行加密,并且保证原始的字符大小写。
想法:
- 先将钥匙字符小写并去重形成列表
- 对照小写字母表将没有的字母加入到钥匙字符列表中
- 将原始字母表和新字母表形成字典供后查询
- 根据字典将加密字符进行加密(其中需要对大小写进行转换)
import sys
key = ""
count = 1
# 获取钥匙字符和加密字符
for line in sys.stdin:
a = line.split()
if count == 1:
key = a[0]
else:
input_str = a[0]
count += 1
# 将钥匙字符小写并去重
key_str = []
for i in key.lower():
if i not in key_str:
key_str.append(i)
# 加入钥匙字符中没有的字母
str_list = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
for i in str_list:
if i not in key_str:
key_str.append(i)
# 将字母表与钥匙字符一一对应形成字典
str_dict = dict(zip(str_list, key_str))
# 加密字符,其中需要进行字母大小写转换,大小写ASCII相差32
new_str = ""
for i in input_str:
if i in str_dict:
new_str += str_dict[i]
else:
new_str += chr(ord(str_dict[chr(ord(i) + 32)]) - 32)
print(new_str)