02913: 加密技术
http://cs101.openjudge.cn/practice/02913/
编制程序,将输入的一行字符加密解密。加密时,每个字符依次反复加上“4962873”中的数字,如果范围超过ASCII码的032(空格)~122(‘z’),则进行模运算。解密和加密的顺序相反。编制加密解密函数,打印各个过程的结果。
例如:如果是this is a book! 密文应该是: 't'+4,'h'+9,'i'+6,'s'+2,' '+8,'i'+7,'s'+3,' '+4,'a'+9,' '+6,'b'+2,'o'+8,'o'+7,'k'+3,'!'+4
输入
输入一行字符串,其中包含了若干空格。
输出
对输入字符串进行加密,并输出加密结果。 再对输入字符串进行解密,并在换行后输出解密结果。
样例输入
aghi lrtq haha样例输出
epnk(suxz&"phke
aghi lrtq hahapython
def encrypt(text):
# 数字序列"4962873"
pattern = "4962873"
encrypted_text = []
for i, char in enumerate(text):
# ASCII码范围限制在32到122之间,超出范围进行模运算
shift = int(pattern[i % len(pattern)])
new_char = chr((ord(char) + shift - 32) % (122 - 32 + 1) + 32)
encrypted_text.append(new_char)
return ''.join(encrypted_text)
def decrypt(encrypted_text):
# 数字序列"4962873"
pattern = "4962873"
decrypted_text = []
for i, char in enumerate(encrypted_text):
# 解密时反向操作
shift = int(pattern[i % len(pattern)])
new_char = chr((ord(char) - shift - 32) % (122 - 32 + 1) + 32)
decrypted_text.append(new_char)
return ''.join(decrypted_text)
text = input()
encrypted = encrypt(text)
print(encrypted)
decrypted = decrypt(encrypted)
print(decrypted)