Prepare > Python > Numpy > Transpose and Flatten

2023. 8. 28. 20:02HackerRank-Python

 

Transpose and Flatten | HackerRank

Use the transpose and flatten tools in the NumPy module to manipulate an array.

www.hackerrank.com

 

문제


Task

You are given a NXM integer array matrix with space separated elements ( N= rows and  M= columns).
Your task is to print the transpose and flatten results.

Input Format

The first line contains the space separated values of N and M.
The next N lines contains the space separated elements of M columns.

Output Format

First, print the transpose array and then print the flatten.

 

=> N과M 을 줄건데 N행, M열의 array에 대해 transpose와 flatten한 array를 출력하라

 

 

 

 

코드


import numpy as np

N, M = map(int, input().split())


a = []
for i in range(N):
    a.append(list(map(int, input().split())))
  
my_arr = np.array(a)


print(np.transpose(my_arr))
print(my_arr.flatten())

 

 

 

 

노트


numpy.array 생성

numpy.array()  # 이딴거 안됨

numpy.array(a)  # 뭐든 넣어줘야 함
  • 빈 array 생성은 불가

 

 

np.transpose(my_arr) 

import numpy

my_array = numpy.array([[1,2,3],
                        [4,5,6]])
print(numpy.transpose(my_array))

#Output
[[1 4]
 [2 5]
 [3 6]]
  • 입력된 numpy의 행과 열을 뒤바꿈(전치함. transpose)
  • 따라서 numpy의 차원도 (N, M) 에서 (M,N)으로 바뀜
  • 기존 array는 보존, 새 array 생성

 

 

my_arr.flatten()

import numpy

my_array = numpy.array([[1,2,3],
                        [4,5,6]])
print my_array.flatten()

#Output
[1 2 3 4 5 6]
  • array의 차원을 1차원으로 만들어버림
  • array 요소들을 한 줄에 모두 출력 (N x M,1)
  • 기본 array는 보존, 새 array 생성
더보기
import numpy

my_array = numpy.array([[1,2,3],
                        [4,5,6]])
print(my_array.flatten().shape)

# (6,)

 

 

코드 간략히

Before

a = []
for i in range(N):
    a.append(list(map(int, input().split())))
  
my_arr = np.array(a)
  • array로 만들어줄 빈 리스트 생성
  • 반복문을 이용해 리스트 채우기(숫자형 변환 포함)
  • 리스트를 array로 만들기

After

my_arr = np.array(
	[list(map(int,input().split())) for _ in range(N)]
)
  • np.array() 안에 for 반목문을 넣어버림(숫자형 변환 포함)
  • 대괄호는 왜 필요하지 모르겠지만 필요함
  • map 함수는 map객체를 리턴하기 때문에 리스트에 담아줘야하고, 리스트 comprehension구문을 쓰기 때문에? []가 필요한 듯

 

 

두 번째 시도

import numpy

N, M = map(int, input().split())

my_array = []
for i in range(N):
    my_array.append(list(map(int, input().split())))


my_arr = numpy.array(my_array)
print(my_arr.transpose())
print(my_arr.flatten())
  • numpy.transpose() 와 array.transpose() 둘 다 되네

 

 

 

참조


 

Discussion on Transpose and Flatten Challenge

Use the transpose and flatten tools in the NumPy module to manipulate an array.

www.hackerrank.com