Skip to main content

infix to postfix conversion and postfix evaluation

definition:

infix: an arithmetic expression is called infix, when it has the operators between the operands.
example: a+b is a infix expression.
postfix: When the operators appear after the operands, then it is called postfix. postfix is actually meant for machines. an example of postfix is: ab+
prefix: when the operators appear before the operands, it is called prefix. prefix is also a machine oriented expression. an example of prefix is: +ab

It is a very classic task to transform infix to postfix and postfix evaluation. We will write functions for both of them and also we will use the driver program to show whether it works or not. 

Infix to postfix conversion:

This can be done using stacks. Here is a brief of the algorithm:
 We read one character at a time from the infix expression. 
If this is a operand then we send it to the output string. The output string is supposed to be the postfix expression at the end. 
If it is an operator, we store it to a stack using the following rules:
(1) if the stack is empty, just store the operator in it.
(2) it the stack contains operators, check the precedence of the top operator. If the top-most operator has more precedence, it gets popped and the the new operator gets stored after that. The popped operator is stored in the output string.
     Otherwise, the new operator gets stored without any pop.
(3) when one encounters "(" one stores it. But on encountering ")", one pops operators and stores them in the output string until one finds "(" in the stack. When one finds the "(", its just popped and is not stored. 

using these rules, one continues to create the output string. Once one has completed parsing the infix expression, he/she pops all the values from the stack and stores them in the output string.
This final output string will be the required postfix expression. 

(1) the precedence function: This is the easiest part of this program. Here is the code for a precedence function below.
int precedence(char c)
{
if(c=="-")
{return 0;}
if(c=="+")
{return 1;}
if(c=="*")
{return 2;}
if(c=="/")
{return 3;}
if(c=="^")
{return 4;}
if(c=="(" || c==")")
{return 5;}
}
(2) postfix converter function:
char *postfix_converter(char *string,int length)
{ char s[100]="\0"; int i; stack operators;
for(i=0;i<length;i++)
{
char c;
c=string[i];
if(c==plus || c==subtract || c==multi || c==divi || c==power || c==left)
{
  if(top==NULL)
  {
   push(c);
  }
  else
  {
   if(precedence(c)>precedence(peek()) || peek()==left)
   {
   push(c);
   }
   else
   {
   char r[2]="\0";
       r[0]=pop();
       strcat(s,r);
       push(c);
   }

  }
}
else
{
if(c==right)
{
 while(peek()!=left)
 {
    char r[2]="\0";
       r[0]=pop();
       strcat(s,r);
 }
 pop();
}
else
{
    char r[2]="\0";
       r[0]=c;
       strcat(s,r);
    //  printf("%s\n",s);
   //  char j=peek();
   //  printf("%c",j);
  
}
}
if(i==(length-1))
{// printf("%d",count);
  while(count>0)
  {
    char r[2]="\0";
       r[0]=pop();
       strcat(s,r);
 //      printf("lool");
  }
}
  
// printf("%d\n",count);
// printf("%s\n",s);
   }

//printf("%d\n",pop());
   printf("%s",s);
}

(3) Now at last, if you want the readymade program, here it is:

The complete program is the following:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE  100 
int count=0;     
typedef struct node{
 char value;
 struct stack *next;
 struct stack *prev;
}stack;

stack *bottom=NULL;
stack *top=NULL;

stack *createnode(char a)
{
 stack *newstack;
 newstack=(stack*)calloc(1,sizeof(stack));
 newstack->value=a;
 newstack->prev=NULL;
 newstack->next=NULL;
 return newstack;
}

int isempty()
   {
       if(count==0)
       {return 1;}
       else
       {return 0;}
    }

int isfull()
    {
     if(count==SIZE)
     {return 1;}
     else
     {return 0;}
    }

void push(char a)
{   if(isfull()==1)
   {
    printf("overflow condition: stack full");
   }
 else             
   {count+=1;     
 stack *newstack = createnode(a);
 if(bottom==NULL) 
 {
 bottom=newstack;
 top=bottom;
 }
 else             
 {
  top->next=newstack;
  newstack->prev=top;
  top=newstack;
 }
   }
}
char peek()       
{
    return top->value;
}
char pop()     
    {   if(isempty()==1)       
        {
         printf("underflow condition:empty stack");
        }
        else
        {if(count==1)           
        {   char c;
         c=top->value;
         top=NULL;
         bottom=NULL;
         count=count-1;
         return c;
       
        }
        else                         
     {char c;
     c=top->value;
  top=top->prev;
  top->next=NULL;
  count=count-1;
  return c;

     }
       }
    }
    char plus=43;
    char multi=42;
    char divi=47;
    char power=94;
    char left=40;
    char right=41;
    char subtract=45;
int precedence(char c)
{  int precide=0;
if(c==subtract)
{precide+=0;}
if(c==plus)
{precide+=1;}
if(c==multi)
{precide+=2;}
if(c==divi)
{precide+=3;}
if(c==power)
{precide+=4;}
if(c==left || c==right)
{precide+=5;}
return precide;
precide=0;
}

char *postfix_converter(char *string,int length)
{ char s[100]="\0"; int i; stack operators;
for(i=0;i<length;i++)

char c;
c=string[i];
if(c==plus || c==subtract || c==multi || c==divi || c==power || c==left)
{
  if(top==NULL)
  {
  push(c);
  }
  else
  {
  if(precedence(c)>precedence(peek()) || peek()==left)
  {
  push(c);
  }
  else
  {
  char r[2]="\0";
      r[0]=pop();
      strcat(s,r);
      push(c);
  }

  }
}
else
{
if(c==right)
{
while(peek()!=left)
{
    char r[2]="\0";
      r[0]=pop();
      strcat(s,r);
}
pop();
}
else
{
    char r[2]="\0";
      r[0]=c;
      strcat(s,r);
  //  printf("%s\n",s);
  //  char j=peek();
  //  printf("%c",j);
 
}
}
if(i==(length-1))
{// printf("%d",count);
  while(count>0)
  {
  char r[2]="\0";
      r[0]=pop();
      strcat(s,r);
//     printf("lool");
  }
}
 
// printf("%d\n",count);
// printf("%s\n",s);
  }

//printf("%d\n",pop());
   printf("%s",s);
}

// driver code , the main function

int main(void)
{   char inversion[200];
printf("give the infix expression\n");
scanf("%s",&inversion);
int longer=strlen(inversion);
postfix_converter(inversion,longer);

return 0;
}
input: (2+3)^3-4+9
output:
Success #stdin #stdout 0s 9432KB
give the infix expression
23+3^49+-
input: (2+3)^3
output:
Success #stdin #stdout 0s 9432KB
give the infix expression
23+3^
input:(3/3)^3+3-3
output:
Success #stdin #stdout 0s 9432KB
give the infix expression
33/3^3+3-

For more details, visit here https://www.geeksforgeeks.org/stack-set-2-infix-to-postfix/

(4) postfix evaluation program:
For evaluation of postfix expression, the algorithm is easy:
(1) parse through the expression character by character.
(2) if a character is operand then push it to stack.
      else if it is an operator, pop two operands from the stack and then perform the operation as
    new_item=popped_2 operator popped_1
      push this new_item back to stack.
(3) at the end of the loop of step 2, pop the stack once as you must only have the result left in the stack. print it. You are done. voila!!

Here is the function named as postfix_evaluation!

(5) postfix evaluation function:
void *postfix_evaluation(char *string,int length)
{  int i; stack operators;
 for(i=0;i<length;i++)
 {
  char c;
  c=string[i];
  if(c==plus || c==subtract || c==multi || c==divi || c==power)
  {
        int a =pop();
        int b=pop();
        if(c==plus)
        {
                int result=b+a;
                push(result);
        }
        if(c==subtract)
        {
                int result=b-a;
                push(result);
        }
        if(c==multi)
        {
                int result=b*a;
                push(result);
        }
        if(c==divi)
        {
                int result=b/a;
                push(result);
        }
        if(c==power)
        {
                int result=pow(b,a);
                push(result);
        }
        }
        else
        {     int k=c-'0';
              push(k);
          //    printf("%d",k);
        }
 }
  int d=pop();
  printf("%d",d);
}

(6) Hey, if you are still reading this post, you may need the ready-made function for postfix evaluation. Here it is for you:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define SIZE  100
int count=0;
typedef struct node{
 int value;
 struct stack *next;
 struct stack *prev;
}stack;

stack *bottom=NULL;
stack *top=NULL;

stack *createnode(int a)
{
 stack *newstack;
 newstack=(stack*)calloc(1,sizeof(stack));
 newstack->value=a;
 newstack->prev=NULL;
 newstack->next=NULL;
 return newstack;
}

int isempty()
   {
       if(count==0)
       {return 1;}
       else
       {return 0;}
    }

int isfull()
    {
     if(count==SIZE)
     {return 1;}
     else
     {return 0;}
    }

void push(int a)
{   if(isfull()==1)
   {
    printf("overflow condition: stack full");
   }
 else
   {count+=1;
 stack *newstack = createnode(a);
 if(bottom==NULL)
 {
 bottom=newstack;
 top=bottom;
 }
 else
 {
  top->next=newstack;
  newstack->prev=top;
  top=newstack;
 }
   }
}
char peek()
{
    return top->value;
}
char pop()
    {   if(isempty()==1)
        {
         printf("underflow condition:empty stack");
        }
        else
        {if(count==1)
        {   int c;
         c=top->value;
         top=NULL;
         bottom=NULL;
         count=count-1;
         return c;

        }
        else
     {int c;
     c=top->value;
  top=top->prev;
  top->next=NULL;
  count=count-1;
  return c;

     }
       }
    }
    char plus=43;
    char multi=42;
    char divi=47;
    char power=94;
    char left=40;
    char right=41;
    char subtract=45;
void *postfix_evaluation(char *string,int length)
{  int i; stack operators;
 for(i=0;i<length;i++)
 {
  char c;
  c=string[i];
  if(c==plus || c==subtract || c==multi || c==divi || c==power)
  {
        int a =pop();
        int b=pop();
        if(c==plus)
        {
                int result=b+a;
                push(result);
     
        }
        if(c==subtract)
        {
                int result=b-a;
                push(result);
        }
        if(c==multi)
        {
                int result=b*a;
                push(result);
        }
        if(c==divi)
        {
                int result=b/a;
                push(result);
        }
        if(c==power)
        {
                int result=pow(b,a);
                push(result);
        }
        }
        else
        {     int k=c-'0';
              push(k);
 
        }

  }
  int d=pop();
  printf("%d",d);
}

// driver code , the main function

int main(void)
{   char inversion[200];
 printf("give the postfix expression\n");
 scanf("%s",&inversion);
 int longer=strlen(inversion);
 postfix_evaluation(inversion,longer);

 return 0;
}
Example:
input: 23+3^
Success #stdin #stdout 0s 9424KB
give the postfix expression
125

Caution/disclaimer: This post only depicts a idea for the programs, and are not fit for all the marginal cases like values above 10^6, inputs other than expected formats and some other things. So please take just the idea from the codes and try to correct this more. You can mail me better versions too. 

Comments

Popular posts from this blog

Mastering SQL for Data Science: Top SQL Interview Questions by Experience Level

Introduction: SQL (Structured Query Language) is a cornerstone of data manipulation and querying in data science. SQL technical rounds are designed to assess a candidate’s ability to work with databases, retrieve, and manipulate data efficiently. This guide provides a comprehensive list of SQL interview questions segmented by experience level—beginner, intermediate, and experienced. For each level, you'll find key questions designed to evaluate the candidate’s proficiency in SQL and their ability to solve data-related problems. The difficulty increases as the experience level rises, and the final section will guide you on how to prepare effectively for these rounds. Beginner (0-2 Years of Experience) At this stage, candidates are expected to know the basics of SQL, common commands, and elementary data manipulation. What is SQL? Explain its importance in data science. Hint: Think about querying, relational databases, and data manipulation. What is the difference between WHERE

What is Bort?

 Introduction: Bort, is the new and more optimized version of BERT; which came out this october from amazon science. I came to know about it today while parsing amazon science's news on facebook about bort. So Bort is the newest addition to the long list of great LM models with extra-ordinary achievements.  Why is Bort important? Bort, is a model of 5.5% effective and 16% total size of the original BERT model; and is 20x faster than BERT, while being able to surpass the BERT model in 20 out of 23 tasks; to quote the abstract of the paper,  ' it obtains performance improvements of between 0 . 3% and 31%, absolute, with respect to BERT-large, on multiple public natural language understanding (NLU) benchmarks. ' So what made this achievement possible? The main idea behind creation of Bort is to go beyond the shallow depth of weight pruning, connection deletion or merely factoring the NN into different matrix factorizations and thus distilling it. While methods like knowle

Spacy errors and their solutions

 Introduction: There are a bunch of errors in spacy, which never makes sense until you get to the depth of it. In this post, we will analyze the attribute error E046 and why it occurs. (1) AttributeError: [E046] Can't retrieve unregistered extension attribute 'tag_name'. Did you forget to call the set_extension method? Let's first understand what the error means on superficial level. There is a tag_name extension in your code. i.e. from a doc object, probably you are calling doc._.tag_name. But spacy suggests to you that probably you forgot to call the set_extension method. So what to do from here? The problem in hand is that your extension is not created where it should have been created. Now in general this means that your pipeline is incorrect at some level.  So how should you solve it? Look into the pipeline of your spacy language object. Chances are that the pipeline component which creates the extension is not included in the pipeline. To check the pipe eleme