我想在python的pset6vigenere上得到一些帮助。我的C语言实现还可以,但是Python代码中有一个bug让我困惑。程序将正确加密,直到找到一个非字母字符为止。在非字母字符之后,我不应该递增,但是在运行程序时会发生这样的情况:键会再次更新自身,但在循环的下一次迭代中不会再次使用字母字符。令我不安的是,在C语言中,同样的实现工作得很完美。我猜循环中的条件有问题,但我不知道是什么。这是我用C和Python运行程序得到的结果,只有第一个密码正确:
这是密码,提前谢谢你的帮助
from cs50 import get_string
import sys
def main():
# Check usage and key
if len(sys.argv) != 2 or not sys.argv[1].isalpha():
print("Usage: python vigenere.py k")
sys.exit(1)
# Prompt user for plaintext
plaintext = get_string("plaintext: ")
# Cipher text
print("ciphertext: ", end="")
# Set keyword iteration counter
i = 0
key = sys.argv[1]
len_key = len(key)
keyword = shift(key[i])
for c in plaintext:
# Take care of uppercase character
if c.isupper():
print(chr(((ord(c) - 65 + keyword) % 26) + 65), end="")
# Take care of lowercase character
elif c.islower():
print(chr(((ord(c) - 97 + keyword) % 26) + 97), end="")
# Take care of non alphabetic character
else:
print(c, end="")
# Take care of keyword counter
if i < len_key - 1 and plaintext[i].isalpha():
i = i + 1
keyword = shift(key[i])
elif i == len_key - 1 and plaintext[i].isalpha():
i = 0
keyword = shift(key[i])
print()
# Function shift value of each carachter of keyword
def shift(char):
if char.isupper():
value = ord(char) - 65
else:
value = ord(char) - 97
return value
if __name__ == "__main__":
main()
目前没有回答
相关问题 更多 >
编程相关推荐