[英]Adding 2 Letter Values Together?
我目前正在尝试使用关键字进行加密。 我已经接受了用户输入和关键字输入,并获得了字母中每个字母的值。 (a = 1,b = 2,c = 3等),现在我需要将这两个值加在一起。 由于我在代码中使用了while循环来获取每个字母并获取值,因此我无法获取每个单独的值并进行添加。 有人可以就正确添加每个值的正确方向给我点意见吗? 谢谢。
def keyEnc():
alpha = ['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']
gcselist = ['g','c','s','e']
code = input("Please enter the word you would like to encrypt: ")
print("User's word is " + code)
print("The number of letters in the code is: ")
print(len(code))
x=0
while x < len(code):
currLetterA=code[x]
print("Letter: ",currLetterA)
myii=alpha.index(currLetterA)
myii=myii+1
print("The Value Is: ",myii)
x=x+1
#############################################################################################
key = input("Please enter the keyword you would like to encrypt your word by: ")
x=0
while x < len(key):
currLetter=key[x]
print("Letter: ",currLetter)
myi=alpha.index(currLetter)
myi=myi+1
print("The Value Is: ",myi)
finWord = myi+myii
print(finWord)
x=x+1
keyEnc()
听起来您正在尝试执行以下操作:
cleartext: somewords = 19 15 13 5 23 15 18 4 19
key: something = 19 15 13 5 20 8 9 14 7
++++++++++++++++++++++++++++
ciphertext: 38 30 26 10 43 23 27 18 26
那正确吗? 在这种情况下,您将需要一个数字列表,而不仅仅是一个输出。 另请注意,如果您的明文和密钥长度不完全相同,则此方法将无效。 想像:
cleartext: somewords = 19 15 13 5 23 15 18 4 19
key: banana = 2 1 14 1 14 1
++++++++++++++++++++++++++++
ciphertext: 21 16 27 6 37 16 ? ? ?
要么
cleartext: somewords = 19 15 13 5 23 15 18 4 19
key: bananahammock = 2 1 14 1 14 1 8 1 13 13 15 3 11
++++++++++++++++++++++++++++++++++++++++
ciphertext: 21 16 27 6 37 16 36 5 32 ? ? ? ?
但是,在这种情况下,您似乎需要这样做:
def key_enc():
cleartext_word = input("Enter the word you want to encrypt: ")
key = input("Enter the word you want as a key: ")
if len(cleartext_word) != len(key):
# I'm not sure how to handle this, so that's your design decision
# but possibly just:
raise ValueError("Clear text and key must have equal length")
result = list()
def lookup_letter(letter):
"""Helper function to return a proper index.
a = 1, b = 2, c = 3, ..."""
return ord(letter) - 96
for letter, key_letter in zip(cleartext_word, key):
result.append(lookup_letter(letter) + lookup_letter(key_letter))
return result
这里缺少zip
的使用是您丢失的关键。 从技术上讲,您不需要这样做,您可以像执行代码一样使用while
循环,方法是:
def key_enc():
# prompt for the cleartext_word and key as above
result = []
i = 0
while i < len(cleartext_word): # which MUST BE EQUAL TO len(key)
clear_letter = cleartext_word[i]
key_letter = key[i]
result_letter = ord(clear_letter)-96 + ord(key_letter)-96
result.append(result_letter)
但是用这种方式很难理解。
说到难以阅读,基本上您的整个功能是:
result = list(map(lambda letters: sum(map(ord,letters))-192, zip(cleartext_word, key_word)))
# YUCK!!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.