how to make my python code more effective

Question:

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:UsersusernameDesktopque.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:UsersusernameDesktopanswer.txt", 'a') as des:
            des.write(f"{frs} {sign} {sec} = {frs+sec}n")
            index+=1  
Asked By: one_hell_of_a_guy

||

Answers:

This is how I would have approached

with open("input.txt", 'r') as source:
    for equation in source.readlines():
        frs = ""
        sign = ""
        sec = ""
        for index, char in enumerate(equation):
            if char == '+' or char == '-' or char =='*' or char =='/':
                sign = char
                frs = int(equation[:index])
                sec = int(equation[index + 1:])
                break
        # when we reach here, we would have found our operands and the operator
        ans = ""
        if char == '+':
            ans = frs + sec
        elif char == '-':
            ans = frs - sec
        elif char == '*':
            ans = frs * sec
        elif char == '/':
            ans = frs / sec
        else:
            print("Unsupported Character:", char)
            exit()
        with open("output.txt", 'a') as des:
            des.write(f"{frs} {sign} {sec} = {ans}n")

Input.txt file is as follows:

1234 + 12121
12 * 33

Output.txt file looks like this:

1234 + 12121 = 13355
12 * 33 = 396
Answered By: ubaid shaikh

If there is no need for security you could use exec to get a much shorter and easier solution.

with open(r"C:UsersשליוDesktopque.txt", 'r') as source:
    with open(r"C:UsersשליוDesktopanswer.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שליוDesktopque.txt", 'r') as source: 
        with open(r"C:UsersשליוDesktopanswer.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
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.