Comparing rpn (postfix) expressions for equivalency


Comparing rpn (postfix) expressions for equivalency



How would one compare any two postfix notated expressions for equivalency?



In the simplest example, foo(a, b) returns True for


a = [3, 5, 'MUL']

b = [5, 3, 'MUL']



What would foo() look like in python? I imagine that one way is to evaluate both expressions and normalize them somehow. I expect that this is a well defined process but haven't found it yet.


foo()



Edit 1:



This was a poorly worded question. I will try with better/more examples, and appreciate your patience as I try and ask the question clearly and precisely.


expr1 = [a, b, 'MUL']

expr2 = [b, a, 'MUL']



OR


expr1 = [a, b, 1, 'ADD', 'MUL']

expr2 = [a, b, 'MUL', a, 'ADD']





Do you have a function that calculates the notation? or are you asking here for someone here to help you create a code for that too?
– Vincent Pakson
Jul 2 at 5:42





I have code to evaluate the postfix expression. Adding to original question if it is useful.
– Vishal
Jul 2 at 5:48





can you add more example ?
– Vikas Damodar
Jul 2 at 6:12






Evaluating an expression and determining equivalency based on the output of one set of possible parameters doesn't seem robust (and I have nothing to back that statement up). Adding more evaluations will add to the time it takes if I have a lot of such comparisons to do. Is there another way to think about this problem/solution too?
– Vishal
Jul 2 at 7:49




2 Answers
2



Here I have tried your problem with a solution, it works , if you have more choices you can add :


a = [3, 5, 'MUL']
b = [5, 3, 'MUL']


def postfix_calc(value, z):
return {
'MUL': lambda c: a[0]*a[1],
'ADD': lambda c: a[0]+a[1],
'SUB': lambda c: a[0]-a[1],
'DIV': lambda c: a[0]/a[1]
}.get(value)(z)


def foo(x, y):
val1 = postfix_calc(x[2], x)
val2 = postfix_calc(y[2], y)
if val1 == val2:
return True
else:
return False


print(foo(a,b))



Since you already have the postfix evaluation. you wcould have it like this then.


foo(a,b):
res_a = postfix(a)
res_b = postfix(b)
if res_a = res_b:
return True
return False



I think this is the simplest solution you're looking for?






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

How to add background colour in existing image using Swift?

What's the difference between DDS and SOME/IP?

Moria Casán