2015-04-07 2 views
-1

Как создать метод divide в Python?Как создать метод разделения в Python

Это мой код:

# Rational numbers 

def gcd(bigger, smaller): 
    '''compute the greatest common divisor of two positive integers''' 
    #print(' in gcd ') 
    if not bigger > smaller : 
     bigger, smaller = smaller, bigger 
    while smaller != 0: 
     remainder = bigger % smaller 
     #print('gcd calc, big:{}, small:{}, rem:{}'.format(bigger, smaller, remainder)) 
     bigger, smaller = smaller, remainder 
    return bigger 

def lcm(a, b): 
    '''calculate the least common multiple of two positive integers''' 
    #print(' in lcm ') 
    return (a*b)//gcd(a,b) 


class Rational(object): 
    '''Rational with numerator and denominator. Denominator defaults to 1''' 

    def __init__(self, numer, denom = 1): 
     #print('in constructor') 
     self.numer = numer 
     self.denom = denom 

    def __str__(self): 
     '''String representation for printing''' 
     #print(' in str ') 
     return str(self.numer) + '/' + str(self.denom) 

    def __repr__(self): 
     ''' Used in the interpreter. Call __str__ for now''' 
     print(' in repr ') 
     return self.__str__() 

    def __add__(self, param_Rational): 
     '''Add two Rationals''' 
     if type(param_Rational) == int: 
      param_Rational = Rational(param_Rational) 
     if type(param_Rational) == Rational: 
      # find the lcm 
      the_lcm = lcm(self.denom, param_Rational.denom) 
      # multiply each numerator by the lcm, then add 
      numerator_sum = the_lcm*self.numer/self.denom + \ 
         the_lcm*param_Rational.numer/param_Rational.denom 
      return Rational(int(numerator_sum), the_lcm) 
     else: 
      print("Wrong type in addition method.") 
      raise(TypeError) 

    def __sub__(self, param_Rational): 
     '''Subtract two Rationals''' 
     #print(' in add ') 
     # find the lcm 
     the_lcm = lcm(self.denom, param_Rational.denom) 
     # multiply each numerator by the lcm, then add 
     numerator_sum = the_lcm*self.numer/self.denom - \ 
        the_lcm*param_Rational.numer/param_Rational.denom 
     return Rational(int(numerator_sum), the_lcm) 

    def reduce_rational(self): 
     '''Return the reduced fraction value as a Rational''' 
     # find the gcd and divide numerator and denominator by it 
     the_gcd = gcd(self.numer, self.denom) 
     return Rational(self.numer//the_gcd, self.denom//the_gcd) 

    def __eq__(self, param_Rational): 
     '''Compare two Rationals for equalit and return a Boolean''' 
     reduced_self = self.reduce_rational() 
     reduced_param = param_Rational.reduce_rational() 
     return reduced_self.numer == reduced_param.numer and\ 
       reduced_self.denom == reduced_param.denom 

    def __mul__(self, param_Rational): 
     ''' Multiply two Rationals ''' 
     if type(param_Rational) == int: 
      param_Rational = Rational(param_Rational) 

     if type(param_Rational) == Rational: 
      #multiply 
      denom_zero_check = self.denom 
      second_denom_zero_check = param_Rational.denom 
      if denom_zero_check & second_denom_zero_check > 0: 
       numer_mul = self.numer*param_Rational.numer 
       denom_mul = self.denom*param_Rational.denom 
       return Rational(int(numer_mul),int(denom_mul)) 
      else: 
       print("Denominator can't be zero.") 
     else: 
      print("Wrong type in subtraction method") 
      raise(TypeError) 
      """ """ 

    def __truediv__(self):   # <-------- Here is where TypeError occurs # 
     ''' Divide two Rationals ''' 
     if type(param_Rational) == int: 
      param_Rational = Rational(param_Rational) 

     if type(param_Rational) == Rational: 
      #multiply 
      denom_zero_check = self.denom 
      second_denom_zero_check = param_Rational.denom 
      if denom_zero_check & second_denom_zero_check > 0: 
       numer_mul = self.numer*param_Rational.denom 
       denom_mul = self.denom*param_Rational.numer 
       return Rational(int(numer_mul),int(denom_mul)) 
      else: 
       print("Denominator can't be zero.") 

И я получаю ошибку (место отмеченные выше):

TypeError: __truediv__() takes 1 positional argument but 2 were given 

Как это исправить? Я получил умножение вниз, но не разделить, следует ли использовать div или truediv? И мне нужно использовать / в фактическом методе div?

+0

Не могли бы вы вывести сообщение об ошибке и указать строку, в которой произошла ошибка? – Kimbluey

+0

Traceback (самый последний вызов последнего): Файл "C:/Users/чан/Desktop/тестирование multiply.py", строка 138, в r5 = r3/r4 TypeError: __truediv __() занимает 1-позиционное аргумент, но 2 были даны –

+0

Кажется, вы просто публикуете целую кучу кода и несколько неопределенное сообщение об ошибке, и вы ожидаете, что другие пользователи предоставят готовое к использованию исправление. Формат SO, пожалуй, не самый подходящий для этого. Более конкретно. На первый взгляд вы как-то называете истинный() с неправильными аргументами, относительно основной ошибкой. – Kris

ответ

2

Как может __truediv__ принимать только один аргумент? Вам нужны два, self и делитель. Точно так же ваш __mul____add__, и __sub__ нужен второй аргумент.

def __truediv__(self, param_Rational): 
    # rest of your code 
+0

, если я использую __truediv__, я ничего не получаю от ответа, когда я делаю r5 = r3/r4 –

+1

@ ChAnChaoSae: В вашем методе '__truediv __()' есть пути кода, поскольку он ничего не возвращает (что фактически делает его возвратом 'None'). В таких случаях вместо этого вы должны создать исключение. – martineau

+0

Я забыл это, СПАСИБО! –

Смежные вопросы