我是python的新手,为实现这一目标付出了很多努力.
这是我的任务:
The Six-Letter Cipher is a method of encoding a secret message that
involves both substitution and transposition. The encryption starts by
randomly filling a 6 6 grid with the alphabet letters from A to Z
and the digits from 0 to 9 (36 symbols in total). This grid must be
known to both the sender and receiver of the message. The rows and
columns of the grid are labelled with the letters A, B, C, D, E, F.Write a Python program that implements the six-letter cipher method.
Your program should:
1. Create a 6×6 grid and fill it randomly with letters and numbers as described in the first paragraph, then prompt the user to enter a
secret message.
2. Display the 6×6 grid and the generated ciphertext, after the user enters the secret message.
3. Prompt the user to enter the ciphertext to display the original message. It is OK to ask the user to separate every two letters of the
ciphertext with a space or comma.
我苦苦挣扎的一点是如何在嵌套列表中搜索已输入的随机放置的字母并给出坐标.也不会以数字(即0,1)而不是字母(即A,B)给出坐标
我想一旦有了有关如何使用此嵌套列表的想法,便可以管理编码和解码.
到目前为止,这是我的代码:
grid = [["Z","9","G","Q","T","3"],
["Y","8","F","P","S","2"],
["X","7","E","O","R","1"],
["W","6","D","N","M","0"],
["V","5","C","L","K","U"],
["J","4","B","I","H","A"]]
def main():
print("Welcome to the sixth cipher")
print("Would you like to (E)Encode or (D)Decode a message?")
operation = input()
if(operation == "E"):
encodecipher()
elif(operation == "D"):
decodecipher()
else:
print("Sorry, input not recognised")
def encodecipher():
print("Please enter a message to encode:")
messagetoencode = input()
def decodecipher():
print("Decode Test")
rowcolumn()
def rowcolumn():
pass
main()
解决方法:
您可以使用Python的枚举对值进行迭代,并在使用时提供每个值的索引位置:
grid = [["Z","9","G","Q","T","3"],
["Y","8","F","P","S","2"],
["X","7","E","O","R","1"],
["W","6","D","N","M","0"],
["V","5","C","L","K","U"],
["J","4","B","I","H","A"]]
search = 'D'
for rownum, row in enumerate(grid):
for colnum, value in enumerate(row):
if value == search:
print "Found value at (%d,%d)" % (rownum, colnum)
您可以将其适应所选的函数结构,例如以下内容(如果网格中的值是唯一的):
def findvalue(grid, value):
for rownum, row in enumerate(grid):
for colnum, itemvalue in enumerate(row):
if itemvalue == value:
return (rownum, colnum)
raise ValueError("Value not found in grid")
如果找不到该值,则会引发ValueError,因此您必须在调用代码中处理该错误.
如果然后需要在0索引的行号和列号之间映射到字母A … F,则可以执行以下操作:
def numbertoletter(number):
if number >= 0 and number <= 26:
return chr(65 + number)
else:
raise ValueError('Number out of range')
这将为您提供以下内容:
>>> numbertoletter(0)
'A'
>>> numbertoletter(1)
'B'
将所有内容放在一起将为您提供:
value = 'B'
row, col = map(numbertoletter, findvalue(grid, value))
print "Value '%s' found at location (%s, %s)" % (value, row, col)