2nd PUC Computer Science Chapter 3 β Stack Notes β Complete Notes, Q&A & Exam Preparation
Complete Short Notes & Exam Preparation Guide
Stack, Operations on Stack, Python Implementation & Expression Notations
Based on the NCERT textbook PDFπ Chapter Overview
In Class XI, different Python data types such as String, List, Set and Tuple were studied for handling values and representing collections of elements. A data structure is a mechanism used to store, organise and access data along with operations that can be efficiently performed on the data.
This chapter introduces Stack, its operations, implementation using Python and applications. It also explains arithmetic expression notations, conversion from infix to postfix notation and evaluation of postfix expressions.
π Table of Contents
- 3.1 Introduction
- 3.2 Stack
- 3.2.1 Applications of Stack
- 3.3 Operations on Stack
- 3.3.1 PUSH and POP Operations
- 3.4 Implementation of Stack in Python
- Stack Functions in Python
- Complete Stack Program
- 3.5 Notations for Arithmetic Expressions
- 3.6 Conversion from Infix to Postfix Notation
- Algorithm 3.1
- 3.7 Evaluation of Postfix Expression
- Algorithm 3.2
- Chapter Summary
- Questions & Answers
- Important Questions
- Quick Revision
- Textbook Exercise
3.1 Introduction
Python provides different data types for handling values. String, List, Set and Tuple are sequence data types that can represent collections of elements of the same type or different types.
Multiple data elements are grouped in a particular way for faster accessibility and efficient storage. Such grouping is called a data structure.
Meaning of Data Structure
A data structure defines a mechanism to store, organise and access data along with operations that can be efficiently performed on that data.
Examples from the Chapter
- String is a data structure containing a sequence of elements where each element is a character.
- List is a sequence data structure in which each element may be of different types.
- Operations such as reversal, slicing and counting can be applied on lists and strings.
Other Important Data Structures
Other important data structures in Computer Science include:
- Array
- Linked List
- Binary Trees
- Heaps
- Graph
- Sparse Matrix
Linear Data Structure
Stack and Queue are two popular data structures used in programming. Although they are not directly available in Python, their concepts are important because they are extensively used in a number of programming languages.
3.2 Stack
A stack can be understood using the example of a pile of books or a stack of plates. When another book or plate is added, it is placed only at the top. Similarly, when an object is removed, it is removed only from the top.
Adding or removing an object from the middle or bottom is inconvenient in a large pile. This arrangement of elements in a linear order is called a stack.
Definition of Stack
LIFO Principle
A stack follows the Last-In-First-Out (LIFO) principle. Therefore, the element inserted last is the first element to be removed.
3.2.1 Applications of Stack
Real-Life Applications
- Pile of clothes in an almirah
- Multiple chairs in a vertical pile
- Bangles worn on wrist
- Pile of boxes of eatables in pantry or on a kitchen shelf
Applications in Programming
1. Reversing a String
To reverse a string, the string is traversed from the last character to the first character. This can be done easily by putting the characters of the string in a stack.
2. Redo/Undo in Text or Image Editors
Text/image editors provide redo and undo options. The most recent editing is redone or undone when the corresponding icon is selected. A stack is used to keep track of changes made.
3. Browser Back Button
While browsing, web pages are accessed through links. Suppose a user moves from P1 to P2 and then P3. Clicking the BACK button once takes the user from P3 to P2, and another click takes the user to P1. The history of browsed pages is maintained as a stack.
4. Matching Parentheses
Arithmetic expressions may use parentheses to order the evaluation of operators. The compiler checks whether opening and closing parentheses are matched and properly nested. A stack is used to handle matching parentheses.
3.3 Operations on Stack
A stack implements a LIFO arrangement. Elements are added and deleted from one end only. This end is called the TOP of the stack.
The two fundamental operations performed on a stack are:
| Operation | Purpose | Type |
|---|---|---|
| PUSH | Adds a new element at the TOP of the stack. | Insertion operation |
| POP | Removes the topmost element from the stack. | Deletion operation |
3.3.1 PUSH and POP Operations
PUSH
PUSH adds a new element at the TOP of the stack. It is an insertion operation.
Elements can be added until the stack becomes full. A stack is full when no more elements can be added. Trying to add an element to a full stack results in an exception called overflow.
POP
POP removes the topmost element of the stack. It is a deletion operation.
Elements can be deleted until the stack becomes empty. Trying to delete an element from an empty stack results in an exception called underflow.
| Condition | Operation | Result |
|---|---|---|
| Stack has space | PUSH | New element is inserted at TOP. |
| Stack is full | PUSH | Overflow condition. |
| Stack contains elements | POP | Topmost element is deleted. |
| Stack is empty | POP | Underflow condition. |
Logical Sequence of the Textbook Example
The textbook illustrates a stack of numbered glasses. The sequence includes PUSH and POP operations in which the topmost glass is always affected.
In the illustrated sequence, POP removes 2, then 4, then 3 and finally 1 as the top element at each stage.
3.4 Implementation of Stack in Python
A stack is a linear and ordered collection of elements. A simple way to implement a stack in Python is by using the list data type.
Either side of the list can be fixed as TOP for inserting and removing
elements. The chapter uses the rightmost end because Python’s built-in
append() and pop() methods insert/delete elements at
that end. Therefore, explicit declaration of TOP is not needed.
Operations Required in the Chapter Program
- Insert/delete elements (glasses)
- Check whether the stack is empty
- Find the number of elements in the stack
- Read the value of the topmost element
Stack Functions in Python
1. Creating an Empty Stack
An empty list named glassStack is created:
glassStack = list()
2. isEmpty()
The isEmpty function checks whether glassStack is
empty. It returns True if the stack is empty and
False otherwise.
def isEmpty(glassStack):
if len(glassStack)==0:
return True
else:
return False
3. opPush()
The opPush function inserts an element into the stack using
append().
def opPush(glassStack,element):
glassStack.append(element)
4. size()
The size function returns the number of elements in the stack by
using Python’s len() function.
def size(glassStack):
return len(glassStack)
5. top()
The top function reads the most recent element in
glassStack. If the stack is empty, it displays
Stack is empty and returns None.
def top(glassStack):
if isEmpty(glassStack):
print('Stack is empty')
return None
else:
x =len(glassStack)
element=glassStack[x-1]
return element
6. opPop()
The opPop function removes and returns the topmost element.
It first checks whether the stack is empty. The Python list method
pop() removes the element from the end of the list.
def opPop(glassStack):
if isEmpty(glassStack):
print('underflow')
return None
else:
return(glassStack.pop())
7. display()
The display function shows the contents of the stack.
def display(glassStack):
x=len(glassStack)
print("Current elements in the stack are: ")
for i in range(x-1,-1,-1):
print(glassStack[i])
π» Complete Stack Program from the Chapter
After defining the functions, the chapter uses the following Python code to implement a stack of glasses.
glassStack = list() # create empty stack
#add elements to stack
element='glass1'
print("Pushing element ",element)
opPush(glassStack,element)
element='glass2'
print("Pushing element ",element)
opPush(glassStack,element)
#display number of elements in stack
print("Current number of elements in stack is",size(glassStack))
#delete an element from the stack
element=opPop(glassStack)
print("Popped element is",element)
#add new element to stack
element='glass3'
print("Pushing element ",element)
opPush(glassStack,element)
#display the last element added to the
#stack
print("top element is",top(glassStack))
#display all elements in the stack
display(glassStack)
#delete all elements from stack
while True:
item=opPop(glassStack)
if item == None:
print("Stack is empty now")
break
else:
print("Popped element is",item)
Output
Pushing element glass1
Pushing element glass2
Current number of elements in stack is 2
Popped element is glass2
Pushing element glass3
top element is glass3
Current elements in the stack are:
glass3
glass1
Popped element is glass3
Popped element is glass1
Underflow
Stack is empty now
append() is used for insertion and pop() for
deletion.
π Important Points About Python Stack Implementation
- The stack is implemented using a Python list.
append()adds an element at the end of the list.pop()removes an element from the end of the list.- The chapter therefore does not require an explicit declaration of TOP.
- Python lists do not have a fixed size.
- The implemented stack will not become full unless there is no more space available in memory.
- Therefore, the chapter states that the implemented stack will not face an overflow condition under normal list-size operation.
3.5 Notations for Arithmetic Expressions
Arithmetic expressions are commonly written with operators between operands,
such as x + y and 2 - 3 * y. Parentheses can be used
to order evaluation in complex expressions. These expressions follow
infix representation and are evaluated using the BODMAS rule.
Polish Notation
Polish mathematician Jan Lukasiewicz introduced a different way of representing arithmetic expressions in the 1920s, called Polish notation. In this notation, operators are written before their operands.
For example, x+y can be written as +xy. This is also
called prefix notation because the operator is prefixed before
the operands.
Reverse Polish Notation
By reversing this logic, operators can be placed after their operands.
For example, x+y can be written as xy+. This is called
reverse Polish notation or postfix notation.
Three Arithmetic Expression Notations
| Type of Expression | Description | Examples from the Chapter |
|---|---|---|
| Infix | Operators are placed between the operands. |
x * y + z3 *(4 + 5)(x + y)/(z * 5)
|
| Prefix (Polish) | Operators are placed before the corresponding operands. |
+z*xy*3+45/+xy*z5
|
| Postfix (Reverse Polish) | Operators are placed after the corresponding operands. |
xy*z+345+*xy+z5*/
|
Infix β Operator in between
Prefix β Operator before operands
Postfix β Operator after operands
3.6 Conversion from Infix to Postfix Notation
Humans can easily evaluate an infix expression. For example, in
x + y / z, the division operation is performed before addition
because of operator precedence following BODMAS.
Prefix and postfix expressions do not have to deal with this precedence during evaluation because the operators are already positioned according to their order of evaluation. Hence, a single traversal from left to right is sufficient to evaluate the expression.
The chapter explains how an arithmetic expression written in infix notation can be converted into an equivalent postfix expression using a stack.
Role of Stack in Conversion
During conversion, a stack keeps track of the operators encountered in the infix expression. A string variable stores the equivalent postfix expression.
Algorithm 3.1: Conversion of Infix to Postfix
postExp.inExp.inExp, repeat Step 4.postExp until Stack is empty.postExp.Detailed Step 4
- If the character is a left parenthesis, PUSH it onto the Stack.
-
Else if the character is a right parenthesis, POP elements
from the Stack and append them to
postExpuntil the corresponding left parenthesis is popped. Discard both left and right parentheses. - Else if the character is an operator, compare its precedence with the operator at the top of the Stack.
-
If its precedence is lower than that of the operator at the top of the Stack,
POP elements until an operator with precedence less than the current operator
is encountered and append them to
postExpbefore pushing the current operator onto the stack. - Otherwise, PUSH the operator onto the Stack.
-
If the character is an operand, append it to
postExp.
π Example 3.1 β Infix to Postfix
The chapter converts the following infix expression into its equivalent postfix expression:
(x + y)/(z*8)
The stack is used to track the operators and parentheses, while a string variable contains the equivalent postfix expression.
Initially both are empty. Each character in the infix expression is processed from left to right and the appropriate action is performed according to the algorithm. After all characters are processed, the string contains the equivalent postfix expression.
3.7 Evaluation of Postfix Expression
A stack can also be used to evaluate an expression written in postfix notation. For simplification, the chapter assumes that operators used in expressions are binary operators.
Algorithm 3.2: Evaluation of Postfix Expression
-
Step 1: INPUT postfix expression in a variable, say
postExp. -
Step 2: For each character in
postExp, repeat Step 3. - Step 3: If the character is an operand, PUSH the character onto the Stack.
- Else, POP two elements from the Stack, apply the operator on the popped elements and PUSH the computed value onto the Stack.
- Step 4: If the Stack has a single element, POP the element and OUTPUT it as the net result.
- Otherwise, OUTPUT βInvaild Postfix expressionβ as given in the textbook.
π Example 3.2 β Evaluation of Postfix Expression
The chapter demonstrates evaluation of the postfix expression:
7 8 2 * 4 / +
The stack-based procedure PUSHes operands, POPs two elements when an operator occurs, applies the operator and PUSHes the computed result back onto the Stack.
π Chapter Summary
- Stack is a data structure in which insertion and deletion are done from one end only, usually referred to as TOP.
- Stack follows the LIFO principle, in which the element inserted last is the first one to be removed.
- PUSH and POP are the two basic operations performed on a stack for insertion and deletion respectively.
- Trying to POP an element from an empty stack results in the special condition called underflow.
- In Python, a list is used for implementing a stack.
- The built-in functions
append()andpop()are used for insertion and deletion respectively. - Because of the way the Python list is used in this implementation, no explicit declaration of TOP is needed.
- An arithmetic expression can be represented in Infix, Prefix or Postfix notation.
- Infix notation places binary operators between operands.
- A single traversal from left to right is sufficient to evaluate Prefix/Postfix expressions because operators are correctly placed according to their order of precedence.
- Stack is commonly used to convert an Infix expression into equivalent Prefix/Postfix notation.
- During conversion of an Infix notation to its equivalent Prefix/Postfix notation, only operators are PUSHed onto the Stack.
- When evaluating a Postfix expression using Stack, only operands are PUSHed onto it.
β Questions & Answers
1-Mark Questions
A data structure defines a mechanism to store, organise and access data along with operations that can be efficiently performed on the data.
A data structure in which elements are organised in a sequence is called a linear data structure.
A stack follows the Last-In-First-Out (LIFO) principle.
TOP is the end of the stack from which elements are added or deleted.
PUSH is the insertion operation that adds a new element at the TOP of the stack.
POP is the deletion operation used to remove the topmost element from the stack.
Trying to add an element to a full stack results in an exception called overflow.
Trying to delete an element from an empty stack results in an exception called underflow.
The Python list data type.
append()
pop()
Infix notation is a representation in which operators are placed between operands.
Prefix notation places operators before the corresponding operands.
Postfix notation places operators after the corresponding operands.
PUSH and POP.
2-Mark Questions
LIFO means Last-In-First-Out. In a stack, the element inserted last is the first element to be removed.
| Basis | PUSH | POP |
|---|---|---|
| Purpose | Adds an element. | Removes an element. |
| Operation | Insertion | Deletion |
| Position | TOP | TOP |
Trying to add an element to a full stack results in the exception called overflow.
Trying to delete an element from an empty stack results in the exception called underflow.
Stack is used for reversing a string and maintaining browser history. It is also used for redo/undo operations and matching parentheses.
3-Mark Questions
Stack is used for reversing a string, keeping track of changes in text/image editors for redo/undo operations, maintaining browser history for the BACK button, and handling matching parentheses in arithmetic expressions.
| Notation | Position of Operator | Example |
|---|---|---|
| Infix | Between operands | x + y |
| Prefix | Before operands | +xy |
| Postfix | After operands | xy+ |
4/5-Mark Questions
A stack can be implemented using a Python list. The chapter creates an empty
list called glassStack. The append() method is used
to insert an element at the end of the list and pop() is used to
remove the element from the end. Functions such as isEmpty(),
opPush(), size(), top(),
opPop() and display() are defined to perform
stack operations.
The algorithm creates an empty postfix string, takes the infix expression as input and processes every character from left to right. Parentheses and operators are handled using a stack, while operands are appended to the postfix string. After all characters are processed, remaining stack elements are popped and appended to the postfix expression, which is then output.
The postfix expression is processed from left to right. Operands are PUSHed onto the stack. When an operator is encountered, two elements are POPped, the operator is applied to them, and the computed value is PUSHed back onto the stack. If the stack contains a single element at the end, it is POPped and output as the net result; otherwise the expression is invalid.
π Important Questions
1 Mark
- Define stack.
- What is LIFO?
- What is TOP?
- Define PUSH operation.
- Define POP operation.
- What is overflow?
- What is underflow?
- What is infix notation?
- What is prefix notation?
- What is postfix notation?
2 Marks
- Differentiate between PUSH and POP operations.
- Differentiate between overflow and underflow.
- Mention applications of stack in programming.
- Explain the use of a stack for matching parentheses.
- Explain the use of a stack in browser history.
3 Marks
- Explain the applications of stack.
- Explain Infix, Prefix and Postfix notations with examples.
- Explain how a stack is implemented using a Python list.
- Explain the role of stack in infix-to-postfix conversion.
4/5 Marks
- Write the functions required to implement a stack in Python.
- Write a program to implement the stack of glasses shown in the chapter.
- Explain Algorithm 3.1 for converting infix to postfix notation.
- Explain Algorithm 3.2 for evaluating postfix expressions.
- Show the stack-based evaluation process of the postfix expression given in the chapter.
- Write a program to reverse a string using stack.
β‘ Quick Revision
Important Definitions
- Data structure
- Linear data structure
- Stack
- TOP
- PUSH
- POP
- Overflow
- Underflow
Important Terms
- LIFO
- Stack
- PUSH
- POP
- Infix
- Prefix
- Postfix
- Polish notation
- Reverse Polish notation
Important Concepts
- Insertion and deletion occur at TOP.
- Stack follows LIFO.
- Python list can implement a stack.
append()is used for insertion.pop()is used for deletion.- Stack is used for infix-to-postfix conversion.
- Stack is used for postfix evaluation.
Important Differences
| Infix | Prefix | Postfix |
|---|---|---|
| Operator between operands | Operator before operands | Operator after operands |
x+y |
+xy |
xy+ |
Important Python Syntax
glassStack = list()
glassStack.append(element)
glassStack.pop()
len(glassStack)
Important Functions
isEmpty()opPush()size()top()opPop()display()
Important Applications
- Reversing a string
- Redo/undo editing
- Browser history
- Matching parentheses
Important Algorithms
- Algorithm 3.1 β Conversion from infix to postfix notation
- Algorithm 3.2 β Evaluation of postfix expression
π Final Revision Flow
π Textbook Exercise
The following questions are the exercise questions provided at the end of the uploaded chapter.
1. State TRUE or FALSE
- Stack is a linear data structure.
- Stack does not follow LIFO rule.
- PUSH operation may result into underflow condition.
- In POSTFIX notation for expression, operators are placed after operands.
2. Find the output of the following code
(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)
3. String Reversal
Write a program to reverse a string using stack.
4. Matching Parentheses
For the arithmetic expression below, show the step-by-step process for matching parentheses using stack data structure:
((2+3)*(4/2))+2
5. Evaluate Postfix Expressions
Evaluate the following postfix expressions while showing the status of the stack after each operation, given:
A=3, B=5, C=1, D=4
A B + C *A B * C / D *
6. Convert Infix to Postfix
Convert the following infix notations to postfix notations, showing stack and string contents at each step.
A + B - C * DA * (( C + D)/E)
7. Stack Program for Odd Numbers
Write a program to create a Stack for storing only odd numbers out of all the numbers entered by the user. Display the content of the Stack along with the largest odd number in the Stack.
π― Last-Minute Exam Revision
- Remember the definition of Stack.
- Remember LIFO and TOP.
- Learn PUSH and POP clearly.
- Do not confuse overflow and underflow.
- Remember Python list implementation using
append()andpop(). - Learn the functions
isEmpty(),opPush(),size(),top(),opPop()anddisplay(). - Revise Infix, Prefix and Postfix differences.
- Revise Algorithm 3.1.
- Revise Algorithm 3.2.
- Practice the textbook conversion and evaluation questions.
- Revise the textbook programs and their outputs.