2023. 9. 1. 20:25ㆍHackerRank-Python
Array Mathematics | HackerRank
Perform basic mathematical operations on arrays in NumPy.
www.hackerrank.com
문제
Task
You are given two integer arrays, A and B of dimensions N X.M
Your task is to perform the following operations:
- Add (A + B)
- Subtract (A - B)
- Multiply (A * B)
- Integer Division (A / B)
- Mod (A % B)
- Power (A ** B)
Note
There is a method numpy.floor_divide() that works like numpy.divide() except it performs a floor division.
Input Format
The first line contains two space separated integers, N and M.
The next N lines contains M space separated integers of array A.
The following N lines contains M space separated integers of array B.
Output Format
Print the result of each operation in the given order under Task.
=> array A,B 에 들어갈 M개의 숫자들을 N줄 줄건데 A,B에 대해 Task를 실행하라
코드
import numpy as np
N, M = map(int, input().split())
A = np.array([list(input().split()) for _ in range(N)], int)
B = np.array([list(input().split()) for _ in range(N)], int)
print(A + B)
print(A - B)
print(A * B)
print(np.floor_divide(A,B)) # A//B 나눗셈에서 몫을 구하는 메소드
print(A % B)
print(A ** B)
노트
array의 연산
import numpy
a = numpy.array([1,2,3,4], float)
b = numpy.array([5,6,7,8], float)
# 더하기
print(a + b) #[ 6. 8. 10. 12.]
print(numpy.add(a, b)) #[ 6. 8. 10. 12.]
# 빼기
print(a - b) #[-4. -4. -4. -4.]
print(numpy.subtract(a, b)) #[-4. -4. -4. -4.]
# 곱하기
print(a * b) #[ 5. 12. 21. 32.]
print(numpy.multiply(a, b)) #[ 5. 12. 21. 32.]
# 나누기
print(a / b) #[ 0.2 0.33333333 0.42857143 0.5 ]
print(numpy.divide(a, b)) #[ 0.2 0.33333333 0.42857143 0.5 ]
# 나눗셈의 몫
print(a // b) #[0. 0. 0. 0.]
print(numpy.floor_divide(a,b)) #[0. 0. 0. 0.]
# 나눗셈의 나머지
print(a % b) #[ 1. 2. 3. 4.]
print(numpy.mod(a, b)) #[ 1. 2. 3. 4.]
# 거듭제곱
print(a**b) #[ 1.00000000e+00 6.40000000e+01 2.18700000e+03 6.55360000e+04]
print(numpy.power(a, b)) #[ 1.00000000e+00 6.40000000e+01 2.18700000e+03 6.55360000e+04]
- 같은 인덱스끼리 연산됨
- 같은 shape여야만 연산이 가능함
참조
기본 수학 함수 | Numpy.floor_divide
나누기 함수(Floor divide function) numpy.floor_divide(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = 입력을 나눈 값보다 작거나 같은 정수 중 가장 큰 값을 반환합
moonnote.tistory.com
'HackerRank-Python' 카테고리의 다른 글
Prepare > Python > Numpy > Sum and Prod (0) | 2023.09.03 |
---|---|
Prepare > Python > Numpy > Floor, Ceil and Rint (0) | 2023.09.02 |
Prepare > Python > Numpy > Eye and Identity (0) | 2023.08.31 |
Prepare > Python > Numpy > Zeros and Ones (0) | 2023.08.30 |
Prepare > Python > Numpy > Concatenate (0) | 2023.08.29 |