Stack 12csc
Stack 12csc
Stack 12csc
COMPUTER SCIENCE
Chapter 2: Stack
(PUSH and POP) and its implementation in python. Expressions in Prefix, Infix, and
postfix
postfix expression
Table of Contents
Stack
1
Takhellambam Sylvia
Examples:
1. String – Contains sequence of characters
2. List – Contains sequence of different data types
2. Stack
The stack is used in many fields in our routine life. Some examples are:
1. Browsers History
2. Mobile Phone Call log
3. Undo and redo commands in software
we can say that a stack is a list of data that follows these rules:
1. Data can only be removed from the top (pop), i.e., the element at the top of
the stack. The removal of element from a stack is technically called POP
operation.
2. A new data element can only be added to the top of the stack (push). The
insertion of element in a stack is technically called PUSH operation
Consider figure below that illustrates the operations (push and pop) on a stack.
2
Takhellambam Sylvia
There are some other terms related to stacks, such as peek, overflow and Underflow.
Example:
Let’s have an example of a bounded stack of capacity 4 which is initially empty, and
drawing pictures of the stack after each of the following steps. Initially the stack is
empty.
3
Takhellambam Sylvia
Solution.
4
Takhellambam Sylvia
pop top = 1
5
Takhellambam Sylvia
Pop top = 2
pop top = 1
pop top = 0
6
Takhellambam Sylvia
In python, you can use lists to implement stacks. Python offers us a convenient set
of methods to operate lists as stacks.
7
Takhellambam Sylvia
where < stack> is a list; top is an integer having value equal to len
(<stack>) -1.
push(a) – Inserts the element ‘a’ at the top of the stack – Time Complexity:
O(1)
pop() – Deletes the topmost element of the stack – Time Complexity: O(1)
Program Code:
STACK IMPLEMENTATION
#Let us create an empty stack -A function named isEmpty to check whether the
stack glassStack is empty or not.
8
Takhellambam Sylvia
return item
#_main_
stack = [ ] # initially stack is empty
top = None
While True:
print (“STACK OPERATIONS”)
print (“1. Push”)
print (“2. Pop”)
print (“3. Peek”)
print (“4. Display stack”)
print ( “5. Exit”)
ch = int (input (“Enter your choice (1-5) :” ) )
if ch == 1 :
item = int (input (“Enter item:” ) )
push (stack, item)
elif ch == 2 :
item = pop (stack)
if item ==”underflow”
print (“underflow” : stack is empty !” )
else:
print (“popped item is”, item)
elif ch == 3:
item = peek (stack)
if item ==”underflow”
9
Takhellambam Sylvia
10
Takhellambam Sylvia
An item stored in a stack is also called item- node sometimes. In the above
implemented stack, the stack contained item-nodes containing just integers. If you
want to create stack that may contain logically group information such as member
details like: member no, member name, age etc. For such the item-node will be a list
containing the member details and then this list will be entered as an item to the
stack. (See figure below)
For stack of figure (a), the stack will be implemented as stack of integers as
item-node is of integer type.
For stack of figure (b), the stack will be implemented as stack of strings as
item-node is of string type.
11
Takhellambam Sylvia
For stack of figure (c), the stack will be implemented as stack of lists as item-
node is of list type.
There are several applications and uses of stacks. The stacks are basically applied
where LIFO (Last in First Out) scheme is required
12
Takhellambam Sylvia
For example:
(A + B) C (D/(J + D)).
These complex arithmetic operations can be converted into polish string using
stacks which then can be executed in two operands and operator form.
Polish string, named after a polish mathematician, Jan Lukasiewicz, refers to the
notation in which the operator symbol is placed either before its operands (prefix
notation) or after its operands (postfix notation) in contrast to usual form where
operator is placed in between the operands (infix notation).
13
Takhellambam Sylvia
which
I. Brackets or Parenthesis,
II. Exponentiation,
An infix expression may be converted into postfix from either manually or using a
stack. The manual conversion requires two passes: one for inserting braces and
another for conversion. However, the convert an infix expression into a postfix
expression manually are given below:
Repeat step (ii) until entire expression is converted into postfix notation.
Solution:
= ((A+B) ×C)/D
= ((AB+) ×C)/D
=(AB+C×) / D
= AB +C × D /
=(((AB+C*)/D) + EF^)/G
14
Takhellambam Sylvia
A* (B+(C+D) * (E+F)/*H
(A*(B+((C+D) * (E+F))/G)) *H
=(A*(B+[(CD+) *(EF+)]/G)) *H
= ABCD+EF + *G/ + H
Solution:
=A + [{BC + DE +F * +}/G]
=ABC +DE +F * +G / +
While converting from infix to prefix form, operation is put before the operands. Rest
of the conversion procedure is like that of infix to postfix conversion.
The following algorithm transforms the infix expression X into its equivalent
postfix expression Y.
15
Takhellambam Sylvia
The algorithm uses a stack to temporarily hold operators and left parentheses.
The postfix expression Y will be constructed from left to right using the
operands from X and the operators which are removed from STACK.
2. Scan X from left to right and REPEAT Steps 3 to 6 for each element of X until
the STACKS is empty:
6. Repeatedly pop from STACKS and add to Y each operator (on the top of
STACKS) which has the same precedence as or higher precedence than
operands.
‘ ‘ ‘ End of if structure’ ‘ ‘
7. Repeatedly pop from STACK and add to Y each operator (on the top of STACK)
until a left parenthesis is encountered.
8. Remove the left parenthesis. [Do not add the left parenthesis to Y].
‘ ‘ ‘ End of if structure’ ‘ ‘
7. END
Solution:
16
Takhellambam Sylvia
17
Takhellambam Sylvia
While reading the expression from left to right, push the element in the stack
if it is an operand;
Pop the two operands from the stacks, if the element is a binary operator. In
case of NOT operator, pop one operand from the stack and then evaluate it
(two operands and an operator).
Push back the result of the evaluation. Repeat it till the end of the expression.
**For a binary operator, two operands are popped from stack and for a unary
operator, one operand is popped. Then, the result is calculated using operand(s) and
the operator, and pushed back into the stack. **
ELSE POP two elements from the Stack, apply the operator on
the popped elements and PUSH the computed value onto the Stack
18
Takhellambam Sylvia
19
Takhellambam Sylvia
Example:2
Example 3:
456*+
The prefix expression is also without parentheses. The prefix expression are
evaluated by the compiler by using two stacks:
One stack (symbol stack) for holding the symbols of the expression (all the
operators and operands/values of the expression are considered symbols)
and
20
Takhellambam Sylvia
Another stack (number stack or operand-value stack) for holding the numbers
Algorithm −
Step 2.1: if it is an operand, push it to the stack.Step 2.2: If it is an operator, pop two
operands from the stack. Perform the operation and push the elements back to the
stack.
Step 3: Do this till all the elements of the expression are traversed and return the top
of stack which will be the result of the operation.
Example: 1. (+ -927)
21
Takhellambam Sylvia
Example 2: ( /+33-+47*+123)
An infix expression is difficult for the machine to know and keep track of
precedence of operators.
Therefore, for the machine, it is easier to carry out a postfix expression than
an infix expression.
22
Takhellambam Sylvia
SUMMARY
23
Takhellambam Sylvia
24
Takhellambam Sylvia
Ans: LIFO
Ans: Top
(True/False) Ans:False
[7] The peek operation refers to accessing/inspecting the top element in the stack.
(True/False)
[9] While popping the element from the stack, a condition will be raised, this
condition is known as ____________.
[1] What do you mean by data structure? Explain your answer with a suitable
example
Ans.: The systematic way of organization, storing, accessing, and retrieving data
including well-defined operations, behaviour and properties is known as data
25
Takhellambam Sylvia
structure.
Examples:
1. String – Contains sequence of characters
2. List – Contains sequence of different data types
[2] What do you mean by the LIFO structure? Support your answer with real-life
examples.
Ans.: LIFO is one of the principles to access data from a data structure. It stands for
Last In First Out. It refers to the item which is inserted last will be access first. So,
the top element will be accessed first.
Example:
1. Books in the shelf
2. Stack of coins
3. Pile of chairs
4. Bangles on woman’s wrist
[3] Enlist a few of the fields where you feel a stack is used in real life.
Ans.: The stack is used in many fields in our routine life. Some examples are:
1. Browsers History
2. Mobile Phone Call log
3. Tubewell boring machine
4. Undo and redo commands in software
[4] What are the basic operations that can be performed on the stack?
Ans.: There are two basic operations can be performed on the stack:
1. Push – Inserting an element
2. Pop – Deleting an element
Ans.: Underflow is the condition which occurs when stack is empty while trying to
delete elements. Overflow is the condition which occurs while inserting an element
when memory is exhausted.
4. Traverse/Display an element
Ans:
def is underflow(stk):
if stk==[]:
return True
else:
return False
Ans:
stk.append(e)
Ans:
def pop_stack(stk):
if stk==[]:
return "UnderFlow"
else:
e = stk.pop()
if len(stk)==0:
top = None
else:
top = len(stk)-1
return e
Ans:
def display(stk):
27
Takhellambam Sylvia
if stk==[]:
print("Stack is Empty")
else:
top = len(stk)-1
print(stk[top],"-Top")
for i in range(top-1,-1,-1):
print(stk[i])
Ans:
def peek(stk):
if stk==[]:
return "UnderFlow"
else:
top = len(stk)-1
return stk[top]
Ans:
def AddPlayer(player):
player.append(pn)
def DeletePlayer(player):
if player==[]:
else:
return player.pop()
782*4/+
28
Takhellambam Sylvia
Ans:
=7 8 2 * 4 / +
= 7 16 4 / +
=74+
= 11
Assignment
a) result=0
numberList=[10,20,30]
numberList.append(40)
result=result+numberList.pop()
result=result+numberList.pop()
print(“Result=”,result)
b) answer=[];
output='' answer.append('T')
answer.append('A')
answer.append('M')
ch=answer.pop()
output=output+ch
ch=answer.pop()
output=output+ch
ch=answer.pop()
output=output+ch
print(“Result=”,output)
10 20 + 25 15 - * 30 /
Q. Q. Evaluate the following postfix expression using a stack and show the
29
Takhellambam Sylvia
15 3 2 + / 7 + 2 *
1.(A*B)/C
2.A-(B*C)+D/E
3.V*W*X+Y-Z
1.A+B-C*D
2. A*((C+D)/E)
3.A*B+C+D*E
30