eval()
will definitely do the trick, but there is a school of thought that using eval()
is best avoided, so I will present an alternative using regular expressions.
Trying to use Python functions like split()
becomes tricky quite quickly as you can only split on a single character. Regular expressions would allow you to find the components of the equation more easily. For example this regular expression:
r'(\d+\.?\d*)([\-+/*])(\d+\.?\d*)'
specifically looks for 3 groups (within parentheses):
(\d+\.?\d*)
looks for a number, with or without decimal place
([\-+/*])
looks for a mathematical symbol
so, together, they will find both numbers and any mathematical symbol you specify.
matches[0]
contains the combination of all of the match groups, and matches[1], [2], [3] contain the first value, the operator, and the second value.
This enables you to perform the calculations without using eval()
import re
with open('./izrazi.txt', 'r+') as f:
lst = f.readlines()
with open('./izrazi2.txt', 'w+') as f:
for line in lst:
matches = re.match(r'(\d+\.?\d*)([\-+/*])(\d+\.?\d*)', line)
if matches:
if matches[2] == "-":
calc = float(matches[1]) - float(matches[3])
if matches[2] == "+":
calc = float(matches[1]) + float(matches[3])
if matches[2] == "/":
calc = float(matches[1]) / float(matches[3])
if matches[2] == "*":
calc = float(matches[1]) * float(matches[3])
f.write(f"{matches[0]}={calc:g}\n")
With an input of:
4-2
9-3
3.142/22
34.2*91.44
9-3
3.142/22
34.2*91.4
This does give the desired output of:
4-2=2
9-3=6
3.142/22=0.142818
34.2*91.44=3127.25
9-3=6
3.142/22=0.142818
34.2*91.4=3125.88
As an aside, you can't use a set
for operations such as -
and /
as they are not commutative. A set
object is an unordered collection of distinct, hashable objects, so it simply not appropriate for use with mathematical terms.