Basicly, what I need for the program to do is to act a as simple fraction calculator (for addition, subtraction, multiplication and division) for the a single line of input, for example:
-input: 1/7 + 3/5
-output: 26/35
My initial code:
import sys
def euclid(numA, numB):
while numB != 0:
numRem = numA % numB
numA = numB
numB = numRem
return numA
for wejscie in sys.stdin:
wyjscie = wejscie.split(' ')
a, b = [int(x) for x in wyjscie[0].split("/")]
c, d = [int(x) for x in wyjscie[2].split("/")]
if wyjscie[1] == '+':
licz = a * d + b * c
mian= b * d
nwd = euclid(licz, mian)
konA = licz/nwd
konB = mian/nwd
wynik = str(konA) + '/' + str(konB)
print(wynik)
elif wyjscie[1] == '-':
licz= a * d - b * c
mian= b * d
nwd = euclid(licz, mian)
konA = licz/nwd
konB = mian/nwd
wynik = str(konA) + '/' + str(konB)
print(wynik)
elif wyjscie[1] == '*':
licz= a * c
mian= b * d
nwd = euclid(licz, mian)
konA = licz/nwd
konB = mian/nwd
wynik = str(konA) + '/' + str(konB)
print(wynik)
else:
licz= a * d
mian= b * c
nwd = euclid(licz, mian)
konA = licz/nwd
konB = mian/nwd
wynik = str(konA) + '/' + str(konB)
print(wynik)
Which I reduced to:
import sys
def euclid(numA, numB):
while numB != 0:
numRem = numA % numB
numA = numB
numB = numRem
return numA
for wejscie in sys.stdin:
wyjscie = wejscie.split(' ')
a, b = [int(x) for x in wyjscie[0].split("/")]
c, d = [int(x) for x in wyjscie[2].split("/")]
if wyjscie[1] == '+':
print("/".join([str((a * d + b * c)/euclid(a * d + b * c, b * d)),str((b * d)/euclid(a * d + b * c, b * d))]))
elif wyjscie[1] == '-':
print("/".join([str((a * d - b * c)/euclid(a * d - b * c, b * d)),str((b * d)/euclid(a * d - b * c, b * d))]))
elif wyjscie[1] == '*':
print("/".join([str((a * c)/euclid(a * c, b * d)),str((b * d)/euclid(a * c, b * d))]))
else:
print("/".join([str((a * d)/euclid(a * d, b * c)),str((b * c)/euclid(a * d, b * c))]))
Any advice on how to improve this futher is welcome.
Edit: one more thing that I forgot to mention – the code can not make use of any libraries apart from sys.
I’d create a class containing
numeratoranddenominatorfields (both integers) and implementing__add__,__sub__,__mul__, and__div__methods. Then you can simply use ordinary math functions to combine the instances.It might be overkill for your purposes, but the code will be a lot cleaner.
In fact, the class-based approach is exactly how the
fractionsmodule is implemented. Normally I’d suggest examining the source code of the fractions module to see how it’s written, but since this is for homework I’m not sure that would be allowed. It might be worth checking out after the assignment is over, just to see how a full-blown fractional-number type is implemented.