Reputation: 53
I have two strings, the one is "K <- L * 5"
and the other is "K <- 5 * L"
Is there a way to say in Python 3 to compare these and return True
? ( because they are the same but in different order )
I'm looking for a solution to compare only the 2nd part, after <-
Specifically I'd like the second part to give the same result.
E.g.
"5 % 3"
and "3 % 5"
are not the same"L * 5"
and "5 * L"
are the sameMaybe a dictionary could help, but I'm not familiar with Python.
Upvotes: 0
Views: 111
Reputation: 1838
As explained in the comments, the check of semantics in this is an obstacle. You could probably build your own (or find someone else's) grammatical parser for these kind of mathematical expressions.
A workaround would be to use the mathematical capability that is already built in and converting the expression to valid expressions. I chose here to convert all numbers and letters to their Ascii equivalent. You can choose yourself how picky you want to be in the conversion (lower all caps, use only certain alphabets etc...) but here is a working example.
def main():
opt1_raw = "K <- N * 5"
opt2_raw = "K <- 5 * N"
opt1 = opt1_raw.split("<-")[1]
opt2 = opt2_raw.split("<-")[1]
ascii_exp = ''.join([str(ord(char)) if char.isdigit() or char.isalpha() else char for char in opt1])
s = eval(ascii_exp)
ascii_exp = ''.join([str(ord(char)) if char.isdigit() or char.isalpha() else char for char in opt2])
p = eval(ascii_exp)
print(opt1 +" and " + opt2 +": " + str(s==p))
main()
In the loop, I am converting all digits
and alphas
(letters) to their ascii equivalent, letting operators such as '*
' and '/
' be where they are. Then I use eval()
to let python evaluate the expression. The result of an evaluation can then look like this: 76*53
instead of "L*5"
Then I just compare the result. I'm sure you can find a more elegant way to incorporate this but its an example of evaluating such abstract expressions.
The output:
L*5 and 5*L: True
L*5 and 5 % 3: False
5 % 3 and 3 % 5: False
L*5 and 5 % 3: False
Upvotes: 1