HackerRank-Python

Prepare > Python > Numpy > Sum and Prod

stem_sw 2023. 9. 3. 19:18
 

Sum and Prod | HackerRank

Perform the sum and prod functions 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 sum tool over axis 0 and then find the product of that result.

Input Format

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

Output Format

Compute the sum along axis 0. Then, print the product of that sum.

 

=> N x M 크기의 array를 줄건데, 행 방향으로 덧하고, 그 곱을 구하라

 

 

 

 

코드


import numpy as np

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

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

sum_arr = np.sum(my_arr, 0)  # axis = 0 을 0만 써줌

print(np.product(sum_arr, axis=None))

 

 

 

 

노트


np.sum()

import numpy

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

print(my_array)

# Output
[[1 2]
 [3 4]]
print numpy.sum(my_array, axis = 0)         #Output : [4 6]
print numpy.sum(my_array, axis = 1)         #Output : [3 7]
print numpy.sum(my_array, axis = None)      #Output : 10
print numpy.sum(my_array)                   #Output : 10
  • axis = 0: 행 방향(세로)으로 더해서 리턴. 1+3, 2+4
  • axis = 1: 열 방향(가로)로 더해서 리턴. 1+2, 3+4
  • Defualt는 None으로 array의 모든 요소를 더해서 리턴. 1+2+3+4

 

 

np.product()

import numpy

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

print numpy.prod(my_array, axis = 0)            #Output : [3 8]
print numpy.prod(my_array, axis = 1)            #Output : [ 2 12]
print numpy.prod(my_array, axis = None)         #Output : 24
print numpy.prod(my_array)                      #Output : 24
  • axis = 0: 행 방향(세로)으로 곱해서 리턴. 1x3, 2x4
  • axis = 1: 열 방향(가로)로 곱해서 리턴. 1x2, 3x4
  • Defualt는 None으로 array의 모든 요소들을 곱해서 리턴. 1x2x3x4