LoginSignup
1
3

More than 3 years have passed since last update.

「世界で闘うプログラミング力を鍛える本」Pythonコード解答例 - 1.8 "0"の行列

Last updated at Posted at 2020-02-01

「世界で闘うプログラミング力を鍛える本」Pythonコード解答例 - 1.8 "0"の行列

目次

CHAP1. 配列と文字列

  1. 重複のない文字列
  2. 同じ文字の数を数える
  3. URLify
  4. 回文の順列
  5. 一発変換
  6. 文字列圧縮
  7. 行列の回転
  8. "0"の行列
  9. 文字列の回転

Pythonコード解答例


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)
1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3