유리수 클래스
유리수를 항상 기약분수로 저장하고 다른 유리수와 사칙연산하는 Rational 클래스를 작성하시오.
작성할 클래스
다음 형태의 클래스를 작성한다.
class Rational:
def __init__(self, numerator, denominator):
# 코드를 작성하세요.
def add(self, other):
# 코드를 작성하세요.
def subtract(self, other):
# 코드를 작성하세요.
def multiply(self, other):
# 코드를 작성하세요.
def divide(self, other):
# 코드를 작성하세요.
def get_fraction(self):
# 코드를 작성하세요.
- 생성자는 분자
numerator와 0이 아닌 분모denominator를 받는다. - 저장되는 분모는 항상 양수여야 한다.
- 분자와 분모를 최대공약수로 나누어 항상 기약분수 형태로 저장한다.
- 값이 0인 유리수는 항상
0/1로 저장한다. add(other),subtract(other),multiply(other),divide(other)는 각각other와 덧셈, 뺄셈, 곱셈, 나눗셈한 새로운Rational객체를 반환한다.- 네 연산 메서드는 현재 객체와
other객체를 변경하지 않는다. get_fraction()은 현재 유리수를(numerator, denominator)형태의tuple로 반환한다.
클래스를 사용하는 코드
작성한 클래스는 아래 코드와 함께 실행된다.
numerator, denominator = map(int, input().split())
value = Rational(numerator, denominator)
q = int(input())
for _ in range(q):
command = input().split()
if command[0] == "value":
fraction = value.get_fraction()
else:
other = Rational(int(command[1]), int(command[2]))
before = value.get_fraction()
other_before = other.get_fraction()
if command[0] == "add":
result = value.add(other)
elif command[0] == "subtract":
result = value.subtract(other)
elif command[0] == "multiply":
result = value.multiply(other)
else:
result = value.divide(other)
if not isinstance(result, Rational):
raise TypeError("The result must be a Rational object.")
if value.get_fraction() != before:
raise ValueError("The original object must not be changed.")
if other.get_fraction() != other_before:
raise ValueError("The other object must not be changed.")
value = result
fraction = value.get_fraction()
print(fraction[0], fraction[1])
print(type(fraction))
위 코드가 정상적으로 동작하도록 클래스의 정의 전체를 제출한다. 입력을 받거나 객체를 생성하는 코드는 제출하지 않는다.
상태만 변경하는 메서드의 반환값은 출력하지 않는다. 값을 조회하거나 계산 결과를 반환하는 메서드는 반환값과 자료형을 출력한다.
입력
첫째 줄에 처음 유리수의 분자와 분모가 주어진다.
둘째 줄에 명령 수 \(Q\)가 주어진다. 다음 \(Q\)개의 줄에는 다음 명령 중 하나가 주어진다.
add n d: 현재 유리수에 \(n/d\)를 더한다.subtract n d: 현재 유리수에서 \(n/d\)를 뺀다.multiply n d: 현재 유리수에 \(n/d\)를 곱한다.divide n d: 현재 유리수를 \(n/d\)로 나눈다.value: 현재 유리수를 조회한다.
연산 명령이 끝나면 현재 유리수는 해당 연산으로 반환된 새 객체가 된다.
- \(-1,000,000 \le numerator,n \le 1,000,000\)
- \(1 \le |denominator|,|d| \le 1,000,000\)
divide명령에서는 \(n \ne 0\)이다.- \(1 \le Q \le 100\)
출력
각 명령마다 현재 유리수의 기약분수 형태를 분자 분모로 출력하고, get_fraction()이 반환한 값의 자료형을 출력한다.
예제 입력 1
1 2
6
value
add 1 3
subtract 1 6
multiply -3 4
divide 2 5
value
예제 출력 1
1 2
<class 'tuple'>
5 6
<class 'tuple'>
2 3
<class 'tuple'>
-1 2
<class 'tuple'>
-5 4
<class 'tuple'>
-5 4
<class 'tuple'>
예제 설명 1
처음 유리수는 1/2이다.
add 1 3의 결과는 \(1/2+1/3=5/6\)이다.subtract 1 6의 결과는 \(5/6-1/6=2/3\)이다.multiply -3 4의 결과는 \(2/3 \times (-3/4)=-1/2\)이다.divide 2 5의 결과는 \(-1/2 \div 2/5=-5/4\)이다.
모든 결과는 기약분수이며 분모는 양수이다. 마지막 value도 현재 값 -5/4를 반환한다.
예제 입력 2
2 4
1
value
예제 출력 2
1 2
<class 'tuple'>
코멘트