Search code examples
pythonstringfractions

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*c)

OUTPUT

11/20

But I need to execute the statement from a string, just like 1/4 + 1/2 and for some reason always returns me 0 or 1:

from fractions import *

class main():
    for i in range(0, 10):
        print "\t\nWRITE YOUR OPERATION"
        code = 'print('
        s = raw_input()
        elements = s.split()

        for element in elements:
            print(element)

            if '/' in element:
                fraction = element.split('/')
                numerator = fraction[0]
                denominator = fraction[1]
                a = Fraction(int(numerator),int(denominator))
                code = code + str(a)
            else:
                code = code + str(element)                

        code = code + ')'        

        exec code

It's something I'm missing?

EDIT 1

I know what is wrong here

The string code is like this:

code = 'print(1/4+2/5*3/4)'

But what I really need is this (which I think is imposible to do):

code = 'print(Fraction(1,4)+Fraction(2,5)*Fraction(3,4))'

Or there is a way to do something like this...?


Solution

  • You can do something like this:

    from fractions import *
    
    def returnElement(element):
        if '/' in element and len(element) > 1:
            fraction = element.split('/')
            numerator = fraction[0]
            denominator = fraction[1]
            return 'Fraction(' + numerator + ',' + denominator + ')'        
        else:
            return element  
    
    class main():
        for i in range(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