Advanced · Classes · 193 of 264
Fractions
Write a Fraction class that adds two fractions and keeps the result in lowest terms (with a positive denominator). Do not use the fractions module.
Input: two fractions like 1/2 and 1/3, one per line. Output: their sum, like 5/6 (a whole number is written like 2/1).
Examples
Input
1/2 1/3
Output
5/6
Input
1/4 3/4
Output
1/1
Input
2/3 -1/6
Output
1/2
One more test checks other inputs when you press Check.
Stuck? The idea behind classes
A class describes a kind of object: its data (attributes, set in __init__) and what it can do (methods). Each object made from it has its own data.
self is the object a method is called on; __str__ says how the object prints.
class Account:
def __init__(self, owner):
self.owner = owner
self.balance = 0
def pay_in(self, amount):
self.balance += amount
acc = Account("Ann")
acc.pay_in(5)
print(acc.balance)Watch for: Every method's first parameter is self, and attributes are reached through it: self.balance, not balance.