728x90
반응형
https://www.acmicpc.net/problem/5376
5376번: 소수를 분수로
유리수 분수를 소수로 나타내면, 소수점 아래 자리가 유한 개인 경우(1/8 = 0.125)와 어떤 자리에서부터 일정한 숫자가 한없이 되풀이 되는 경우(1/11 = 0.090909...)가 있다. 소수를 입력받은 뒤, 분수로
www.acmicpc.net
문제 해결
- 순환소수를 분수로 바꾸는 방법을 알고 있다면 구현은 어렵지 않다.
- 하지만 순환부분만 존재를 할 때 순환하지 않는 부분(non_repeat)는 ""이 되는데 int(non_repeat)를 사용하면 ValueError가 뜨는 것을 인지하고 작성해야한다.
CODE
from math import gcd
def convert_to_fraction(decimal):
after_point = decimal.split('.')[1]
if '(' in after_point:
non_repeat, repeat = after_point.split('(')
repeat = repeat[:-1]
denominator = 10 ** (len(non_repeat)) * (10 ** len(repeat) - 1)
try:
numerator = int(non_repeat + repeat) - int(non_repeat)
except ValueError:
numerator = int(non_repeat + repeat)
else:
denominator = 10 ** len(after_point)
numerator = int(after_point)
divisor = gcd(numerator, denominator)
numerator //= divisor
denominator //= divisor
return f"{numerator}/{denominator}"
if __name__ == "__main__":
for _ in range(int(input())):
decimal = input()
fraction = convert_to_fraction(decimal)
print(fraction)
728x90
반응형
'알고리즘 > [python] 백준 BOJ' 카테고리의 다른 글
[python] 백준 2436 공약수 (0) | 2024.04.04 |
---|---|
[python] 백준 11562 백양로 브레이크 (1) | 2024.04.03 |
[python] 백준 2304 창고 다각형 (0) | 2024.03.14 |
[python] 백준 1315 RPG (0) | 2024.03.11 |
[python] 백준 14426 접두사 찾기 (0) | 2024.03.10 |
댓글