我在加密大写字母时遇到问题,例如如果消息是COMPUTING IS FUN关键字是GCSE我应该得到JRFUBWBSN LL KBQ,但我的实际结果是xftipkpgb zz ype。这个结果既没有正确的字母,也没有资本。任何帮助表示赞赏
message = input('\nenter message: ')
keyword = input('enter keyword: ')
def chr_to_inta(char):
return 0 if char == 'Z' else ord(char)-64
def int_to_chra(integer):
return 'Z' if integer == 0 else chr(integer+64)
def add_charsa(msg, key):
return int_to_chr(( chr_to_int(msg) + chr_to_int(key)) % 26 )
def chr_to_int(char):
return 0 if char == 'z' else ord(char)-96
def int_to_chr(integer):
return 'z' if integer == 0 else chr(integer+96)
def add_chars(msg, key):
return int_to_chr(( chr_to_int(msg) + chr_to_int(key)) % 26 )
def vigenere(message, keyword):
keystream = cycle(keyword)
new = ''
for msg in message:
if msg == ' ': # adds a space
new += ' '
elif 96 < ord(msg) < 123: # if lowercase
new += add_chars(msg, next(keystream))
else: # if uppercase
new += add_charsa(msg, next(keystream))
return new
new = vigenere(message, keyword)
print('your encrypted message is: ',new)
答案 0 :(得分:0)
因为你似乎没有得到我所说的:
def add_charsa(msg, key):
return int_to_chr(( chr_to_int(msg) + chr_to_int(key)) % 26 )
是你现在拥有的。有了这个,你得到了糟糕的结果:
>>> vigenere('COMPUTING IS FUN','GCSE')
'xftipkpgb zz ype'
这是因为您没有更改此函数的return语句来调用新的大写函数。如果您将return语句更改为:
def add_charsa(msg, key):
return int_to_chra(( chr_to_inta(msg) + chr_to_inta(key)) % 26 )
#notice the change in function calls from int_to_chr -> int_to_chra, and chr_to_int -> chr_to_inta
然后你会得到预期的结果:
>>> vigenere('COMPUTING IS FUN','GCSE')
'JRFUBWBSN LL KBQ'
值得一提的是,如果您的密钥混合使用大写和小写字母,这将无效。很好。我会将您的keystream
更改为:keystream = cycle(keyword.lower())
,然后您的功能将是:
def add_charsa(msg, key):
return int_to_chra(( chr_to_inta(msg) + chr_to_int(key)) % 26 )
#notice the call to chr_to_int(key) because key will always be lower case