В созданном кассе Fraction, добавить сложение, вычитание, умножение дроби с целым числом?

Kira777

Новичок
Пользователь
Ноя 21, 2020
6
0
1
Есть класс дробей, необходимо добавить функцию сложения, вычитания, умножения? Есть несколько вариантов, но они не работают. Может кто-то подскажетБ что еще можно сделать?
Сам класс:
class Fraction:


def __init__(self, num, denom):
self.num = num
self.denom = denom

def __str__(self):
return str(self.num)+'/'+str(self.denom)

def __add__(self, other):
newnum = self.num * other.denom + other.num * self.denom
newdenom = self.denom * other.denom
common = gcd(newnum, newdenom)
return Fraction(newnum//common, newdenom//common)

def __sub__(self, other):
newnum = self.num * other.denom - other.num * self.denom
newdenom = self.denom * other.denom
common = gcd(newnum, newdenom)
return Fraction(newnum//common, newdenom//common)

def __mul__(self, other):
newnum = self.num * other.num
newdenom = self.denom * other.denom
common = gcd(newnum, newdenom)
return Fraction(newnum//common, newdenom//common)







if __name__ == "__main__":

f1 = Fraction(11,6)
f2 = Fraction(2,9)
print(f1+f2)
print(f1 - f2)
print(f1 * f2)


Варианты:
1.
def __add__(self, other):

if isinstance(other, (int, Fraction)):
return Fraction(self.num * other.denom +
other.num * self.denom,
self.denom * other.denom)


elif isinstance(other, float):
return float(self) + other
elif isinstance(other, complex):
return complex(self) + other

return NotImplemented
2.
def __add__(self,other): #попыткас целым числом
# является ли первый параметр сложения дробью

if not isinstance(self, Fraction):
return NotImplemented
# является ли второй параметр сложения дробью
if isinstance(other, Fraction):
self.num = other.num
self.denom = other.denom
# является ли второй параметр сложения целым числом
elif isinstance(other, int):
self.num = other
self.denom = 1
# является ли второй параметр сложения чем-то другим
else:
return NotImplemented

newnum = self.num * other.denom + other.num * self.denom
newdenom = self.denom * self.denom
common = gcd(newnum, newdenom)
return Fraction(newnum//common, newdenom//common)
 

regnor

Модератор
Команда форума
Модератор
Июл 7, 2020
2 625
469
83
вставьте код через теги code, где пишите сообщение, чуть выше есть панель инструментов, там три точки -> код -> Python, и туда вставляйте свой код
так ничего не понятно...
 

Kira777

Новичок
Пользователь
Ноя 21, 2020
6
0
1
Код:
def gcd(num, denom):
    while num%denom != 0:
        num, denom = denom, num%denom
    return denom

class Fraction:
    

    def __init__(self, num, denom):
        self.num = num
        self.denom = denom

    def __str__(self):
        return str(self.num)+'/'+str(self.denom)

    def __add__(self, other):
        newnum = self.num * other.denom + other.num * self.denom
        newdenom = self.denom * other.denom
        common = gcd(newnum, newdenom)
        return Fraction(newnum//common, newdenom//common)

    def __sub__(self, other):
        newnum = self.num * other.denom - other.num * self.denom
        newdenom = self.denom * other.denom
        common = gcd(newnum, newdenom)
        return Fraction(newnum//common, newdenom//common)

    def __mul__(self, other):
        newnum = self.num * other.num
        newdenom = self.denom * other.denom
        common = gcd(newnum, newdenom)
        return Fraction(newnum//common, newdenom//common)







if __name__ == "__main__":

    f1 = Fraction(11,6)
    f2 = Fraction(2,9)
    print(f1+f2)
    print(f1 - f2)
    print(f1 * f2)
    
    
    
    #1
    
        def __add__(self,other): #попыткас целым числом
    # является ли первый параметр сложения дробью
    
        if not isinstance(self, Fraction):
            return NotImplemented
    # является ли второй параметр сложения дробью
        if isinstance(other, Fraction):
            self.num = other.num
            self.denom = other.denom
    # является ли второй параметр сложения целым числом
        elif isinstance(other, int):
            self.num = other
            self.denom = 1
    # является ли второй параметр сложения чем-то другим
        else:
            return NotImplemented
        
        newnum = self.num * other.denom + other.num * self.denom
        newdenom = self.denom * self.denom
        common = gcd(newnum, newdenom)
        return Fraction(newnum//common, newdenom//common)


#2

    def __add__(self, other):
              
        if isinstance(other, (int, Fraction)):
            return Fraction(self.num * other.denom +
                            other.num * self.denom,
                            self.denom * other.denom)
                
                
        elif isinstance(other, float):
            return float(self) + other
        elif isinstance(other, complex):
            return complex(self) + other
                
            return NotImplemented
 

regnor

Модератор
Команда форума
Модератор
Июл 7, 2020
2 625
469
83
так у вас все работает... где ошибка то?
Python:
def gcd(num, denom):
    while num % denom != 0:
        num, denom = denom, num % denom
    return denom


class Fraction:

    def __init__(self, num, denom):
        self.num = num
        self.denom = denom

    def __str__(self):
        return str(self.num) + '/' + str(self.denom)

    def __add__(self, other):
        newnum = self.num * other.denom + other.num * self.denom
        newdenom = self.denom * other.denom
        common = gcd(newnum, newdenom)
        return Fraction(newnum // common, newdenom // common)

    def __sub__(self, other):
        newnum = self.num * other.denom - other.num * self.denom
        newdenom = self.denom * other.denom
        common = gcd(newnum, newdenom)
        return Fraction(newnum // common, newdenom // common)

    def __mul__(self, other):
        newnum = self.num * other.num
        newdenom = self.denom * other.denom
        common = gcd(newnum, newdenom)
        return Fraction(newnum // common, newdenom // common)


if __name__ == "__main__":

    f1 = Fraction(11, 6)
    f2 = Fraction(2, 9)
    print(f1 + f2)  # Ответ 37/18
    print(f1 - f2)  # Ответ 29/18
    print(f1 * f2)  # Ответ 11/27
или вам нужно помочь исключения написать при неверном вводе?
 
Последнее редактирование:

regnor

Модератор
Команда форума
Модератор
Июл 7, 2020
2 625
469
83
так можно с исключениями
Python:
def gcd(num, denom):
    while num % denom != 0:
        num, denom = denom, num % denom
    return denom


class Fraction:

    def __init__(self, num, denom):
        self.num = num
        self.denom = denom

    def __str__(self):
        return str(self.num) + '/' + str(self.denom)

    def __add__(self, other):
        if isinstance(self.num, int) and isinstance(self.denom, int) and isinstance(other.num, int) and isinstance(
                other.denom, int):
            newnum = self.num * other.denom + other.num * self.denom
            newdenom = self.denom * other.denom
            common = gcd(newnum, newdenom)
            return Fraction(newnum // common, newdenom // common)
        else:
            raise TypeError('must be int')

    def __sub__(self, other):
        if isinstance(self.num, int) and isinstance(self.denom, int) and isinstance(other.num, int) and isinstance(
                other.denom, int):
            newnum = self.num * other.denom - other.num * self.denom
            newdenom = self.denom * other.denom
            common = gcd(newnum, newdenom)
            return Fraction(newnum // common, newdenom // common)
        else:
            raise TypeError('must be int')

    def __mul__(self, other):
        if isinstance(self.num, int) and isinstance(self.denom, int) and isinstance(other.num, int) and isinstance(
                other.denom, int):
            newnum = self.num * other.num
            newdenom = self.denom * other.denom
            common = gcd(newnum, newdenom)
            return Fraction(newnum // common, newdenom // common)
        else:
            raise TypeError('must be int')


if __name__ == "__main__":
    f1 = Fraction(11, 6)
    f2 = Fraction(2, 9)
    print(f1 + f2)  # Ответ 37/18
    print(f1 - f2)  # Ответ 29/18
    print(f1 * f2)  # Ответ 11/27

    f1 = Fraction('11', 6)
    f2 = Fraction(2, 9)
    print(f1 + f2)  # TypeError('must be int')

    f1 = Fraction(11, 6)
    f2 = Fraction(2.2, 9)
    print(f1 + f2)  # TypeError('must be int')
 
Последнее редактирование:

Kira777

Новичок
Пользователь
Ноя 21, 2020
6
0
1
так у вас все работает... где ошибка то?
Python:
def gcd(num, denom):
    while num % denom != 0:
        num, denom = denom, num % denom
    return denom


class Fraction:

    def __init__(self, num, denom):
        self.num = num
        self.denom = denom

    def __str__(self):
        return str(self.num) + '/' + str(self.denom)

    def __add__(self, other):
        newnum = self.num * other.denom + other.num * self.denom
        newdenom = self.denom * other.denom
        common = gcd(newnum, newdenom)
        return Fraction(newnum // common, newdenom // common)

    def __sub__(self, other):
        newnum = self.num * other.denom - other.num * self.denom
        newdenom = self.denom * other.denom
        common = gcd(newnum, newdenom)
        return Fraction(newnum // common, newdenom // common)

    def __mul__(self, other):
        newnum = self.num * other.num
        newdenom = self.denom * other.denom
        common = gcd(newnum, newdenom)
        return Fraction(newnum // common, newdenom // common)


if __name__ == "__main__":

    f1 = Fraction(11, 6)
    f2 = Fraction(2, 9)
    print(f1 + f2)  # Ответ 37/18
    print(f1 - f2)  # Ответ 29/18
    print(f1 * f2)  # Ответ 11/27
или вам нужно помочь исключения написать при неверном вводе?
так у вас все работает... где ошибка то?
Python:
def gcd(num, denom):
    while num % denom != 0:
        num, denom = denom, num % denom
    return denom


class Fraction:

    def __init__(self, num, denom):
        self.num = num
        self.denom = denom

    def __str__(self):
        return str(self.num) + '/' + str(self.denom)

    def __add__(self, other):
        newnum = self.num * other.denom + other.num * self.denom
        newdenom = self.denom * other.denom
        common = gcd(newnum, newdenom)
        return Fraction(newnum // common, newdenom // common)

    def __sub__(self, other):
        newnum = self.num * other.denom - other.num * self.denom
        newdenom = self.denom * other.denom
        common = gcd(newnum, newdenom)
        return Fraction(newnum // common, newdenom // common)

    def __mul__(self, other):
        newnum = self.num * other.num
        newdenom = self.denom * other.denom
        common = gcd(newnum, newdenom)
        return Fraction(newnum // common, newdenom // common)


if __name__ == "__main__":

    f1 = Fraction(11, 6)
    f2 = Fraction(2, 9)
    print(f1 + f2)  # Ответ 37/18
    print(f1 - f2)  # Ответ 29/18
    print(f1 * f2)  # Ответ 11/27
или вам нужно помочь исключения написать при неверном вводе?
Здравствуйте, у меня не получается написать код, например сложение Fraction (3,5)+5, а так же вычетание и умножение.
 

regnor

Модератор
Команда форума
Модератор
Июл 7, 2020
2 625
469
83
я не понял вопроса, к сожалению...
вам нужно чтобы операции были между дробью и целым числом? и результат выводил дробью?
 

Kira777

Новичок
Пользователь
Ноя 21, 2020
6
0
1
я не понял вопроса, к сожалению...
вам нужно чтобы операции были между дробью и целым числом? и результат выводил дробью?
Да. Все верно. Я пробовала несколько вариантов, которые прикрепила ниже. Но так как я только начинаю изучать питон, я не могу понять, как код написать.
 

Kira777

Новичок
Пользователь
Ноя 21, 2020
6
0
1
Да. Все верно. Я пробовала несколько вариантов, которые прикрепила ниже. Но так как я только начинаю изучать питон, я не могу понять, как код написать.
То есть мне в конце необходимо чтобы формулы умножения, сложения, вычетания производили расчет дроби с целым числом, ответ в виде дроби.
 

regnor

Модератор
Команда форума
Модератор
Июл 7, 2020
2 625
469
83
То есть мне в конце необходимо чтобы формулы умножения, сложения, вычетания производили расчет дроби с целым числом, ответ в виде дроби.
Python:
def gcd(num, denom):
    while num % denom != 0:
        num, denom = denom, num % denom
    return denom


class Fraction:

    def __init__(self, num, denom=1):
        self.num = num
        self.denom = denom

    def __str__(self):
        return str(self.num) + '/' + str(self.denom)

    def __add__(self, other):
        if isinstance(self.num, int) and isinstance(self.denom, int) and isinstance(other.num, int) and isinstance(
                other.denom, int):
            newnum = self.num * other.denom + other.num * self.denom
            newdenom = self.denom * other.denom
            common = gcd(newnum, newdenom)
            return Fraction(newnum // common, newdenom // common)
        else:
            raise TypeError('must be int')

    def __sub__(self, other):
        if isinstance(self.num, int) and isinstance(self.denom, int) and isinstance(other.num, int) and isinstance(
                other.denom, int):
            newnum = self.num * other.denom - other.num * self.denom
            newdenom = self.denom * other.denom
            common = gcd(newnum, newdenom)
            return Fraction(newnum // common, newdenom // common)
        else:
            raise TypeError('must be int')

    def __mul__(self, other):
        if isinstance(self.num, int) and isinstance(self.denom, int) and isinstance(other.num, int) and isinstance(
                other.denom, int):
            newnum = self.num * other.num
            newdenom = self.denom * other.denom
            common = gcd(newnum, newdenom)
            return Fraction(newnum // common, newdenom // common)
        else:
            raise TypeError('must be int')


if __name__ == "__main__":
    f1 = Fraction(11, 6)
    f2 = Fraction(2, 9)
    print(f1 + f2)  # Ответ 37/18
    print(f1 - f2)  # Ответ 29/18
    print(f1 * f2)  # Ответ 11/27

    f1 = Fraction(11, 6)
    f2 = Fraction(2)
    print(f1 + f2)  # Ответ 23/6
    print(f1 - f2)  # Ответ -1/6
    print(f1 * f2)  # Ответ 11/3

    f1 = Fraction(11)
    f2 = Fraction(2, 9)
    print(f1 + f2)  # Ответ 101/9
    print(f1 - f2)  # Ответ 97/9
    print(f1 * f2)  # Ответ 22/9

    f1 = Fraction('11', 6)
    f2 = Fraction(2, 9)
    print(f1 + f2)  # TypeError('must be int')

    f1 = Fraction(11, 6)
    f2 = Fraction(2.2, 9)
    print(f1 + f2)  # TypeError('must be int')
 

Kira777

Новичок
Пользователь
Ноя 21, 2020
6
0
1
Python:
def gcd(num, denom):
    while num % denom != 0:
        num, denom = denom, num % denom
    return denom


class Fraction:

    def __init__(self, num, denom=1):
        self.num = num
        self.denom = denom

    def __str__(self):
        return str(self.num) + '/' + str(self.denom)

    def __add__(self, other):
        if isinstance(self.num, int) and isinstance(self.denom, int) and isinstance(other.num, int) and isinstance(
                other.denom, int):
            newnum = self.num * other.denom + other.num * self.denom
            newdenom = self.denom * other.denom
            common = gcd(newnum, newdenom)
            return Fraction(newnum // common, newdenom // common)
        else:
            raise TypeError('must be int')

    def __sub__(self, other):
        if isinstance(self.num, int) and isinstance(self.denom, int) and isinstance(other.num, int) and isinstance(
                other.denom, int):
            newnum = self.num * other.denom - other.num * self.denom
            newdenom = self.denom * other.denom
            common = gcd(newnum, newdenom)
            return Fraction(newnum // common, newdenom // common)
        else:
            raise TypeError('must be int')

    def __mul__(self, other):
        if isinstance(self.num, int) and isinstance(self.denom, int) and isinstance(other.num, int) and isinstance(
                other.denom, int):
            newnum = self.num * other.num
            newdenom = self.denom * other.denom
            common = gcd(newnum, newdenom)
            return Fraction(newnum // common, newdenom // common)
        else:
            raise TypeError('must be int')


if __name__ == "__main__":
    f1 = Fraction(11, 6)
    f2 = Fraction(2, 9)
    print(f1 + f2)  # Ответ 37/18
    print(f1 - f2)  # Ответ 29/18
    print(f1 * f2)  # Ответ 11/27

    f1 = Fraction(11, 6)
    f2 = Fraction(2)
    print(f1 + f2)  # Ответ 23/6
    print(f1 - f2)  # Ответ -1/6
    print(f1 * f2)  # Ответ 11/3

    f1 = Fraction(11)
    f2 = Fraction(2, 9)
    print(f1 + f2)  # Ответ 101/9
    print(f1 - f2)  # Ответ 97/9
    print(f1 * f2)  # Ответ 22/9

    f1 = Fraction('11', 6)
    f2 = Fraction(2, 9)
    print(f1 + f2)  # TypeError('must be int')

    f1 = Fraction(11, 6)
    f2 = Fraction(2.2, 9)
    print(f1 + f2)  # TypeError('must be int')



Спасибо!!!
 

Форум IT Специалистов