好的,所以我在python中使用Caesar密码程序已经达到了这个目的,并且看不出为什么这不起作用的任何原因,但它没有......它输出新单词为&# 39;一个' '一个' '一个' (因为这个词中有很多字母)。我的猜测是它的某种循环导致每个字母被改成' a'但我无法弄明白。有人可以帮助我吗?感谢。
我的代码:
word = input("please enter the word you wish to encrypt: ")
seperated = list(word)
length = len(word)
alphabet1 = ["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"]
alphabet2 = ["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","a"]
length2 = len(alphabet1)
length3 = len(alphabet2)
for eachposition in range(length):
for letter in range(length2):
if seperated[eachposition] == alphabet1[letter]:
seperated.pop(eachposition)
seperated.insert(eachposition, alphabet2[letter])
print(seperated)
答案 0 :(得分:0)
我在您的代码中添加了一些print
次调用,并且在seperated[eachposition] == alphabet1[letter]
评估为True
时,其中有很多误报。从那以后我很快意识到了这个问题。
你从不使用循环中的break
,所以这里发生了什么:
由于你的密码只是将每个字母前进到一个字母上,所以这个循环将一直运行,直到它到达列表中的最后一个字母,' a'。
简单的解决方法是使用break
。它会过早地结束for
循环。这意味着当你替换一个字母时,你想要突破那个内部循环并移动到下一个字符。
for eachposition in range(length):
for letter in range(length2):
if seperated[eachposition] == alphabet1[letter]:
seperated.pop(eachposition)
seperated.insert(eachposition, alphabet2[letter])
break
答案 1 :(得分:0)
@SuperBiasedMan为您提供了保存代码的工作解决方案,但我建议为您的任务提供一个更简单的循环(不需要弹出和插入,因为您在整个单词中按顺序迭代)。
new = []
for c in word:
for i in range(length2):
if c == alphabet1[i]:
new.append(alphabet2[i])
break
new = ''.join(new)
print new
还考虑使用词典。它们可以解决这类问题。
答案 2 :(得分:0)
另一种方法是将每个字符转换为其ASCII数字,即a = 97,b = 98等asciitable.com这可以通过ord()
完成num = ord(character) - 97
然后,您可以添加密钥以获取新的ascii代码并将其转换回字符。您已经使用模数来允许从字母表的结尾到字母的开头循环。
encr_char = chr((num + key)% 26 + 97)
您需要添加代码来处理大写字母(ascii 65 - 90)和非字母字符。 isupper()
和isalpha()
将在此处完成工作。
这种方法允许改变密钥。