所以,我在 CodeEval 上遇到了这个挑战,但我似乎不知道从哪里开始,所以我需要一些指导(如果可以的话,还需要答案)来帮助我解决这个挑战。
描述:
有一个板(矩阵)。棋盘的每个单元格都包含一个整数,最初为 0。
接下来的操作可以应用于查询板:
SetRow i x: it means that all values in the cells on row "i" have been change value to "x" after this operation.
SetCol j x: it means that all values in the cells on column "j" have been changed to value "x" after this operation.
QueryRow i: it means that you should output the sum of values on row "i".
QueryCol j: it means that you should output the sum of values on column "j".
电路板的尺寸为 256x256
i 和 j 是从 0 到 255
x 是从0 到31
输入样本:
你的程序应该接受一个文件名路径作为它的第一个参数。此文件中的每一行都包含一个查询操作。例如
SetCol 32 20
SetRow 15 7
SetRow 16 31
QueryCol 32
SetCol 2 14
QueryRow 10
SetCol 14 0
QueryRow 15
SetRow 10 1
QueryCol 2
输出样本:
对于每个查询,输出查询的答案。例如
5118
34
1792
3571
我在 Python 方面不是那么,但这个挑战非常有趣,尽管我对如何解决它没有任何线索。所以,我需要你们的帮助。
谢谢!
请您参考如下方法:
您可以为此使用稀疏矩阵;由 (col, row) 元组作为字典中的键进行寻址,以节省内存。否则 64k 单元是一个大列表(在 64 位系统上为 2MB+):
matrix = {}
这样效率更高,因为挑战不太可能为板上的所有行和列设置值。
然后设置列或行:
def set_col(col, x):
for i in range(256):
matrix[i, col] = x
def set_row(row, x):
for i in range(256):
matrix[row, i] = x
然后对行或列求和:
def get_col(col):
return sum(matrix.get((i, col), 0) for i in range(256))
def get_row(row):
return sum(matrix.get((row, i), 0) for i in range(256))
