Click here to Skip to main content
15,881,938 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Input in a text file:
a=2*8
b=3*9
c=4*8
d=5*9
e=a+b
f=c+d
g=0*6
h=1*7
i=e+g
j=f+h
output=i+j

Desired Output :
output=(((2*8)+(3*9))*(0*6))+(((4*8)+(5*9))*(1*7))

What I have tried:

Python
#Logic from internet.
D = dict()
output = None
with open('var.txt') as v:
    for line in v:
        k, v = line.strip().split('=')
        if k == 'output':
            output = v
        else:
            D[k] = v
    for k, v in D.items():
        output = output.replace(k, f'({v})')
    print(output)
Posted
Updated 14-Nov-21 2:03am
v2
Comments
Richard MacCutchan 14-Nov-21 7:44am    
You need to check each entry as you read them and replace the entry with the result of the expression if it contains the keys of existing entries. Thus when you read item e you need to replace "a+b" with the actual values you have already saved earlier.
Patrice T 14-Nov-21 8:02am    
What is your question ?
A v Nov2021 14-Nov-21 8:39am    
The current script throws a output as (e+g)+(f+h) but i need all elements of e, g, f h too like the desired output i have mentioned. How to modify this script?
Richard MacCutchan 14-Nov-21 8:51am    
Se my suggestion above.
A v Nov2021 14-Nov-21 8:59am    
I understand the logic, but I don't know how to implement it. I am a naive programmer. The above code snipet is also from the internet.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900