我是蟒蛇的初学者,正在上一门课程。我的任务是做一个凯撒密码,我可以输入所用的字母表。为此,我不能使用ord()或list()或任何导入的函数,只能使用基本的python。我让它只写一封信,但我似乎想不出如何使它适用于不止一封信。任何帮助都将不胜感激!
def cypher(target, alphabet, shift):
for index in range( len(alphabet)):
if alphabet[index] == target:
x = index + shift
y = x % len(alphabet)
return (alphabet[y])发布于 2021-02-10 18:19:55
我看这是你的第一个问题。谢谢你的关心。
我认为您希望您的代码使用上面构建的函数来加密完整的脚本。因此,您的函数所做的是,它接受一个字母作为target,并转移它。
通过迭代string的元素,可以轻松地将其应用于它。
我在这里通过一些调整为您的查询提供了正确的实现:
alphabet = "abcdefghijklmnopqrstuvwxyz"
def cypher(target, shift):
for index in range(len(alphabet)):
if alphabet[index] == target:
x = index + shift
y = x % len(alphabet)
return (alphabet[y])
string = "i am joe biden"
shift = 3 # Suppose we want to shift it for 3
encrypted_string = ''
for x in string:
if x == ' ':
encrypted_string += ' '
else:
encrypted_string += cypher(x, shift)
print(encrypted_string)
shift = -shift # Reverse the cypher
decrypted_string = ''
for x in encrypted_string:
if x == ' ':
decrypted_string += ' '
else:
decrypted_string += cypher(x, shift)
print(decrypted_string)发布于 2021-02-10 18:46:46
有很多方法可以完成这样的事情,但是你可能想要一种形式的
获取您的映射的输入values
str.maketrans table)
下面是一个非常无聊的凯撒密码的完整例子
source_string = input("source string: ").upper()
cut_position = int(input("rotations: "))
# available as string.ascii_uppercase
source_values = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
# create a mapping
mapping = source_values[cut_position:] + source_values[:cut_position]
# display mapping
print("using mapping: {}".format(mapping))
# build a translation table
table = str.maketrans(source_values, mapping)
# use your translation table to rebuild the string
resulting_string = source_string.translate(table)
# display output
print(resulting_string)将提供映射和低强制文本作为练习。
https://stackoverflow.com/questions/66142259
复制相似问题