convert strings to python

Asked

Viewed 107 times

-3

I am having doubts to resolve this exercise. First, follow example of txt file.

5/2  
500+20   
200-20  
20*10

I need to read this txt file and solve the equations in Python.
Follow the code I currently have.

arquivo = open("Calculadora lendo TXT.txt", 'r')  
for linha in arquivo:  
    linha = linha.strip()  
    print(linha)

In my beginner’s logic, I believe I need to convert string for INT and how to identify signs of operations.

2 answers

0

Cassio, if you split the line it will generate an array of three positions, in which to do the following operations:

1 - Take the 1st and 3rd term of the array and convert them to int(arr[position]) - Split
2 - With the second position of the array you can make an if with Elif and put in any operation you want. Sum, Subtraction and multiplication. - Link: Conditional

I believe that already helps to resolve this issue.

  • 2

    and how would he do the "split" without knowing the operator first? (hint - the correct thing is to make a reader (parser) that reads character to character and has logic to read a number of n digits, an operator, and another number, with optional spaces. - can be done with regular expressions, but character-by-character logic would be more didactic - and seems to be the goal of the exercise)

  • The intention of doing Spilt is to break into an array of three positions, to be able to use the vector to perform the operation, really with regular expression I could do, but what I wanted to point is a simpler and didactic way of solving.

-1

I would solve so:

with open('Calculadora lendo TXT.txt') as arquivo:
   for linha in arquivo:
       print(f'{linha}: {eval(linha)}')

Using "with" you do not worry about having to close the file after using it. The "for" line hasn’t changed a bit. I used string formatting to print. The first variable is indicating the account that will be held, put ":" and then use the "Eval" function that executes the account. Note that to work the accounts must use the Python standard, for example "**" to increase power. For the given example it works for everyone.

  • the use of Eval is a "short circuit" that invalidates the purpose of the exercise - although it works in this case.

  • My idea was to get solution in Python, not algorithm exercise solution. The problem then is algorithmic and should be with this tag. But I understood the point of view. Python has many shortcuts that really should not be used when the idea is to exercise algorithm.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.