我在python中有这段代码
BASE = ord('a') - 1
def str_to_nums(s):
return [ord(ch) - BASE for ch in s]
def nums_to_str(nums):
return "".join(chr(n + BASE) for n in nums)
print(str_to_nums("a")) # => [8, 9]
print(nums_to_str([8, 9])) # => "hi"
print(str_to_nums("ca")) # => [3, 1]
print(nums_to_str([13, 16]))# => "ca"
def test2():
NIL = len(numbers)
LIG = len(gcse)
test = (LIG)
if test >= (NIL):
contine ()
else:
gcse.extend(GIGCSE)
LIG = len(gcse)
test = (LIG)
if test == (NIL):
contine ()
else:
gcse.extend(CIGCSE)
LIG = len(gcse)
test = (LIG)
if test == (NIL):
contine ()
else:
gcse.extend(SIGCSE)
LIG = len(gcse)
test = (LIG)
if test == (NIL):
contine ()
else:
gcse.extend(SIGCSE)
LIG = len(gcse)
test = (LIG)
if test == (NIL):
contine ()
else:
gcse.extend(EIGCSE)
LIG = len(gcse)
test = (LIG)
if test == (NIL):
contine ()
else:
test2()
def contine ():
print(gcse)
gcseto = ''.join(gcse)
print (gcseto)
gcsenum = (str_to_nums(gcseto))
print (gcsenum)
numberencryption = [sum(i) for i in zip(numbers,gcsenum)]
print(numberencryption)
for num in numberencryption:
if num > 26:
added=(numbers + gcsenum) - 26
print(added)
print (numberencryption)
letterencryption = (nums_to_str(numberencryption))
print(letterencryption)
letters = input('Write Text: ')
letters = letters.lower()
numbers = (str_to_nums(letters))
print (numbers)
gcse = ["g","c","s","e"]
print (gcse)
GIGCSE=["g"]
CIGCSE=["c"]
SIGCSE=["s"]
EIGCSE=["e"]
test2()
我的代码将字母加密成另一个字母,如
hello>[8, 5, 12, 12, 15]
gcse>['g', 'c', 's', 'e']>['g', 'c', 's', 'e', 'g']gcseg>[7, 3, 19, 5, 7]
然后它将两者加在一起制作
[15, 8, 31, 17, 22]
然后转换成相应的数字:
哦(某些符号)qv,我想要做的就是它达到26的数字极限
A = 1 Z = 26 一个= 27 Z = 52
所以它在26之后循环播放
我得到的错误是:TypeError:不支持的操作数类型 - :' list'和' int'
答案 0 :(得分:0)
错误在函数added=(numbers + gcsenum) - 26
的{{1}}中,因为contine ()
和numbers
都是列表,这个gcsenum
会将它们连接成一个更大的列表并减去一个列表中的数字是无效的操作。我不明白你的意图所以我无法提供你必须自己找到的解决方案
答案 1 :(得分:0)
这是一个清理版本:
from itertools import cycle
BASE = ord('a') - 1
def str_to_nums(s):
"""
Convert a lowercase string to a list of integers in [1..26]
"""
return [ord(ch) - BASE for ch in s]
def nums_to_str(nums):
"""
Convert a list of integers in [1..26] back to a lowercase string
"""
return "".join(chr(n + BASE) for n in nums)
def shift_cypher(string, key_string):
nums = str_to_nums(string)
key = str_to_nums(key_string)
# x % 26 returns a value in [0..25]
# but we want a value in [1..26]
# so after % (mod) we have to add one
# so _before_ we add we have to subtract one
# so that the result comes out right!
encrypted = [((num + k - 1) % 26) + 1 for num,k in zip(nums, cycle(key))]
return nums_to_str(encrypted)
def main():
text = input("Text to encode: ")
key = input("Key to encode by: ")
print("Result is", shift_cypher(text, key))
if __name__ == "__main__":
main()
像
一样运行Text to encode: hello
Key to encode by: aaa
Result is ifmmp