Prepare > Python > Python Functionals > Reduce Function
2023. 10. 3. 12:58ㆍHackerRank-Python
Reduce Function | HackerRank
Python Practice
www.hackerrank.com
문제
=> 유리수의 개수 n 과, 공백으로 분리된 분자, 분모들을 인풋해줄건데, 유리수들을 곱해서 나오는 값의 분자, 분모를 출력해라.
코드
from fractions import Fraction
from functools import reduce
def product(fracs):
t = reduce(lambda x, y: x * y, fracs)
return t.numerator, t.denominator
if __name__ == '__main__':
fracs = []
for _ in range(int(input())):
fracs.append(Fraction(*map(int, input().split())))
result = product(fracs)
print(*result)
노트
rational number: 유리수
numerator: 분자
denominator: 분모
Fraction()
유리수 표현과 계산에 사용하는 함수
기본사용
a = Fraction(1, 5) # 분수 1/5를 의미
print(a)
# Fraction(1, 5)
a = Fraction('1/5') # 문자열로 입력
print(a)
# Fraction(1, 5)
연산 가능
result = Fraction(1, 5)+Fraction(2, 5)
print(result)
# Fraction(3, 5)
분자, 분모 값 추출
a = Fraction(1, 5) # 분수 1/5를 의미
print(a.numerator) # 분자
print(a.denominator) # 분모
"""
1
5
"""
실수형 변환
print(float(result))
# 0.6
reduce()
누적 연산, 혹은 함수의 누적 적용에 사용하는 함수
reduce(함수, iterable, 초기값)
print(reduce(lambda x, y : x + y,[1,2,3]))
# 6
- 함수는 람다함수로 지정: 아하 누적합을 구하려고 하는구나
- iterable은 리스트
- 초기값 default는 0
- ((1+2)+3)의 순서로 연산
print(reduce(lambda x, y : x + y, [1,2,3], -3))
# 3
- (((-3+1)+2)+3) 의 순서임
from fractions import gcd
print(reduce(gcd, [2,4,8], 3))
# 1
- gcd는 최대공약수(greatest common divisor)를 구하는 함수
참조
020 분수를 정확하게 계산하려면? ― fractions
fractions는 유리수를 계산할 때 사용하는 모듈이다. > 유리수(rational number)란 두 정수의 비율 또는 분수 형식으로 나타낼 수 있는 수를 말한다. ## …
wikidocs.net
[python] 파이썬 최대공약수, 최소공배수 함수 (gcd, lcm)
안녕하세요. BlockDMask입니다. 오늘은 파이썬에서 최대공약수와 최소공배수를 구할 수 있는 함수 gcd 함수와, lcm 함수에 대해서 알아보겠습니다. 파이썬에서는 정말 많은 게 함수로 되어있네요. 하
blockdmask.tistory.com
'HackerRank-Python' 카테고리의 다른 글
itertools > Maximize It! (1) | 2024.02.12 |
---|---|
Prepare > Python > Python Functionals > Validating Email Addresses With a Filter (1) | 2023.10.04 |
Prepare > Python > Built-Ins > ginortS (0) | 2023.10.02 |
Prepare > Python > Built-Ins > Athlete Sort (0) | 2023.10.01 |
Prepare > Python > Built-Ins > Any or All (0) | 2023.09.29 |