"Buch, um die Programmierfähigkeit zu trainieren, um in der Welt zu kämpfen" Python-Code-Antwortbeispiel - 1,8 "0" -Matrix
import numpy as np
def setZeros(matrix):
row = [False] * matrix.shape[0]
column = [False] * matrix.shape[1]
for i in range(matrix.shape[0]):
for j in range(matrix.shape[1]):
if matrix[i,j] == 0:
row[i] = True
column[j] = True
for i in range(len(row)):
if row[i]:
nullifyRow(matrix,i)
for j in range(len(column)):
if column[j]:
nullifyColumn(matrix,j)
def nullifyRow(matrix, row):
for j in range(matrix.shape[1]):
matrix[row,j] = 0
def nullifyColumn(matrix, col):
for i in range(matrix.shape[0]):
matrix[i,col] = 0
input_matrix_1 = np.matrix([[1,2,3,4],[5,6,0,8],[9,10,11,12],[13,14,15,16]])
print(input_matrix_1)
setZeros(input_matrix_1)
print(input_matrix_1)
input_matrix_2 = np.matrix([[0,2,3,4],[5,6,7,8],[9,10,11,12],[0,14,15,16]])
print(input_matrix_2)
setZeros(input_matrix_2)
print(input_matrix_2)
Recommended Posts