I have text strings such as mathematical expressions (e.g. 11 + 50 * 10), and I need to calculate the resulting number doing the math from left to right discarding the fact that multiplication precedes addition. For 11 + 50 * 10:
If i connect this string to a num component I will get a result of 11+500 = 511.
What I need is that 11+50 is calculated first (=61), followed by the multiplication 61 * 10 = 610
Is this possible? The strings can be of various lengths with more operators than in this example (e.g. 11 + 50 * 10 * 26 + 38 + 9 * 56 * 26, which should give → 23 160 592).
You can calculate expressions from left to right in Python with this simple script:
tokens = []
temp = ''
for char in exp:
if char.isdigit():
temp += char
elif char in '+-*/':
if temp:
tokens.append(temp)
temp = ''
tokens.append(char)
if temp:
tokens.append(temp)
exp = tokens[0]
for i in range(1, len(tokens), 2):
exp = f"({exp}{tokens[i]}{tokens[i+1]})"
r = eval(exp)
Lason.gh (5.2 KB)
1 Like
Cool, thank you Mahdiyar!