자료구조

#2 자료구조 <분수연산> Python

j9m 2020. 5. 5. 13:44
반응형

분수에 관한 기본연산과 비교연산에 대한 코드입니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
def gcd(m, n):  #최대공약수를 구하는 함수입니다.
    while n:
        m, n = n, m % n
    return m
 
class Fraction: #Fraction class를 만들어줍니다.
 
    def __init__(self, num, denom):  #constructor입니다
        self._num = num  #num은 분자값
        self._denom = denom  #denom은 분모값 입니다.
 
    def __repr__(self):  #string으로 출력하기위한 함수
        return str(self)
 
    def __str__(self): #__repr__함수를 이용해서 출력형식입니다.
        return str(self._num) + "/" + str(self._denom)
 
    def __add__(self, other):  #분수의 덧셈입니다.
        new_num = self._num * other._denom + self._denom * other._num #분자를 더해줍니다.
        new_denom = self._denom * other._denom #분모값을 통일시켜줍니다.
        common = gcd(new_num, new_denom) #common은 분자와 분수의 최대공약수 값입니다. 
        return Fraction(new_num // common, new_denom // common) #최대공약수로 나누어줍니다.
 
    def __sub__(self, other):
        new_num = self._num * other._denom - self._denom * other._num
        new_denom = self._denom * other._denom
        common = gcd(new_num, new_denom)
        return Fraction(new_num // common, new_denom // common) #최대공약수로 나누어줍니다.
    
    def _mul_(self,other):
        new_num = self._num*other._num #분자끼리 곱해줍니다.
        new_denom = self._denom*other._denom #분모끼리 곱해줍니다.  
        common = gcd(new_num,new_denom) #새로운 분수의 분모와 분자의 최대공약수값
        return Fraction(new_num // common, new_denom // common)
 
    def _truediv_(self,other):
        new_num = self._num * other._denom # 1/2 나누기 2/3은 1*3/2*2 
        new_denom = self._denom*other._num
        common = gcd(new_num,new_denom) #새로운 분수의 분모와 분자의 최대공약수값
        return Fraction(new_num // common,new_denom // common) #최대공약수로 나누어줍니다.
 
#아래는 분수 간 크기를 비교하는 함수입니다.     
    def __eq__(self, other):
        return (self._num * other._denom) == (other._num * self._denom)
    def __gt__(self, other): 
        return (self._num * other._denom) < (other._num * self._denom)
    def __ge__(self, other): 
        return (self._num * other._denom) <= (other._num * self._denom)
    def __lt__(self, other):
        return (self._num * other._denom) > (other._num * self._denom)
    def __le__(self, other):
        return (self._num * other._denom) >= (other._num * self._denom)
    def __ne__(self, other):
        return (self._num * other._denom) != (other._num * self._denom)
cs
분수에 관한 기본연산과 비교연산에 대한 코드입니다.

반응형