Prepare > Python > Numpy > Min and Max

2023. 9. 4. 19:48HackerRank-Python

 

Min and Max | HackerRank

Use the min and max tools of NumPy on the given 2-D array.

www.hackerrank.com

 

문제


Task

You are given a 2-D array with dimensions N X M.
Your task is to perform the min function over axis 1 and then find the max of that.

 

Input Format

The first line of input contains the space separated values of N and M.
The next N lines contains M space separated integers.

Output Format

Compute the min along axis 1 and then print the max of that result.

 

=> N X M 크기의 array줄건데, 열 방향에서 가장 작은 값들 중에서 가장 큰 값을 구하라

 

 

 

 

코드


import numpy as np

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

arr = np.array(
    [input().split() for _ in range(N)], int
)

row_min_arr = np.min(arr, axis=1)


print(np.max(row_min_arr))

 

 

 

 

노트


np.min()

import numpy

my_array = numpy.array([[2, 5], 
                        [3, 7],
                        [1, 3],
                        [4, 0]])

print(numpy.min(my_array, axis = 0))         #Output : [1 0]
print(numpy.min(my_array, axis = 1))         #Output : [2 3 1 0]
print(numpy.min(my_array, axis = None))      #Output : 0
print(numpy.min(my_array))                   #Output : 0
  • axis=0: 행 방향(가로)에서 가장 작은 값 리턴. (2, 3, 1, 4 중에서 1) & (5, 7, 3, 0 중에서 0)
  • axis=1: 열 방향(세로)에서 가장 작은 값 리턴. (2, 5 중에서 2) & (3, 7 중에서 3) & (1, 3 중에서 1) & (4, 0 중에서 0)
  • Defualt는 None으로 array의 모든 요소 중 가장 작은 값 리턴. (2, 5, 3, 7, 1, 3, 4, 0 중에서 0)

 

 

np.max()

import numpy

my_array = numpy.array([[2, 5], 
                        [3, 7],
                        [1, 3],
                        [4, 0]])

print(numpy.max(my_array, axis = 0))         #Output : [4 7]
print(numpy.max(my_array, axis = 1))         #Output : [5 7 3 4]
print(numpy.max(my_array, axis = None))      #Output : 7
print(numpy.max(my_array))                   #Output : 7
  • axis=0: 행 방향(가로)에서 가장 큰값 리턴. (2, 3, 1, 4 중에서 4) & (5, 7, 3, 0 중에서 7)
  • axis=1: 열 방향(세로)에서 가장 큰 값 리턴. (2, 5 중에서 5) & (3, 7 중에서 7) & (1, 3 중에서 3) & (4, 0 중에서 4)
  • Defualt는 None으로 array의 모든 요소 중 가장 큰 값 리턴 2, 5, 3, 7, 1, 3, 4, 0 중에서 7

 

 

두 번째 시도

import numpy as np

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

print(
    np.max(np.min(np.array([input().split() for _ in range(N)], int), axis=1))
    )
  • 리스트 컴프리헨션으로 최대한 한 줄에 써보기