2013-11-22 1 views
1

"d/n"형식의 두 분수를 사용자가 입력하게하는 코드를 만들었습니다.파이썬 클래스 소수 번호

어떻게 축소 된 형태의 분수를 인쇄 할 수 있습니까?

예 : 2/4를 입력하면 1/2이 인쇄됩니까?

import sys 

class Rational: 

    def __init__(self,n,d): 
    self.numerator= n 
    self.denominator= d 
    def value(self): 
    return float(self.numerator)/float(self.denominator) 

    def __repr__(self): 
    return "%d/%d ~ %g" % (self.numerator,self.denominator,self.value()) 
    def read(self): 
    while 1: 
     try: 
     s=raw_input("Enter fraction n/d: ") 
     n,d= s.split("/") 
     self.numerator= int(n) 
     self.denominator= int(d) 
     except KeyboardInterrupt: 
     print 
     exit() 
     except: 
     print sys.exc_info()[0] 
     print "bad input, try again." 
     else: 
     if int(d)==0: 
      print "The denominator cannot be zero. Try again." 
     elif int(d)<0: 
      print "The denominator cannot be negative. Try again." 
     else: 
      return 

r1=Rational(1,1) 
r1.read() 
print r1 

r2=Rational(1,1) 
r2.read() 
print r2 
+1

분수 모듈의 존재를 알고 있습니까? – Ant

답변

4

당신을 위해 작업을 수행 fractions.Fraction() class를 사용하고 있습니다

>>> import fractions 
>>> fractions.Fraction(2, 4) 
Fraction(1, 2) 

분수 스스로를 단순화하기 위해, 최대 공약수를 계산 :

def gcd(a, b): 
    while b: 
     a, b = b, a%b 
    return a 

g = gcd(numerator, denominator) 
numerator //= g 
denominator //= g 
+0

내가 '/'대신 '/'를 물어도 될까요? ?? – RGS

+1

@RSerrao : float division 대신 floor division (또는 Python 2에서는 피연산자에 따라 floor * 또는 float division). –

+0

요점은, g가 num과 den의 전체 제수가 될 것이라는 것을 알고 있다면, 왜 floor division입니까? 좋은 연습인가요 아니면 중요하지 않습니까? – RGS

0

는 단순히 numerator와 분할 번호를 표시하기 전에 greatest common divisordenominator을 입력하십시오. 그것은 당신이 당신 자신의 클래스를 사용하고자하는 경우입니다. 그렇지 않은 경우 fractions 모듈에 Fraction 클래스가 있습니다.

0

먼저, 분수에 대한 축소 된 양식을 계산하는 Rational 클래스에 지원을 추가해야합니다. 기본적으로, 당신이해야 할 일은 reduce() 메소드를 추가하는 것입니다.이 메소드는 Rational의 두 분자, 분모의 가장 낮은 공통 분모를 찾습니다. 알고리즘에 대해서는 Least Common Multiple을보십시오. 이 도움이

0
import fractions 

f = fractions.Fraction(5, 10) 
print (f) # print 1/2 
1
>>> num = 2 
    >>> den = 4   
    >>> from fractions import Fraction 
    >>> frac = Fraction(num,den).limit_denominator() 
    >>> numer = frac.numerator 
    >>> denom = frac.denominator 
    >>> print '%d/%d ~ %g' % (numer, denom, float(numer)/denom) 
    1/2 ~ 0.5 

희망. (링크 http://docs.python.org/2/library/fractions.html)