Given the numbers (NM) that you often see in problem books, A solution when the output result is obtained by some character string of N rows x M columns.
Example) Star chart, multiplication table, etc.
& + + + +
+ & + + +
+ + & + +
+ + + & +
+ + + + &
N M
import numpy as np
#(N M)= (5 5)Suppose there is an input in the form of
n, m = input().split()
n, m = int(n), int(m)
#Create a two-dimensional array with N rows and M columns(This time, all 0 arrays)
hyou = np.zeros((n,m))
#If there are multiple character strings to be displayed on the star chart, etc., set "Numbers in the array of that part" to 1.,2,3...And replace it in different cases
#This time it's a simple one that just puts 1 when the numbers in the row and column are the same
for i in range(n):
for j in range(m):
if i == j:
hyou[i][j] = 1
#Numerical value indicating the element at the end of the line(Subscript of the last element of a column in a two-dimensional array)
x = m -1
for i in range(n):
#Whether or not the output line ends is determined by whether j == x
#End if not the end=" "Output blank space with, and at the end, start a new line with the print function as it is
#Change the characters to be output for each number
for j in range(m):
if hyou[i][j] == 0 and j != x:
print("+", end = " ")
elif hyou[i][j] == 1 and j != x:
print("&", end = " ")
if hyou[i][j] == 0 and j == x:
print("+")
elif hyou[i][j] == 1 and j == x:
print("&" )
It's simple, but I think it's easy to forget, so I'll make a note of it.
Recommended Posts