How to run another program by python?

7

I'm trying to make a calculation engine in Python . For example, I have a program named engine.py , which takes an equation and returns the roots. I wanted to write another program named interface.py , which would just take the equation and tell the engine to calculate and take the value returned. Can you do that?

engine.py

x = str(input())  
x = x.replace("-","+-")  
Eq = list(x.split("+"))  
b = 0  
c = 0  
if "" in Eq: Eq.remove("")  
for i in range(0,len(Eq)):
    if (Eq[i] == "x²"):    
        a = 1  
    elif (Eq[i] == "-x²"):  
        a = -1  
    elif "x²" in Eq[i]:  
        aux = Eq[i]  
        a = int(aux.replace("x²",""))  
    elif (Eq[i] == "x"):  
        b = 1  
    elif (Eq[i] == "-x"):  
        b = -1  
    elif "x" in Eq[i]:
        aux = Eq[i]
        b = int(aux.replace("x",""))
    else:
        c = int(Eq[i])
delta = (b * b) - 4 * a * c 
print("Delta:",delta)
if delta<0:
    print('Essa equacao nao tem raiz real')
elif delta==0:
    x1 = (-b)/(2*a)
    print('Raiz:',x1)
else:
    from math import sqrt
    x1 = (-b+sqrt(delta))/(2*a)
    x2 = (-b-sqrt(delta))/(2*a)
    print('Raizes:')
    print("x':",x1)
    print("x'':",x2)  

Interface.py

x = input()  
y = manda_para_engine(x)
print(x)

something like this

    
asked by anonymous 30.10.2015 / 14:51

1 answer

8

Yes.

Set your engine.py file more or less as follows:

def calcular_equacao(a, b, c):
    delta = (b * b) - 4 * a * c 
    print("Delta:", delta)
    if delta<0:
        print('Essa equacao nao tem raiz real')
        return None
    elif delta==0:
        x1 = (-b)/(2*a)
        return x1
    else:
        from math import sqrt
        x1 = (-b+sqrt(delta))/(2*a)
        x2 = (-b-sqrt(delta))/(2*a)
        return (x1, x2)  

In the file interface.py , import engine.py as follows:

import engine

To call the engine function:

a = engine.calcular_equacao(1, 2, 3)

engine.py and interface.py must be in the same directory. By doing a% w / o% w / o%, the result should be the tuple with the roots, or an integer, or% w / o% if it has no real roots.

Notice that I did not address the expression handling logic for the function. The function is simply called with print , a and None already filled.

    
30.10.2015 / 14:57