How to count the number of method arguments when converting an infix expression to reverse polish

I have an expression as shown below. MIN (MAX (AVG (AVG (4,2), 2,3), SUM (1,2))) I applied the shunting yard algorithm to convert the infix to inverse notation. I add MAX, MIN, and AVG functions with two arguments. But suppose that if I want to implement variable arguments, then I need to know how many arguments each function had in an infix expression. Can someone tell me how I can change the shunting yard algorithm to turn it on. arguments of each function when converting infix to rpn?

+6
source share
3 answers

This is how I finally did it. When the token is an open bracket, I add it to the output queue. Then, when you convert or execute RPN output, and I come across a function call token, I pop the elements from the stack until I come across an open bracket, drop it and consider everything in between to be an argument to the function.

This is probably not a simple solution, but work like a charm :)

+2
source

So, if you have log max(1, 2, 3, 4, 5) , you will do:

 log => push sin to stack max => push max to stack ( => push ( to stack 1 => push 1 to stack , => pop top of stack to output => pop 1 to output 2 => push 2 to stack , => pop 2 to output ... => end result: 1 2 3 4 5 max log 

The problem is that you do not know how many arguments max belongs to and how many - log (the logarithm may or may not accept the base as an argument).

Using the wikipedia description, it should be possible to read each function argument separator (comma): if you have k function separators, then you have k + 1 arguments, so you can print 1 2 3 4 5 max_5 log above. Be careful to have different values ​​in case of nested functions:

 max(1, 2, log(3, 4), 5) => 1 2 3 4 log_2 5 max_4 --------- max has 4 arguments after evaluating log_2(3, 4) 

You have one account for the max token, and another for the log function. You need to keep track of the counter for the highest function token in your stack, but also for all the other function tokens in your stack, as you can eventually resume them.

+5
source

A slightly tidier solution is to make another stack. Press the current token position on this stack when it detects an open bracket. Then, when a closed bracket is found, pop out the first value and use the difference between the current token position to find the total number of arguments between the brackets. If the operator is a function, you can use this value or otherwise discard it.

0
source

Source: https://habr.com/ru/post/984442/


All Articles