Python - Execute A String Code For Fractions
I've been working in some type of calculator for fractions using from fractions import * following the next logic: a = Fraction(1,4) b = Fraction(2,5) c = Fraction(3,4) print(a+b*
Solution 1:
I tried this and this is working (my input was in the form a/b + c/d):
from fractions import*
print ("your operation:")
op = input()
#print (op)
elements = op.split()
for el in elements:
if ('/'in el):
fraction = el.split('/')
numerator = fraction[0]
denominator = fraction[1]
a = Fraction(int(numerator),int(denominator))
print (numerator)
print (denominator)
print (a)
Solution 2:
You can use ast eval
import ast
defmyfunc():
localvars = {}
expr = 'x = 1/4 + 1/2'eval(compile(ast.parse(expr), '<input>', mode="exec"), localvars)
return localvars['x']
Note, in python 2 it will yield 0 as both 1/4
and 1/2
will result in 0, you need to do 1.0/4
in python 2. python3 will calculate it using double types so it will return 0.75 as you expect , ie python2 version:
import ast
defmyfunc():
localvars = {}
expr = 'x = 1.0/4 + 1.0/2'eval(compile(ast.parse(expr), '<input>', mode="exec"), localvars)
return localvars['x']
Solution 3:
You can do something like this:
from fractions import *
defreturnElement(element):
if'/'in element andlen(element) > 1:
fraction = element.split('/')
numerator = fraction[0]
denominator = fraction[1]
return'Fraction(' + numerator + ',' + denominator + ')'else:
return element
classmain():
for i inrange(0, 10):
print"\t\nWRITE YOUR OPERATION"
code = 'print('
s = raw_input()
elements = s.split()
for element in elements:
code = code + returnElement(element)
code = code + ')'print code
exec code
Post a Comment for "Python - Execute A String Code For Fractions"