我正在尝试为换位密码制作解密功能
I am trying to make a decryption function for transposition cipher
我应该仅限于使用 len()、ord() 和 range() 函数。但是,我不知道我应该如何满足这些要求并最终做出了这个:
def swap(s: str, index0: int, index1: int):
smaller = index0 if index0 < index1 else index1
bigger = index0 if index0 >= index1 else index1
if bigger >= len(s) or smaller < 0:
return None
ret = s[:smaller] + s[bigger] + s[smaller+1:] # swap first
ret = ret[:bigger] + s[smaller] + s[bigger+1:] # swap second
return ret
def swap_encrypt(s: str, key:str):
ret = s
for key_chr in key:
index = ascii_uppercase.index(key_chr)
swap_this = index % len(ret)
with_this = (swap_this - 1) % len(ret)
ret = swap(ret, swap_this, with_this)
return ret
s = ''
key = ''
def main2():
s = input('Enter your message: ')
s = cleanup(s)
key = input('Enter your keyword: ')
key = cleanup(key)
ret= swap_encrypt((s), (key))
print(cleanup(ret))
main2()
当我为消息输入 'Lsoth' 并为关键字输入 'a' 时,我得到 'HSOTL' 而不是 'SLOTH'
有没有办法既能满足我的要求,又能解决我的解密问题?
def swap_decrypt(msg: str, key: str):
ret = msg
for key_char in key:
index = ord(key) + ord('A')
swap_this = index % len(ret)
with_this = (swap_this + 1) % len(ret)
ret = swap2(ret, swap_this, with_this)
return ret
def main3():
msg = input('Enter message for decrpytion: ')
key = input('Enter keyword for decryption: ')
msg = cleanup(msg)
key = cleanup(key)
ret = swap_decrypt(msg, key)
print(cleanup(ret))
而不是 ascii_uppercase
做 index = ord(key) + ord('A')
,并且 (swap_this -1)
应该是加而不是减 1。在这些小的更改之后,您的问题将得到解决。我还按顺序更改了一些变量,以便它更有意义。
我应该仅限于使用 len()、ord() 和 range() 函数。但是,我不知道我应该如何满足这些要求并最终做出了这个:
def swap(s: str, index0: int, index1: int):
smaller = index0 if index0 < index1 else index1
bigger = index0 if index0 >= index1 else index1
if bigger >= len(s) or smaller < 0:
return None
ret = s[:smaller] + s[bigger] + s[smaller+1:] # swap first
ret = ret[:bigger] + s[smaller] + s[bigger+1:] # swap second
return ret
def swap_encrypt(s: str, key:str):
ret = s
for key_chr in key:
index = ascii_uppercase.index(key_chr)
swap_this = index % len(ret)
with_this = (swap_this - 1) % len(ret)
ret = swap(ret, swap_this, with_this)
return ret
s = ''
key = ''
def main2():
s = input('Enter your message: ')
s = cleanup(s)
key = input('Enter your keyword: ')
key = cleanup(key)
ret= swap_encrypt((s), (key))
print(cleanup(ret))
main2()
当我为消息输入 'Lsoth' 并为关键字输入 'a' 时,我得到 'HSOTL' 而不是 'SLOTH'
有没有办法既能满足我的要求,又能解决我的解密问题?
def swap_decrypt(msg: str, key: str):
ret = msg
for key_char in key:
index = ord(key) + ord('A')
swap_this = index % len(ret)
with_this = (swap_this + 1) % len(ret)
ret = swap2(ret, swap_this, with_this)
return ret
def main3():
msg = input('Enter message for decrpytion: ')
key = input('Enter keyword for decryption: ')
msg = cleanup(msg)
key = cleanup(key)
ret = swap_decrypt(msg, key)
print(cleanup(ret))
而不是 ascii_uppercase
做 index = ord(key) + ord('A')
,并且 (swap_this -1)
应该是加而不是减 1。在这些小的更改之后,您的问题将得到解决。我还按顺序更改了一些变量,以便它更有意义。