1

我是 python 的新手,并且为实现这一目标而苦苦挣扎。这是我的任务:

六字母密码是一种对涉及替换和转置的秘密消息进行编码的方法。加密首先随机填充一个 6  6 网格,其中包含从 A 到 Z 的字母和从 0 到 9 的数字(总共 36 个符号)。消息的发送者和接收者都必须知道这个网格。网格的行和列标有字母 A、B、C、D、E、F。

编写一个实现六字母密码方法的 Python 程序。你的程序应该: 1. 创建一个 6x6 的网格,并按照第一段中的描述随机填充字母和数字,然后提示用户输入一个秘密信息。2. 用户输入密文后,显示 6x6 网格和生成的密文。3.提示用户输入密文以显示原始消息。要求用户将密文的每两个字母用空格或逗号隔开即可。

我正在努力解决的问题是如何在嵌套列表中搜索已输入的随机放置的字母并给出坐标。坐标也不会以数字(即 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()
4

3 回答 3

4

我知道您这样做是出于学习/家庭作业的目的,但我会指出这一点,以供您稍后记住。更容易将您所拥有的内容视为 36 项(恰好可以表示为 6x6) - 或者更明确地 - 您有一个字符 -> 坐标,并且 adict非常有用,并且可以反转它...

from string import ascii_uppercase, digits
from random import shuffle
from itertools import product

# build 36 items list and randomise it
chars = list(ascii_uppercase + digits)
shuffle(chars)

# alternatively, use your existing grid:
from itertools import chain
chars = list(chain.from_iterable(grid))
# ...


# Create char -> (coords)
lookup = dict(zip(chars, product('ABCDEF', repeat=2)))
# Swap over so (coords) -> char
rev_lookup = {v: k for k,v in lookup.iteritems()}
于 2013-01-05T14:04:45.367 回答
2

您可以使用 Python 的 enumerate 来迭代值并随时提供每个值的索引位置:

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")

如果找不到该值,这将引发 a 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)
于 2013-01-05T13:38:59.760 回答
1

这是获取网格中字符坐标的简单方法:

def find_pos(s):
    for i, j in enumerate(grid):
        try:
            return i, j.index(s)
        except ValueError:
            continue
    raise ValueError("The value {0!r} was not found.".format(s))


>>> find_pos("O")
(2, 3)
于 2013-01-05T13:39:36.717 回答