DATA STRUCTURE WITH PYTHON                                          CODE: 20CS41P
LIFO Data Structure
    A stack is used to store data such that the last item inserted is the first item
      removed.
    It is used to implement a last-in first-out (LIFO) type protocol.
    The stack is a linear data structure in which new items are added, or existing
      items are removed from the same end, commonly referred to as the top of the
      stack.
    The opposite end is known as the base.
 Abstract View of Stack:
  Consider the example in Figure, which illustrates new values being added to the top
  of the stack and one value being removed from the top.
Figure : Abstract view of a stack: (a) pushing value 19; (b) pushing value 5;
(c)resulting stack after 19 and 5 are added; and (d) popping top value.
SEARCH EDUCATIONS                                                                       Page 1
DATA STRUCTURE WITH PYTHON                                        CODE: 20CS41P
The most common uses of a stack are:
Example #1: Reverse a String:
A Stack can be used to reverse the characters of a string. This can be
achieved by simply pushing one by one each character onto the Stack,
which later can be popped from the Stack one by one. Because of the last
in first out (LIFO) property of the Stack, the first character of the Stack is
on the bottom of the Stack and the last character of the String is on the
Top of the Stack and after performing the pop operation in the Stack, the
Stack returns the String in Reverse order.
     Example #2: Evaluation of Arithmetic Expressions:
     A stack is a very effective data structure for evaluating arithmetic
     expressions
           Mathematical expressions are rather easy for humans to evaluate.
           But the task is more difficult in a computer program.
           To simplify the evaluation of a mathematical expression in
           computer, it is converted into another form i.e postfix form, then
           postfix expression is evaluated in computer.
           Postfix Expressions can be evaluated using stack.
       Example: Postfix Expression, 7 4 -3 * 1 5 + / *
SEARCH EDUCATIONS                                                                Page 2
DATA STRUCTURE WITH PYTHON                                   CODE: 20CS41P
   Example #3: Message Box
                o Message box in messenger applications work like Stack data
                  structure.
                o New Message are always added or inserted at the top of the
                  message box.
Define Stack ADT
   A stack is a data structure that stores a linear collection of data items.
   Adding and removing items is done from one end known as the top of the
   stack. An empty stack is a stack containing no items.
         Stack( ): Creates a new empty stack.
         isEmpty( ): Returns a boolean value indicating whether the stack
SEARCH EDUCATIONS                                                         Page 3
DATA STRUCTURE WITH PYTHON                                   CODE: 20CS41P
      is empty or not.
      length( ): Returns the number of items in the stack.
      push(item): Adds the given item to the top of the stack.
      pop(): Removes and returns the top item of the stack, if the stack is not
      empty.
      Items cannot be popped from an empty stack. The next item on the
      stack becomes the new top item
SEARCH EDUCATIONS                                                       Page 4
DATA STRUCTURE WITH PYTHON                                        CODE: 20CS41P
                             STACK IMPLEMENTATION
Let us consider implementation of a stack in Python using List Data structure.
creating a Stack class.
       class Stack:
       def init (self):
       self.items = list()
       Push operation
       The push operation is used to add an element to the top of the stack.
           Here is an implementation:
       def push(self,value):
       self. items. append(value)
       Pop operation
       Pop method will remove the top element from the stack. We will make
           the stack return None if there are no more elements:
       def pop(self):
       if self.isEmpty() == True:
       print("Stack is empty, cannot remove") else:
       return self.items.pop()
       Peek
       Peek method will return the top of the stack without removing it from
           the stack. If there is a top element, return its data, otherwise return
           None.
       def peek(self):
       if self.isEmpty() == True:
       print("Stack is empty")
       else:
SEARCH EDUCATIONS                                                              Page 5
DATA STRUCTURE WITH PYTHON                                       CODE: 20CS41P
        return self.items[-1]
        Display
        Display method will display the all the elements of stack.
        def display(self):
        print("Stack items are") for i in self.items:
        print(i)
        isEmpty
        isEmpty is used to check whether stack is empty or not
        def isEmpty(self):
        if len(self.items) == 0: return True
        else:
        return False
        length
        length is used to find the number of elements present in the stack
        def length(self):
        return len(self.items)
Program #1: Python Program to implement Stack.
class Stack:
       def __init__(self):
                   self.items = list()
                def push(self,value):
            self.items.append(value)
      def pop(self):
if self.isEmpty() == True:
print("Stack is empty, cannot remove")
SEARCH EDUCATIONS                                                            Page 6
DATA STRUCTURE WITH PYTHON                      CODE: 20CS41P
else:
return self.items.pop()
def peek(self):
if self.isEmpty() == True:
print("Stack is empty")
else:
return self.items[-1]
def display(self):
print("Stack items are") for i in self.items:
print(i)
def isEmpty(self):
if len(self.items) == 0: return True
else:
return False
def length(self):
return len(self.items)
S = Stack()
S.push(10) S.push(20) S.push(30)
S.display()
print("Top of the Stack:",S.peek())
print("Length: ", S.length()) S.pop()
S.display()
SEARCH EDUCATIONS                                       Page 7
DATA STRUCTURE WITH PYTHON                    CODE: 20CS41P
print("Top of the Stack:",S.peek()) S.pop()
S.display()
print("Top of the Stack:",S.peek())
print("Empty?: ",S.isEmpty()) S.pop()
print("Empty?: ",S.isEmpty())
print("Length: ", S.length())
Output #1:
Stack items are 10
20
30
Top of the Stack: 30 Length: 3
Stack items are 10
20
Top of the Stack: 20
Stack items are 10
Top of the Stack: 10 Empty?: False Empty?:
True
Length: 0
SEARCH EDUCATIONS                                     Page 8
DATA STRUCTURE WITH PYTHON                                       CODE: 20CS41P
                              STACK APPLICATIONS
     BALANCED DELIMITERS
      A number of applications use delimiters. Some common examples
      include mathematical expressions, programming languages, and the
      HTML markup language used by web browsers.
      There is a strict rule that delimiters must be paired and balanced.
      The delimiters must be used in pairs of corresponding types: {}, [], and ().
Balanced Delimiters can be checked using Stack as follows:
1. As the input is scanned, we can push each opening delimiter onto the stack.
2. When a closing delimiter is found, we pop the opening delimiter from
   the stack and compare it to the closing delimiter.
3. For properly paired delimiters, the two should match. Thus, if the top of
   the stack contains a left bracket [, then the next closing delimiter should
   be a right bracket ].
4. If the two delimiters match, it indicates that current delimiter is
   properly paired and can continue processing the remaining input.
5. But if they do not match, it means that delimiters are not balanced and
   we can stop processing the input.
   Example: Consider the following code to be checked for delimiter:
SEARCH EDUCATIONS                                                            Page 9
DATA STRUCTURE WITH PYTHON                                     CODE: 20CS41P
   As the file is scanned, we can push each opening delimiter onto the
   stack. When a closing delimiter is encountered, we pop the opening
   delimiter from the stack and compare it to the closing delimiter.
   For properly paired delimiters, the two should match.
   Thus, if the top of the stack contains a left bracket [, then the next
   closing delimiter should be a right bracket].
   If the two delimiters match, we know they are properly paired and
   can continue processing the source code.
   But if they do not match, then we know the delimiters are not correct
   and we can stop processing the file.
   The below table shows the steps performed by our algorithm and the
   contents of the stack after each delimiter is encountered in our
   sample code segment.
SEARCH EDUCATIONS                                                           Page 10
DATA STRUCTURE WITH PYTHON                                      CODE: 20CS41P
Evaluating Postfix Expressions
      We work with mathematical expressions on a regular basis and they
      are rather easy for humans to evaluate.
      But the task is more difficult in a computer program.
      To simplify the evaluation of a mathematical expression, we need an
      alternative representation for the expression.
      Three different notations can be used to represent a mathematical
      expression.
    Infix notation - the operator is specified between the operands
      A+B.
    Prefix notation - the operator immediately precedes the two
      operands +AB,
    Postfix notation – the operator follows the two operands AB+.
Converting from Infix to Postfix
     Place parentheses around every group of operators in the correct order of
     evaluation.
     There should be one set of parentheses for every operator in the infix
     expression.
     ((A * B) + (C / D))
     For each set of parentheses, move the operator from the middle to the end
     preceding the corresponding closing parenthesis.
     ((A B *) (C D /) +)
     Remove all of the parentheses, resulting in the equivalent postfix
     expression. A B * C D / +
     Evaluation of Postfix Expressions
     Evaluating a postfix expression requires the use of a stack to store the
     operands or variables at the beginning of the expression until they are
     needed.
     Assume we are given a valid postfix expression stored in a string
     consisting of operators and single- letter variables.
     We can evaluate the expression by scanning the string, one character at a
     time.
     For each character or item, we perform the following steps:
         o If the current item is an operand, push its value onto the stack.
         o If the current item is an operator:
         o Pop the top two operands off the stack.
SEARCH EDUCATIONS                                                          Page 11
DATA STRUCTURE WITH PYTHON                                     CODE: 20CS41P
         o Perform the operation. (Note the top value is the right operand while
           the next to the top value is the left operand.)
         o Push the result of this operation back onto the stack.
Example:
let's evaluate the postfix expression: A B C + * D/. Assume,A = 8 C = 3
B=2D=4
The postfix evaluation algorithm assumes a valid expression. But what
happens if the expression is invalid?If the stack is not empty, It indicates
that the expression is invalid and we must flag an error.
SEARCH EDUCATIONS                                                         Page 12
DATA STRUCTURE WITH PYTHON                            CODE: 20CS41P
Program #2: Python Program to implement Bracket Matching using Stack
class Stack:
def __init__(self): self.items = list()
def push(self,value):
self.items.append(value)
def pop(self):
if self.isEmpty() == True:
print("Stack is empty, cannot remove")
else:
return self.items.pop()
def isEmpty(self):
if len(self.items) == 0:
return True
else:
return False
def isBalanced(S,text):
for char in text:
if char in ["[","{","("]:
S.push(char)
elif char in ["]","}",")"]:
temp = S.pop()
if temp == "(":if char != ")":
SEARCH EDUCATIONS                                              Page 13
DATA STRUCTURE WITH PYTHON                             CODE: 20CS41P
return False
if temp == "{":
if char != "}": return False
if temp == "[":
if char != "]":
return False
else:
continue
if S.isEmpty() == True:
return True
S = Stack()
text = input("Enter Text\n")
res=isBalanced(S,text) if res==True:
print("Valid and Balnaced Expression")
else:
print("Invalid expression")
Output #1:
Enter Text
a=int(input("Enter number")) Valid and Balnaced Expression
Output #2:
Enter Text a=int(input("Enter number")
Invalid Expression
SEARCH EDUCATIONS                                             Page 14
DATA STRUCTURE WITH PYTHON                                      CODE: 20CS41P
Experiment 1: Implement Stack Data Structure.
Introduction
    A Stack is a linear data structure, used to store group of data items such
      that the last item inserted is the first item removed.
    Stack data structure follows LIFO (Last In First Out) principle for
      insertion-deletion operation.
    Abstract View of Stack:
Basic Operations of Stack
Basic operations of Stack are listed below:
•Push
•Pop
Push Operation
•Inserting new data item at the top of the stack is known as Push operation on
Stack.
SEARCH EDUCATIONS                                                          Page 15
DATA STRUCTURE WITH PYTHON                                    CODE: 20CS41P
Pop Operation
•Removing existing data item from the top of the non-empty stack is known as
Pop operation on Stack.
Stack ADT
      A stack is a data structure that stores a linear collection of data items.
      Adding and removing items is done from one end known as the top of the
      stack. An empty stack is a stack containing no items.
      Stack( ): Creates a new empty stack.
      isEmpty( ): Returns a Boolean value indicating whether the stack is empty
      or not.
      length( ): Returns the number of items in the stack.
      push(item): Adds the given item to the top of the stack.
      pop(): Removes and returns the top item of the stack, if the stack is not
      empty.
                  Items cannot be popped from an empty stack.
                  The next item on the stack becomes the new top item.
      peek(): Returns data item from top of a non-empty stack without removing
      it.
Python implementation of Stack Data Structure
class Stack:
def _ _init_ _(self):
self.items = list()
def push(self,value):
self.items.append(value)
def pop(self):
if self.isEmpty() == True:
SEARCH EDUCATIONS                                                        Page 16
DATA STRUCTURE WITH PYTHON                                         CODE: 20CS41P
print("Stack is empty, cannot remove") else:
return self.items.pop()
def peek(self):
if self.isEmpty() == True: print("Stack is empty")
else:
return self.items[-1]
def display(self): print("Stack items are") for i in self.items:
print(I,end=”\t”)
def isEmpty(self):
if len(self.items) == 0: return True
else:
return False
def length(self):
return len(self.items)
S = Stack()
S.push(10) S.push(20) S.push(30) S.display()
print("\nTop Item of the Stack:",S.peek()) print("Length: ", S.length())
S.pop() S.display()
print("\nTop Item of the Stack:",S.peek()) S.pop()
S.display()
print("\nTop Item of the Stack:",S.peek()) print("Stack Empty?: ",S.isEmpty())
S.pop()
print("Stack Empty?: ",S.isEmpty())
print("Length: ", S.length())
Output #1
SEARCH EDUCATIONS                                                         Page 17
DATA STRUCTURE WITH PYTHON                                         CODE: 20CS41P
Assignments
   A letter means push and an asterisk means pop in the following sequence.
   Give the sequence of values returned by the pop operations when this
   sequence of operations is performed on an initially empty Stack.
      EAS*Y*QUE***ST***IO*N***
     Hand execute the following code segment and show the contents of the
     resulting stack.
values = Stack()
for iin range( 16 ) :
if i % 3 == 0 : values.push( i )
3.Hand execute the following code segment and show the contents of the
resulting stack.
values = Stack() for iin range( 16 ) : if i % 3 == 0 : values.push( i ) elifi % 4 == 0
: values.pop()
Experiment #2: Implement Bracket Matching using Stack.
Introduction
   A number of applications use delimiters (Brackets).
   Some common examples include mathematical expressions, programming
   languages, and the HTML mark-up language used by web browsers.
   There is a strict rule that delimiters (Brackets) must be paired and balanced.
   The delimiters (Brackets) must be used in pairs of corresponding types: {}, [],
   and ().
Bracket Matching can be implemented using Stack as follows:
    As the input is scanned, we can push each opening Delimiter (Bracket)
     onto the stack.
    When a closing delimiter (Bracket) is found, we pop the opening delimiter
     (Bracket) from the stack and compare it to the closing delimiter (Bracket).
    For properly paired delimiters, the two should match. Thus, if the top of the
     stack contains a left bracket [, then the next closing delimiter (Bracket)
     should be a right bracket ].
    If the two delimiters (Brackets) match, it indicates that current delimiter
     (Bracket) is properly paired and can continue processing the remaining
     input.
    But if they do not match, it means that delimiters (Brackets) are not
     balanced/matched and we can stop processing the input.
Example #1: input : ( { [ ] } )
SEARCH EDUCATIONS                                                             Page 18
DATA STRUCTURE WITH PYTHON                                     CODE: 20CS41P
     Input           Current                 Stack Operation                     Stack
                    Character
     ({[]                (            Push ( to the Stack               (
      })
     ({[]                {            Push { to the Stack                   ({
      })
     ({[]                [            Push [ to the Stack                   ({ [
      })
                                      Pop i.e [
     ({[]                ]            Compare it with current          ({
      })                              character i.e ] Yes, it matches
                                      Pop i.e {
     ({[]                }            Compare it with current          (
      })                              character i.e }
                                      Yes, it matches
                                      Pop i.e (
     ({[]                )            Compare it with current          ---------
      })                              character i.e ) Yes, it matches
                                        Since the stack is empty now, Brackets in
     ({[]             --------                              given
      })                                             input is matched.
Example #2: input: a=int(input( ) )
     Input           Current                 Stack Operation                 Stack
                    Character
   a=int(inp             a            No Operation. Just ignore.    Empty
     ut())
   a=int(inp             =            No Operation. Just ignore.    Empty
     ut())
   a=int(inp              i           No Operation. Just ignore.    Empty
     ut())
   a=int(inp             n            No Operation. Just ignore.    Empty
     ut())
   a=int(inp              t           No Operation. Just ignore.    Empty
     ut())
   a=int(inp              (           Push ( to the Stack               (
     ut())
   a=int(inp              i           No Operation. Just ignore.    (
SEARCH EDUCATIONS                                                                Page 19
DATA STRUCTURE WITH PYTHON                                         CODE: 20CS41P
     ut())
   a=int(inp                n             No Operation. Just ignore.    (
     ut())
   a=int(inp                p             No Operation. Just ignore.    (
     ut())
   a=int(inp                u             No Operation. Just ignore.    (
     ut())
   a=int(inp                t             No Operation. Just ignore.    (
     ut())
   a=int(inp                (             Push ( to the Stack               ((
     ut())
                                          Pop i.e (
   a=int(inp                )             Compare it with current         (
     ut())                                character i.e ( Yes, it
                                          matches
                                          Pop i.e (
   a=int(inp                )             Compare it with current         Empty
     ut())                                character i.e (
                                          Yes, it matches
                                          Since the stack is empty now, Brackets
   a=int(inp           --------                         in given input is matched.
     ut())
Example #3: input : ( { )
     Input           Current                    Stack Operation                  Stack
                    Character
     ({[)                   (           Push ( to the Stack             (
      ({)                   {           Push { to the Stack               ({
                                        Pop i.e {
                                        Compare it with current
      ({)                   )                                             (
                                        character i.e ) No, it does not
                                        match.
                                        Stop processing the input.
                                Brackets in given input is not
                                          matched.
SEARCH EDUCATIONS                                                                Page 20
DATA STRUCTURE WITH PYTHON                                   CODE: 20CS41P
Python Implementation of Bracket matching using Stack
        class Stack:
def _ _init_ _(self):
self.items = list()
def push(self,value):
self.items.append(value)
def pop(self):
if self.isEmpty() == True:
print("Stack is empty, cannot remove") else:
return self.items.pop()
def isEmpty(self):
if len(self.items) == 0: return True
else:
return False
def length(self):
return len(self.items)
def isBalanced(text):
S = Stack()
for char in text:
if char in ["[","{","("]: S.push(char)
elif char in ["]","}",")"]: temp = S.pop()
if temp == "(":
if char != ")": return False
if temp == "{":
if char != "}": return False
if temp == "[":
if char != "]": return False
else:
continue
if S.isEmpty() == True: return True
text = input("Enter Text\n") res=isBalanced(text)
if res==True:
print("Brackets are matched\nValid and Balnaced Expression") else:
print("Brackets are not matched\nInvalid expression")
Output #1
SEARCH EDUCATIONS                                                    Page 21
DATA STRUCTURE WITH PYTHON                                    CODE: 20CS41P
Output #2:
Output #3:
Output #4:
Assignments
     For the following statements, Verify whether the brackets are matching or
        not.
(a)print(sum(10,20)
(b) [ ] ( { } )
(c) (A - C) + (C * D) / E
(d) [ { } ( ) { } [ ]
    Rewrite the isBalanced( ) function defined in the above program by
     including one more delimiter i.e < >.
    For the following statements, Verify whether the delimiters are matching or
     not.
(a) <b>Hi</i>
(b) <bHello</b>
SEARCH EDUCATIONS                                                         Page 22
DATA STRUCTURE WITH PYTHON                                      CODE: 20CS41P
Implement and Demonstrate Evaluating Postfix Expression
Introduction
    We work with mathematical expressions on a regular basis and they
      are rather easy for humans to evaluate. But the task is more difficult in
      a computer program.
    To simplify the evaluation of a mathematical expression, we need an
      alternative representation for the expression.
Three different notations can be used to represent a mathematical expression.
            Infix notation - the operator is specified between the operands
               A+B.
            Prefix notation - the operator immediately precedes the two
               operands +AB,
            Postfix notation – the operator follows the two operands AB+.
Evaluation of Expressions
To simplify the evaluation of a mathematical expression, we need to perform the
following operations in order:
    Convert given infix expression to its equivalent postfix form.
    Evaluate the postfix expression.
Converting Infix Expression to Postfix Expression
To convert infix expression to its equivalent postfix expression, we need to
follow the steps given below:
Example: Let us consider infix expression: A*B+C/D
    Place parentheses around every group of operands in the correct order of
     evaluation. There should be one set of parentheses for every operator in the
     infix expression.
     ((A * B) + (C / D))
    For each set of parentheses, move the operator from the middle to the end
     preceding the corresponding closing parenthesis.
     ((A B *) (C D /) +)
    Remove all of the parentheses to get the equivalent postfix expression. A B
     *CD/+
SEARCH EDUCATIONS                                                          Page 23
DATA STRUCTURE WITH PYTHON                                         CODE: 20CS41P
Evaluation of Postfix Expressions
     Evaluating a postfix expression requires the use of a stack to store the
     operands or variables at the beginning of the expression until they are
     needed.
     Initially, the stack is empty. Assume we are given a valid postfix
     expression stored in a string consisting of operators and single-letter
     variables.
     We can evaluate the expression by scanning the given expression or input
     string, one character at a time.
     For each character or item, we perform the following steps:
    If the current item is an operand, push its value onto the stack.
    If the current item is an operator:
      Pop the top two operands off the stack.
      Perform the operation. (Note the top value is the right operand while the
      next to the top value is the left operand.)
      Push the result of this operation back onto the stack.
    At the end of the expression evaluation, If the stack contains only one
     value i.e result, then it indicates that the given infix/postfix expression is
     valid.
    At the end of the expression evaluation, If the stack contains too many
     values, it indicates that the given infix/postfix expression is invalid (we
     need to display appropriate error message in applications to indicate the
     same).
Example #1: Evaluate the postfix expression: A B C + * D/.
Given,   A=8 B=2 C=3D=4
         Expressi         Current                 Stack Operation            Stack
           on            Character
                                          Push the value of A to
         ABC+                 A                                          8
                                          the Stack Push (8)
          *D/
                                          Push the value of B to the
         ABC+                 B                                         82
                                          Stack
          *D/                             Push (2)
                                          Push the value of C to the
         ABC+                 C                                         82 3
                                          Stack
          *D/                             Push (3)
                                          Pop two items, right = 3 left
         ABC+                 +           = 2 perform 2 + 3 = 5         85
                                          Push 5 to the stack ,
SEARCH EDUCATIONS                                                             Page 24
DATA STRUCTURE WITH PYTHON                                    CODE: 20CS41P
          *D/                          Push(5)
                                       Pop two items, right = 5 left
         ABC+               *          = 8 perform 5 * 8 = 40        40
          *D/                          Push 40 to the stack ,
                                       Push(40)
                                       Push the value of D to the
         ABC+               D                                        40 4
                                       Stack
          *D/                          Push (4)
                                       Pop two items, right = 4 left
         ABC+               /          = 40 perform 40 * 4 = 10      10
          *D/                          Push 10 to the stack ,
                                       Push(10)
Example #2: Evaluate the expression: A * B / C.
Given,    A = 5 B =4 C = 3
Convert given expression to its postfix form.
   ((A*B)/C)
   ((AB*)C/)
   AB*C/
Equivalent Postfix Expression: AB*C/
Evaluate Postfix Expression.
Postfix Expression: AB*C/
Given,      A = 5 B =4 C = 10
        Expressio         Current                Stack Operation              Stack
           n             Character
                                         Push the value of A to the
         AB*C/                  A                                        5
                                         Stack
                                         Push (5)
                                         Push the value of B to the
         AB*C/                  B                                        54
                                         Stack Push (4)
                                         Pop two items, right = 4 left =
         AB*C/                  *        5 perform 5 + 4 = 20            20
                                         Push 20 to the stack ,
                                         Push(20)
                                         Push the value of C to the
         AB*C/                  C                                        20 10
                                         Stack Push (10)
                                         Pop two items, right = 10 left
         AB*C/                  /        = 20 perform 20 / 10 = 2        2
                                         Push 2 to the stack , Push(2)
SEARCH EDUCATIONS                                                           Page 25
DATA STRUCTURE WITH PYTHON                                        CODE: 20CS41P
At the end, Here Only one value (result) left on stack, it indicates that given
expression is valid and 2 is the result of the expression.
Example #3: Evaluate the postfix expression: A B * C D +.
Given,    A=8B=2C=3D=4
         Expressio          Current                 Stack Operation               Stack
            n              Character
                                            Push the value of A to the
          AB*C                  A                                           8
                                            Stack
           D+                               Push (8)
                                            Push the value of B to the
          AB*C                  B                                           82
                                            Stack
           D+                               Push (2)
                                            Pop two items, right = 2 left =
          AB*C                  *           8 perform 8 * 2 = 16            16
           D+                               Push 16 to the stack ,
                                            Push(16)
                                            Push the value of C to the
          AB*C                  C                                           16 3
                                            Stack Push (3)
           D+
                                            Push the value of C to the
          AB*C                  D                                           16 3 4
                                            Stack Push (4)
           D+
                                            Pop two items, right = 4 left =
          AB*C                  +           3 perform 3 + 4 = 7             16 7
           D+                               Push 7 to the stack , Push(7)
At the end, Here Too many values left on stack, it indicates that given expression
is invalid.
Python Implementation to evaluate Postfix Expressions.
class Stack:
def init (self):
self.items = list()
def push(self,value):
self.items.append(value)
def pop(self):
if self.isEmpty() == True:
print("Stack is empty, cannot remove") else:
return self.items.pop()
def isEmpty(self):
SEARCH EDUCATIONS                                                            Page 26
DATA STRUCTURE WITH PYTHON                                       CODE: 20CS41P
if len(self.items) == 0: return True
else:
return False
def length(self):
return len(self.items)
def evaluate(text):
S = Stack()
for char in text:
if char in ["0","1","2","3","4","5","6","7","8","9"]:
S.push(int(char))
elif char in ["+","-","*","/","%"]: right = S.pop()
left = S.pop() if char == "+":
res = left + right S.push(res)
if char == "-":
res = left - right S.push(res)
if char == "*":
res = left * right S.push(res)
if char == "/":
res = left / right S.push(res)
if char == "%":
res = left % right S.push(res)
else:
print("Expression should contains only digits and operators (+, -, *, /, %)") return
if S.length() == 1: print("Valid Expression") print("Result: ",S.pop())
else:
print("Invalid Expression")
inputExp = input("Enter Postfix Expression\n") evaluate(inputExp)
Output 1
Output 2
SEARCH EDUCATIONS                                                           Page 27
DATA STRUCTURE WITH PYTHON                                      CODE: 20CS41P
Assignments
       Translate each of the following infix expressions into postfix notation and
       evaluate it using Stack. Given, A= 5, B=4, C=1 D=5 E=3.
  a.   (A * B) / C
  b.   A - (B * C) + D / E
  c.   (A - C) + (C * D) / E
  d.   E*D*A+B-C
  e.   A/B*C-D+E
       Evaluate the following postfix expressions using Stack. Given, A= 5, B=4,
       C=1 D=5 E=3.
  a.   ABC-D*+
  b.   AB+CD-/E+
  c.   ABCDE*+/+
  d.   DCE+AB-*-
  e.   AB+C-DE*+
SEARCH EDUCATIONS                                                           Page 28