파이썬 loop 질문드립니다
본문
# [,0] [,1] [,2] [,3] [,4]
#[0,] 17 11 5 3 1
#[1,] 19 13 7 4 2
#[2,] 21 15 9 8 6
#[3,] 23 16 14 12 10
#[4,] 25 24 22 20 18
안녕하세요 파이썬 공부하고 있는 초보자입니다 loop문을 1번만 사용해서 위와 같은 행렬을 만드려고 하는데 아래 if부분 코드작성에 어려움을 겪고 있습니다 ㅜㅜ 답변 남겨주시면 정말 감사드리겠습니다
def MyMatrix2(n):
#
# n = dimesion of (nXn) square matrix
if n < 2:
print(f'{"n ="} {n} {"should be >=2"}')
A = np.zeros([n,n], dtype=int)
# for example, n=5
# anti-diagonal component
# A[idx] = (5:1)^2, where idx = (4,0), (3,1), (2,2), (1,3), (0,4)
A[np.arange(n-1,-1,-1), np.arange(0,n)] = np.arange(n, 0, -1)**2
for i in np.arange(0, n):#start of "for" loop
#
# if i=4, idx = 5-4-1 = 0 --> [4,0] = [i,idx]
idx = n - i - 1
if A[idx,i] :
start_ = A[idx,i] - 2 * i
end_ = A[idx,i] - 2
row_vec = np.arange(start_, end_ + 1, 2)
col_vec = row_vec + 1
#
A[idx, np.arange(0,i)] = row_vec
A[np.arange(n-1,idx,-1),i] = col_vec
else:
start_ = A[idx,i] - 2*i
end_ = A[idx,i] - 2
col_vec = np.arange(start_, end_ + 1, 2)
row_vec = col_vec + 1
A[idx, np.arange(0,i)] = row_vec
A[np.arange(n-1, idx, -1),i] = col_vec
return(A)
답변 1
import numpy as np
def MyMatrix2(n):
#
# n = dimesion of (nXn) square matrix
if n < 2:
print(f'{"n ="} {n} {"should be >=2"}')
A = np.zeros([n,n], dtype=int)
# for example, n=5
# anti-diagonal component
# A[idx] = (5:1)^2, where idx = (4,0), (3,1), (2,2), (1,3), (0,4)
A[np.arange(n-1,-1,-1), np.arange(0,n)] = np.arange(n, 0, -1)**2
for i in np.arange(0, n):#start of "for" loop
#
# if i=4, idx = 5-4-1 = 0 --> [4,0] = [i,idx]
idx = n - i - 1
if A[idx,i] :
start_ = A[idx,i] - 2 * i
end_ = A[idx,i] - 2
row_vec = np.arange(start_, end_ + 1, 2)
col_vec = row_vec + 1
#
A[idx, np.arange(0,i)] = row_vec
A[np.arange(n-1,idx,-1),i] = col_vec
else:
start_ = A[idx,i] - 2*i
end_ = A[idx,i] - 2
col_vec = np.arange(start_, end_ + 1, 2)
row_vec = col_vec + 1
A[idx, np.arange(0,i)] = row_vec
A[np.arange(n-1, idx, -1),i] = col_vec
return(A)
A= MyMatrix2(4)
print('\n'.join([''.join(['{:4}'.format(item) for item in row]) for row in A]))
#또는 print(np.matrix(A))