import numpy as np
def matrixElementsSum(matrix):
a = np.array(matrix) # no need of appending in []
my_sum = 0 # sumofcolumn not required
for x in range(len(a)): # x in matrix row
for y in range(len(a[x])): # y in matrix col
if a[x][y] == 0 and x < len(a)-1: # handling last index
a[x+1][y] = 0 # set next row same column=0
my_sum += a[x][y] # adding value to sum..
# no for loop required, you are not appending values to a list.
# it's an integer and it's declared outside of loops.
return my_sum
matrix = [[0, 1, 1, 2], [0, 5, 0, 0], [2, 0, 3, 3]]
print(matrix)
print(matrixElementsSum(matrix))
total = 0
zeros = []
for row in matrix:
total += sum([val for ix, val in enumerate(row) if not ix in zeros])
zeros = [ix for ix, i in enumerate(row) if i == 0]
total
import numpy as np
matrix = [[0, 1, 1, 2], [0, 5, 0, 0], [2, 0, 3, 3]]
matrix = np.rot90(matrix).flatten()
indices = set(np.where(matrix==0)[0]+1) # set of indices to the right of 0 fast lookup
final = sum(e for i,e in enumerate(matrix) if i not in indices)
print(final)
找到有内联注释的woking代码。在
你可以这样做如下
你可以旋转,展平,他们使用一个简单的理解:
输出:
^{pr2}$旋转和展平时,将留下:
^{3}$如果你注意到,矩阵中所有上面有
0
的值,现在它们的左边都有0
,你可以使用列表理解来忽略这些值,然后求出结果的和。在我相信有一种方法可以不用旋转,但我觉得这种方法更容易想象。在
相关问题 更多 >
编程相关推荐