2016-06-07 2 views
1

2 분수와 연산자를 읽고 평가할 때 답을 나에게주는 프로그램을 작성했습니다. 코드의 길이에 신경 쓰지 마라. 방금 완성했다고 덧붙였다. 내 질문은 다음과 같다 : I 입력출력 합계 단순화 python3

12/23 
23/12 
* 

나는 그것이 나에게 출력 1을주고 원하는대로 입력 할 때. 그러나 그것은 나를 1/1 준다. 이 문제를 어떻게 해결할 수 있습니까? 이 모든 경우를 처리 할

def __str__ (self): 
    if self.d == 1: 
     return "%d" % self.n 
    return "%d/%d" % (self.n, self.d) 

: 당신이 내부적으로 두 개의 동일한 번호를 저장하는 방법을 중요하지 않기 때문에

x = input().split('/') 
y = input().split('/') 
z = input() 
def gcd (a, b): 
    if b == 0: 
     return a 
    else: 
     return gcd(b, a%b) 

class Rational: 
    def __init__ (self, a=0, b=1): 
     g = gcd (a, b) 
     self.n = a/g 
     self.d = b/g 
    def __add__ (self, other): 
     return Rational (self.n * other.d + other.n * self.d, 
          self.d * other.d) 
    def __sub__ (self, other): 
     return Rational (self.n * other.d - other.n * self.d, 
          self.d * other.d) 
    def __mul__ (self, other): 
     return Rational (self.n * other.n, self.d * other.d) 
    def __div__ (self, other): 
     return Rational (self.n * other.d, self.d * other.n) 
    def __str__ (self): 
     return "%d/%d" % (self.n, self.d) 
    def __float__ (self): 
     return float (self.n)/float (self.d) 

q = Rational() 
w = Rational() 
q.n = int(x[0]) 
q.d = int(x[1]) 
w.n = int(y[0]) 
w.d = int(y[1]) 
answer = eval("q"+z+"w") 

답변

1

수정할 필요로하는 유일한 방법은 외부 표현을 수행하는 __str__입니다 을 포함하여 n/1을 올바르게 입력하십시오.