2

I need an algorithm for evaluating postfix expression using recursion. In this postfix expression an operand can be of more than one digit. A space is used to distinguish between two operands. So an expression '45 68 +' is valid.

I thought of evaluating it in reverse direction but I think that should not be correct.

Can someone help me with just the algorithm.

Thanks in advance.

Keen Sage
  • 1,899
  • 5
  • 26
  • 44
  • 2
    The algorithm wasn't given to you in class? Wikipedia to the rescue: http://en.wikipedia.org/wiki/Reverse_Polish_notation#Postfix_algorithm – Ray Toal Nov 10 '11 at 02:54
  • 1
    These are simple algorithms that are easily available online. Also, if the algo wasn't given to you in class, it might be for a reason. Your teacher might be wanting you to figure it out for ourself. Honestly, try figuring it out yourself, write code, and debug it before venturing out and looking for one. – darnir Nov 10 '11 at 03:02
  • @RayToal Thanks for the help but I wanted to do it using recursion. The implementation given in the wiki is using stack. – Keen Sage Nov 10 '11 at 03:03
  • @darnir I was able to write the prefix version of it. But I am not able to think about the base case for this algorithm. – Keen Sage Nov 10 '11 at 03:05
  • Oh! I see. You were supposed to come up with the recursive algorithm. My bad. That is a good homework problem, asking you to map the stack operation to recursive calls. And I see what you mean: doing it recursively for a prefix version is easier. Do you have only binary operators here? – Ray Toal Nov 10 '11 at 03:28
  • 1
    @RayToal Yes, only binary operator – Keen Sage Nov 10 '11 at 04:05
  • Okay, as a recursive call it would really be a good exercise. The postfix is undoubtedly a little tricky in this case. – darnir Nov 10 '11 at 08:41
  • Why? Postfix is a linear notation. No recursion required. – user207421 Feb 27 '17 at 00:37

3 Answers3

2

Doesn't strike me as a recursive-friendly problem. But I'm sure it could be done that way.

Two approaches occur to me:

Option #1: Make functional recursion calls and returns match the stack push and pop operations described on the Wiki.

Down side to this approach is that you'll quickly find that the returned data from the function can be fairly complex. It'll probably be an operator. Maybe with an optional operand (IE: number). You'll be returning structures/objects that maybe should have operations (methods) on them.

Option #2: Each recursive call processes the next character of the input stream.

I think this approach would pass in as parameters the stack and maybe an "accumulator" for the current number -- to accumulate digits into a number before pushing it on the stack. There would be one massive tail recursion numeric result returned.

This approach is really just rewriting a loop as recursion.

Either way, figuring it out yourself should be challenging and educational!

Jeff Grigg
  • 1,004
  • 8
  • 7
1

Following is a sort of pseudo code which will work for postfix expressions with +/- . I think you can further extend the idea. If you still face difficulty then mail me to 2shanks.p@gmail.com as I am not regular on this site.

void recursivePostfix(char* expr)  
{  
if(!expr)   return;  

bool flag=true;
static double result=0;
double v1=result, v2=0, dec=0;
char oper='0';
int i=0, state=1;

do
{
    if('0' != oper)
    {
        switch(oper)
        {
            case '+': result=v1+v2; break;
            case '-': result=v1-v2; break;
            case '*': result=v1*v2; break;
            case '/': result=v1/v2; break;
        }
        oper = '0';
        v1 = result;
        v2 = 0;
        recursivePostfix(expr+i);
    }

    if(SPACE_CHAR == *(expr+i) && state++)
        continue;

    switch(state)
    {
        case 1:
            v1 = v1*10 + (expr[i]-'0'); break;
        case 2:
            v2 = v2*10 + (expr[i]-'0'); break;
        case 3:
            oper = *(expr+i);
    }  
}while(0 != *(expr+i++));
cout << result;

}
askquestion
  • 171
  • 1
  • 14
paper.plane
  • 1,201
  • 10
  • 17
0

I just code this for an interview, so here is my solution using Python:

def recursive_postfix(s):
    s = s.split(' ')
    if len(s) == 1:
        return s[0]
    res = None
    for i in range(len(s)):
        if s[i] in ['+', '-', '*', '/']:
            res = eval(f'{s[i-2]}{s[i]}{s[i-1]}')
            break
    s = s[0:i-2] + [str(res)] + s[i+1:]
    return recursive_postfix(' '.join(s))

assert recursive_postfix('2 2 + 1 *') == '4' # (2 + 2) * 1
assert recursive_postfix('3 4 2 + * 5 *') == '90' # 3 * (4 + 2) * 5
assert recursive_postfix('7 2 2 * -') == '3' # 7 - (2 * 2)
juanifioren
  • 633
  • 5
  • 18