def set(seq, row, col, val):
if seq[row-1][col-1] != val:
x = seq.remove(seq[row-1]) #[[32,33]]
y = seq.pop(row-1) #[50,92]
z = y.remove(row-1) #[50] It is wrong from here onwards
a = y.insert(row-1,val) #[50,50]
b = x.append(a) # [[32,33],[50,50]]
return b
鉴于
test_case_100 = make_matrix([[32, 33], [50, 92]]) # [[32, 33], [50, 92]]
然后set函数应该改变矩阵如下
set(test_case_100, 2, 2, 50) # [[32, 33], [50, 50]]
set(test_case_100, 2, 1, 30) #[[32, 33], [30, 50]]
set(test_case_100, 1, 2, 29) #[[32, 29], [30, 50]]
set(test_case_100, 1, 1, -20) #[[-20, 29], [30, 50]]
print(set(test_case_100, 2, 2, 50)) # [[-20, 29], [30, 50]]
答案 0 :(得分:2)
正如@thefourtheye在评论中所指出的那样,你使这个过得更加艰难。
def set_matrix(matrix, row, col, value):
try:
matrix[row-1][col-1] = value
except IndexError:
raise IndexError("No value at x:{}, y:{}".format(row,col))
这可能是将OOP引入编码风格的好时机。
class Matrix(list):
def __init__(self, *args):
for arg in args:
self.append(arg)
def setval(self,row,col,value):
try:
self[row-1][col-1] = value
except IndexError:
raise IndexError("No value at x:{}, y:{}".format(row,col))
test_matrix = Matrix([32, 33], [50, 92])
test_matrix.setval(2,2,50)
print(test_matrix) # [[32, 33], [50, 50]]
你在这里使用类似新课程的原因是你可以做一些很酷的事情:
class Matrix(list):
# code goes here
def __str__(self):
COLSIZE = max(map(len,(val for col in self for val in col)))+1
NUMCOLS = len(self[0]) # all rows equal size I hope!
formatstring = "{}{}{}".format("{:>",COLSIZE,"}")*NUMCOLS
return "\n".join(formatstring.format(*row) for row in self)
>>> print(Matrix([1,2],[3,4],[5,6]))
1 2
3 4
5 6
>>> print(Matrix([226,1],[330,1000],[15,17]))
226 1
330 1000
15 17