Issue
i was given a task in school to get a file basic math exercises (+,-,*,/) and i was told i need to solve these with python and write the answers in new file , i did finish my code and its working but i dont think my code is as efficient as the teacher expects . i assume that there are spaces between first num , operation and second num but it is not Necessarily true. Example for question. txt - 1234 + 12121 12 * 33 Example for answer. txt - 1234 + 12121 = 13,355 12 * 33 = 396
~with open(r"C:\Users\username\Desktop\que.txt", 'r') as source:
index = 0
t = source.readlines()
while index < len(t):
frs = ""
sign = ""
sec = ""
for chr in t[index]:
if chr == " ":
break
frs += chr
now = False
for chr in t[index]:
if chr == " ":
now = True
elif now :
sign = chr
break
count = 0
for chr in t[index]:
if chr == " ":
count += 1
elif count == 2:
sec += chr
frs = int(frs)
sec = int(sec)
with open(r"C:\Users\username\Desktop\answer.txt", 'a') as des:
des.write(f"{frs} {sign} {sec} = {frs+sec}\n")
index+=1
Solution
If there is no need for security you could use exec to get a much shorter and easier solution.
with open(r"C:\Users\שליו\Desktop\que.txt", 'r') as source:
with open(r"C:\Users\שליו\Desktop\answer.txt", 'a') as des:
for equation in source.readlines():
try:
exec("result = " + equation)
des.write(f"{equation.replace("\n","")} = {result}\n")
print(f"calculated result {result}")
except Exception as e:
print(f"failed at {equation.replace("\n",""} because of {e}")
EDIT:
Version that OP eventually used from comment:
def my_exec(code):
exec('global i; i = %s' % code)
global i
return i
def calc():
with open(r"C:\Users\שליו\Desktop\que.txt", 'r') as source:
with open(r"C:\Users\שליו\Desktop\answer.txt", 'a') as des:
for equation in source.readlines():
result = my_exec(equation)
a = equation.replace("\n","")
des.write(f"{a} = {result}\n")
Answered By - wuerfelfreak
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.