创建函数guess_index

时间:2014-04-26 02:42:58

标签: python python-3.x python-3.3

创建一个函数guess_index,它将告知编号在哪里。因此,如果我有一个4x4电路板,则数字将为

[
[2,False], [3,False], [4, False], [1, False]
[ Same line as above
[same line as above
[same line as above

]

所以,首先我需要将其转换为如下所示的列表

[
[0,1,2,3],
[4,5,6,7],
[8,9,10,11],
[12,13,14,15]
]

所以guess_index(board,3)应该返回[0,3]意味着数字3位于第0行&第3栏。同样,guess_index(board,14)应该返回[3,2]。棘手的部分是让它适用于2x4和4x2矩阵等

我的代码是

def guess(board, guess)
     count = 0
  for i in board:
    for j in i:
      board[i][j] == [count]
      count += 1
  for a in board:
    for b in a:
      if b == guess:
        return [a,b]

但是当我尝试上面写的例子时,我只是得到了无?

1 个答案:

答案 0 :(得分:0)

从:

开始
board = [[[5, False], [5, False], [3, False], [4, False]],
         [[1, False], [0, False], [6, False], [7, False]],
         [[2, False], [2, False], [3, False], [0, False]],
         [[7, False], [6, False], [1, False], [4, False]]]

你可以:

def guess_index(board, guess):
    """Calculate coordinates for guess index within board."""
    row_len = len(board[0])
    return guess // row_len, guess % row_len

示例:

>>> guess_index(board, 3)
(0, 3)
>>> guess_index(board, 14)
(3 ,2)

然后,您可以使用它来获取board

中的整数和布尔值
row, col = guess_index(board, guess)
int_value, bool_value = board[row][col]

guess == 3int_value == 4 bool_value == False