python中的二维数组

时间:2017-10-10 16:32:19

标签: python arrays list list-comprehension

CodeFights上有一项涉及构建二维数组的任务:

  

螺旋矩阵是大小为n×n的方阵。它包含所有   整数范围从1到n * n,因此数字1写在   右下角,所有其他数字都在增加   逆时针方向螺旋顺序。

     

考虑到矩阵n的大小,你的任务是创建一个螺旋   基质

在以下代码中,应该只填充一个由...表示的间隙:

def createSpiralMatrix(n):
    dirs = [(-1, 0), (0, -1), (1, 0), (0, 1)]
    curDir = 0
    curPos = (n - 1, n - 1)
    res = ...

    for i in range(1, n * n + 1):
        res[curPos[0]][curPos[1]] = i
        nextPos = curPos[0] + dirs[curDir][0], curPos[1] + dirs[curDir][1]
        if not (0 <= nextPos[0] < n and
                0 <= nextPos[1] < n and
                res[nextPos[0]][nextPos[1]] == 0):
            curDir = (curDir + 1) % 4
            nextPos = curPos[0] + dirs[curDir][0], curPos[1] + dirs[curDir][1]
        curPos = nextPos

    return res

当我填写以下代码时,所有测试都会通过:

res = [[0 for item in range(n)] for sublist in range(n)]

但是,如果我稍微改为:

res = [[None for item in range(n)] for sublist in range(n)]

我收到以下错误消息:

Execution error on test 1: Something went wrong when executing the solution - program stopped unexpectedly with an error.
Traceback (most recent call last):
  file.py3 on line ?, in getUserOutputs
    userOutput = _runiuljw(testInputs[i])
  file.py3 on line ?, in _runiuljw
    return createSpiralMatrix(*_fArgs_jlosndfelxsr)
  file.py3 on line 8, in createSpiralMatrix
    res[curPos[0]][curPos[1]] = i
IndexError: list index out of range
  

测试1输入:n:3输出:空预期输出:[[5,4,3],[6,9,2],   [7,8,1]]控制台输出:空

相同的结果(带有错误消息)使用以下代码:

res = [list(range(n)) for sublist in range(n)]

所有三个选项都构建了相同大小的数组:

n = 3

res = [[0 for item in range(n)] for sublist in range(n)]
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

res = [[None for item in range(n)] for sublist in range(n)]

[[None, None, None], [None, None, None], [None, None, None]]

res = [list(range(n)) for sublist in range(n)]

[[0, 1, 2], [0, 1, 2], [0, 1, 2]]

我错过了一些明显的东西吗?

1 个答案:

答案 0 :(得分:0)

如果您希望它与if not ...一起使用,则只需更改res语句的第三个条件即可同意您初始化nextPos的方式。否则,def createSpiralMatrix(n): dirs = [(-1, 0), (0, -1), (1, 0), (0, 1)] curDir = 0 curPos = (n - 1, n - 1) res = [[None for item in range(n)] for sublist in range(n)] for i in range(1, n * n + 1): res[curPos[0]][curPos[1]] = i nextPos = curPos[0] + dirs[curDir][0], curPos[1] + dirs[curDir][1] if not (0 <= nextPos[0] < n and 0 <= nextPos[1] < n and res[nextPos[0]][nextPos[1]] is None): # Changed this line curDir = (curDir + 1) % 4 nextPos = curPos[0] + dirs[curDir][0], curPos[1] + dirs[curDir][1] curPos = nextPos return res 将错误地超出2D数组的范围。

import random

def hundred_flips():
    result = sum([random.randint(0, 1) for i in range(100)])
    return result

all_results = [hundred_flips() for i in range(10**5)]