我制作了一个Caesar密码程序进行评估,但我想知道我是否可以提高效率?
#A Caesar cipher program
##Defines the alphabet
abc = ['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']
##Collects the infomation from the user
task = input("Would you like to encrypt or decrypt?: ")
word = input("Please enter your word: ")
offset = int(input("Please enter your offset: ")) % 26
##The function to work out the answer
def workout(offset):
final = []
for i in word:
try:
if i.isupper():
final.append(abc[abc.index(i.lower()) + offset].upper())
else:
final.append(abc[abc.index(i.lower()) + offset])
except:
final.append(i)
print(''.join(final))
##Displays the final result
if task == "encrypt":
workout(offset)
else:
workout(-offset)
感谢所有回复:) 谢谢!
答案 0 :(得分:0)
以下是如何使用str.translate
>>> offset = 5
>>> abc = ['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']
>>> trns = str.maketrans(''.join(abc), ''.join(abc[offset:] + abc[:offset]))
>>> "dog".translate(trns)
'itl'
您必须添加一些额外的代码来处理负偏移
所以你的功能可以成为
def workout(offset):
trns = str.maketrans(''.join(abc), ''.join(abc[offset:] + abc[:offset]))
print(words.translate(trns))
考虑将words
作为参数传递,将abc
传递给字符串而不是列表
import string
abc = string.ascii_lowercase
ABC = string.ascii_uppercase
def workout(offset, words):
trns = str.maketrans(abc + ABC, abc[offset:] + abc[:offset] + ABC[offset:] + ABC[:offset])
print(words.translate(trns))
请注意,您仍然需要一些额外的逻辑才能使负偏移工作