IIPUCCSNEWA
IIPUCCSNEWA
II PUC
COMPUTER SCIENCE
Prepared by:
SANGAMESH. G. B
LECTURER IN COMPUTER SCIENCE
DEEKSHA @ NAVKIS RESIDENTIAL PU COLLEGE,
BANGALORE NORTH - 562162
CONTENTS
CHAPTER-03: STACK
CHAPTER-04: QUEUE
CHAPTER-05: SORTING
CHAPTER-06: SEARCHING
Government of Karnataka
Department of School Education (Pre-University)
II PUC Computer Science
Blue Print
Part Part Part Part Part
Chapter Description Hours A B C D E Total
VSA-01 VSA-01 SA-02 SA-03 E-05 E-05
[MCQ] [FIB] Marks Marks Marks Marks Marks
[LOTS] [HOTS]
Chapter-03 Stack 9 1 1 1 08
Chapter-04 Queue 9 1 1 1 08
Chapter-05 Sorting 12 2 1 1 10
Chapter-06 Searching 12 1 1 1 10
UNIT - A
PYTHON PROGRAMMING
Chapter-03: Stacks
Chapter-04: Queues
Chapter-05: Sorting
Chapter-06: Searching
CHAPTER – 01
EXCEPTION HANDLING IN PYTHON
In this chapter:
Introduction
Syntax Errors
Exceptions
Built-in Exceptions
Raising Exceptions
Finally Clause
1. Introduction:
Sometimes while executing python program, the program does not execute at all or the program
executes but generates unexpected output or behaves abnormally.
These occur when there are syntax errors, runtime errors or logical errors in the code.
In python, exceptions are errors that get triggered automatically. However, exceptions can be
forcefully triggered and handled through program code.
2. Syntax Errors:
Syntax errors are detected when we have not followed the rules or syntax of the particular
programming language while writing the program.
Syntax errors occurs before execution of program or parsing stage
Syntax errors are also known as parsing errors.
Programming Example:
Example-01:
def test ( ) :
marks=20
if marks>10:
print “GOOD SCORE”
SyntaxError X
X Missing parenthesis in call to ‘print’, Did you mean print ‘GOOD SCORE’
OK
On encountering a syntax error, Python stops execution until the error is corrected.
(The interpreter does not execute the program unless we rectify the errors, save and rerun the
program)
When syntax error is encountered, Python displays name of the error and a small description
about the error.
b. In Script mode:
A dialog box specifying the name of the error and a small description about the error
Example:
3. Exception:
An exception is a python object that represents an error that occurs during the execution of
program even if program is syntactically correct.
OR
In python, exceptions are errors that get triggered automatically. However, exceptions can be
forcefully triggered and handled through program code.
OR
Exceptions are unexpected events or errors that occurs while a program is running
When exception occurs, it is said to be raised and may disrupt the normal flow of program
execution.
The run time error is called an exception
This type of errors might disrupt the normal execution of the program and are called exceptions.
An exception needs to be handled by the exception handler or programmer so that the program
does not terminate abnormally.
Example:
result = 10 / 0
Exception: ZeroDivisionError
OR
Example:
a=10
b=int(input(“Enter the value for b=”))
print(a/b)
4. Types of exceptions:
a. Built-in exceptions
b. User defined exceptions
a. Built-in Exceptions:
These are commonly occurring exceptions, which are usually defined in the
compiler/interpreter.
There are several built-in exceptions in python that are raised when error occurs.
These built-in exceptions will display the exact reasons of errors along with the raised exception
name.
The programmer then has to take appropriate action to handle it.
Built-in Exceptions:
Built-in exceptions are pre-defined errors in Python to handle common runtime errors.
[Link] Built-in Exceptions Explanation
01 SyntaxError It is raised when there is error in syntax of program (Python code)
02 ValueError It is raised when there is wrong value for the data type
OR
It is raised when a built-in operation receives an argument that the
right data type but mismatched or inappropriate values.
03 IOError It is raised when the file specified in a program statement cannot be
opened
04 KeyboardInterrupt It is raised when user accidentally click the Delete or Escape key
05 ImportError It is raised when the requested module definition is not opened or
found
06 EOFError It is raised when the end of file condition is reached without reading
any data by input().
07 ZeroDivisionError It is raised when denominator in a division operation is zero
08 IndexError It is raised when the index or subscript in a sequence is out of range
09 NameError It is raised when local or global variable name is not defined
10 IndentationError It is raised due to incorrect indentation in the program code
11 TypeError It is raised when an operator is supplied with a value of incorrect
data type
12 OverFlowError It is raised when the result of a calculation exceeds the maximum
limit for numeric data type.
5. Raising Exceptions:
When error is detected in a program, the python interpreter raises (throws) an exception
The exception handlers are designed to execute when a specific exception is raised
The programmers can also forcefully raise exceptions in a program using raise and assert
statement
Syntax:
raise exception-name[(optional argument)]
Example:
exception(“OOPs! Error Occurred”)
- The argument is optional and generally a string that is displayed when an exception is
raised.
- When an exception is raised, the message:
“OOPS : An exception has occurred” is displayed along with a brief description of error
- The error detected may be a built-in exception or may be a user-defined exception.
- This displays the message and a stack traceback showing the function calls leading to the
exception
- Programming example
Example-01:
a=20
b=int(input("Enter the b value: "))
if b==0:
raise ZeroDivisionError("Cannot divide by zero")
else:
print(a/b)
Output:
Enter the b value: 0
Traceback (most recent call last):
File "C:\Users\Admin\[Link]", line 4, in <module>
raise ZeroDivisionError("Cannot divide by zero")
ZeroDivisionError: Cannot divide by zero
Example-02:
length=int(input("Enter the number="))
if length>10:
raise IndexError("Index length is only 10")
print("Length is larger than 10")
else:
print("No error, Length is less than 10")
Output:
Enter the number=15
Traceback (most recent call last):
File "C:\Users\Admin\[Link]", line 3, in <module>
raise IndexError("Index length is only 10")
IndexError: Index length is only 10
b. Assert Statement:
The assert statement is used to test an expression or condition in the program code.
- Using the keyword assert
If the result after testing comes false, then the exception (Assertion Error) is raised.
This assert statement is generally used in the beginning of the function or after the function
call to check for valid input
Syntax:
assert Expression[, arguments]
Example-01:
Output:
Enter the numerator:20
Enter the denominator:0
Traceback (most recent call last):
File "C:/Users/Admin/[Link]", line 3, in <module>
assert num2!=0 ,("Denominator cannot be zero")
AssertionError: Denominator cannot be zero
Example-02:
print("Use of assert statement")
def negativecheck(number):
assert(number>=0), "OOPS... Negative Number"
print("The number is",number)
print(negativecheck(100))
print(negativecheck(-350))
Output:
Use of assert statement
The number is 100
None
AssertionError: OOPS... Negative Number
6. Exception Handling:
It is the process of writing additional code in a program to give proper messages or instructions to
the user on encountering an exception.
Each and every exception has to be handled by the programmer to avoid the program crashing
abruptly.
In python, exceptions are handled or implemented by using try and except, else and finally
blocks
OR
When an error occurs, Python interpreter creates an object called the exception object.
This object contains information about the error like its type, file name and position in the
program where the error has occurred.
The object is handed over to the runtime system to find an appropriate code to handle this
particular exception.
This process of creating an exception object and handing it over to the runtime system is called
throwing an exception.
When an exception occurs while executing a particular program statement, the control jumps to
an exception handler, abandoning the execution of the remaining program statements
The runtime system searches the entire program for a block of code, called the exception
handler that can handle the raised exception.
The runtime system first searches the method in which the error occurred and the exception was
raised. If not found, it searches the method from which this method was called.
This hierarchical search in reverse order continues until the exception handler is found.
This entire list of methods is known as the call stack.
When a suitable handler is found in the call stack, it is executed by the runtime process.
If the runtime system cannot find an appropriate exception after searching all the methods in the
call stack, then the program execution stops.
OR
a. Throwing an exception:
The process of creating an exception object and handling it over to the run time system is called
throwing an exception. (When an error occurs, Python creates an exception object and transfers
control to the runtime system
Each time an error is detected in a program, the python interpreter raises (throws) an exception.
Exception handlers are designed to execute when a specific exception is raised
Programmers can also forcefully raise exceptions in a program using raise and assert statements
Once an exception is raised, no further statement in the block of code is executed.
Syntax:
raise nameerror
assert condition, “Message”
d. Handling Exceptions: The matched handler executes specific code to resolve the error.
Programming Example:
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Division by zero is not allowed.")
except ValueError:
print("Invalid input! Please enter an integer.")
How it works:
In the execution of the program, if an exception is encountered (raised) then the try block
execution is stopped and the control is shifted to except block, where we can handle the error or
take appropriate actions.
a. try: The try block contains the code that might raise an exception
b. except: The except block contains the code to handle the exception.
Syntax:
try:
# code that might raise an exception
except [exception_name]:
# code to handle the exception
Example:
print("catching exceptions using try and except blocks")
try:
n=50
d=int(input("Enter the denominator="))
quotient=(n/d)
print(quotient)
print("Division is performed successfully")
except ZeroDivisionError:
print("Denominator as Zero...not allowed")
print("Outside try…except block")
OR
Q. Explain catching exception use of try… and except block with suitable example
Ans:
A try...except block is used to catch and handle exceptions in Python.
- try block: Contains code that might raise an exception.
- except block: Contains code to handle specific exceptions.
Syntax:
try:
# code that might raise an exception
except [exception_name]:
# code to handle the exception
Example:
try:
result = 5 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
In the code, two types of exceptions – ZeroDivisonError and ValueError are handled using two
excepts blocks for a single try block
When an exception is raised, a search for the matching except block is made till it is handled.
If no match is found, then the program terminates
Example-01:
print("use of multiple except blocks")
try:
n=50
d=int(input("Enter the denominator="))
quotient=(n/d)
print(quotient)
print("Division is performed successfully")
except ZeroDivisionError:
print("Denominator as Zero...not allowed")
except ValueError:
print("only Integer should be entered")
Output-01:
use of multiple except blocks
Enter the denominator=12
4.166666666666667
Division is performed successfully
Example-01:
print("use of except without specfiying any exception")
try:
n=50
d=int(input("Enter the denominator="))
quotient=(n/d)
print(quotient)
print("Division is performed successfully")
except ZeroDivisionError:
print("Denominator as Zero...not allowed")
except:
print("OOPS... Some exception raised")
Example:
Output:
handling exception using try...except.... else block
Enter the denominator=4
Division is performed successfully
The result of division operation is 12.5
Syntax:
try:
# code that may raise an exception
except [exception_name]:
# code to handle exception]
else:
# if there is no exception then this block get executed
finally:
# code will always be executed
Example-01:
print("handling exception using try...except.... else...finally")
try:
n=50
d=int(input("Enter the denominator="))
quotient=(n/d)
print("Division is performed successfully")
except ZeroDivisionError:
print("Denominator as Zero...not allowed")
except valueError:
print("Only Integer should be entered")
else:
print("The result of division operation is",quotient)
finally:
print("Over and Out... ")
Output-01:
handling exception using try...except.... else...finally
Enter the denominator=4
Division is performed successfully
The result of division operation is 12.5
Over and Out...
Example-01:
print("practicing for try block")
try:
n=50
d=int(input("Enter the denominator="))
quotient=(n/d)
print("Division is performed successfully")
except ZeroDivisionError:
print("Denominator as Zero...not allowed")
else:
print("The result of division operation is",quotient)
finally:
print("Over and Out... ")
Output-01:
Review Questions:
1. “Every syntax error is an exception but every exception cannot be a syntax error.” Justify the
statement.
Syntax is a specific type of exception that is detected when we have not followed the rules or
syntax of the particular programming language while writing the program. On the other hand,
An exception is a python object that represents an error that occurs during the execution of
program even if program is syntactically correct. This includes not only syntax error but also
runtime errors or logical errors.
Therefore, every syntax error is an exception but every exception cannot be a syntax error.”
OR
Syntax errors are mistakes in the code’s structure or grammar, such as missing colons or incorrect
indentation, which prevent the code from being parsed. They are caught before the program runs
and must be fixed for the program to execute.
Exceptions, on the other hand, occur during the execution of syntactically correct code when
something unexpected happens, like trying to divide by zero. Thus, while all syntax errors are
exceptions (as they represent issues to be corrected), not all exceptions are syntax errors; some are
runtime issues that arise despite correct syntax.
OR
Syntax Errors:
• Occur when the code violates Python’s grammatical rules.
• Detected before the program runs (parsing stage).
• Examples: Missing colons, improper indentation.
Exceptions:
• Occur during runtime when the code encounters an error.
• Can be handled using exception handling mechanisms.
• Examples: Division by zero, file not found
5. When are the following built-in exceptions raised? Give examples to support your answer
a. ImportError
b. IOError
c. NameError
d. ZeroDivisionError
a. ImportError:
It is raised when the requested module definition is not opened.
Example:
import module
Output:
ModuleNotFoundError: No module named ‘module’
b. IOError:
It is raised when the file specified in a program statement cannot be opened
Example:
File = open (“[Link]”, “r”)
Output:
FileNotFoundError: [Error 2] No such file or directory: “[Link]’
c. NameError:
It is raised when local or global variable is not defined
Example:
Print(var+40)
Output:
NameError: name ‘var’ is not defined.
d. ZeroDivisionError:
It is raised when denominator in a division operation is zero
Example:
Print(50/0)
Output:
ZeroDivisionError: division by zero
Built-in exceptions are pre-defined errors in Python to handle common runtime errors.
[Built-in exceptions are pre-defined errors in Python’s standard library that handle common
runtime issues.]
Exception When it Occurs Example
ZeroDivisionError Raised when Dividing a number by 10 / 0
zero
ValueError Raised when there is wrong value int("abc")
for the data type
NameError Raised when referencing a variable print(x) (where x is undefined).
that is not defined
IndexError Raised when accessing an invalid lst = [1,2];
index in a sequence print(lst[5])
TypeError Raised when an operation is 5 + "hello"
performed on incompatible types Adding a string and an integer
(Operation is applied to an
incorrect data type)
a. Exception Handling
It is the process of writing additional code in a program to give proper messages or
instructions to the user on encountering an exception
b. Throwing an exception
The process of creating an exception object and handling it over to the run time system is
called throwing an exception. (The process where Python creates an exception object when an
error occurs and passes it to the runtime system)
c. Catching an exception
An exception is said to be caught when a code that is designed to handle a particular exception
is executed (Catching an exception means raising an exception)
OR
The process of executing the appropriate exception handler to deal with the raised exception
a. Exception handler: Exception handlers are the codes that are designed to execute when a
specific execution is raised.
[A block of code written to handle errors in a program and prevent it from crashing]
b. Try block: The try block contains code that might raise an exception
c. Except block: The except block contains code to handle the exception
(An exception is caught is try block and handles in except block)
d. Else block: The else block executes only if no exception occurs in the try block.
e. Finally block: The finally block are always executed regardless of whether an exception
occurred in try block or not
f. Multiple except: Multiple except blocks handles different exception types separately
g. Raise statement: The raise statement can be used to throw or raise an exception manually.
(Using the Keyword- raise).
h. Assert statement: The assert statement is used to test an expression in the program code.
(Using the keyword assert)
11. Consider the code given below and fill in the blanks.
Example-01:
print("Learning exceptions")
try:
num1=int(input(“Enter the first number=”))
num2=int(input(“Enter the second number=”))
quotient=(num1/num2)
print("Both the number entered were correct”)
except ____________________ : # to enter only integers
print("Please enter only numbers")
except _____________________: # Denominator should not be zero
print(“Number 2 should not be zero)
else:
print("Great…you are a good programmer”)
___________________________: #To be executed at the end
print("JOB OVER…GO GET SOME REST")
Output:
print("Learning exceptions")
try:
num1=int(input(“Enter the first number=”))
num2=int(input(“Enter the second number=”))
quotient=(num1/num2)
print("Both the number entered were correct”)
except ValueError: # to enter only integers
print("Please enter only numbers")
except ZeroDivisionError: # Denominator should not be zero
print(“Number 2 should not be zero)
else:
print("Great…you are a good programmer”)
finally: #To be executed at the end
print("JOB OVER…GO GET SOME REST")
12. What is the use of finally clause ? Use finally clause in the problem given in question-7
Example-01:
print("Learning exceptions")
try:
num1=int(input(“Enter the first number=”))
num2=int(input(“Enter the second number=”))
quotient=(num1/num2)
print("Both the number entered were correct”)
except ____________________ : # to enter only integers
print("Please enter only numbers")
except _____________________: # Denominator should not be zero
print(“Number 2 should not be zero)
else:
print("Great…you are a good programmer”)
___________________________: #To be executed at the end
print("JOB OVER…GO GET SOME REST")
Output-01:
Learning exceptions
try:
Enter the first number=12
Enter the second number=4
3.0
Both the number entered were correct
JOB OVER…GO GET SOME REST
Output-02:
Learning exceptions
try:
Enter the first number=var
Please enter only numbers
JOB OVER…GO GET SOME REST
Output-03:
Learning exceptions
try:
Enter the first number=33
Enter the second number=0
Number 2 should not be zero
JOB OVER…GO GET SOME REST
13. Write a code using the math module where you use the wrong number of arguments for a method
and handle the ValueError exception.
Answer:
import math
try:
result = [Link](16, 2) # Incorrect number of arguments
except TypeError:
print("Incorrect number of arguments provided to sqrt() method")
15. How are exceptions raised and caught in Python? Explain the call stack.
Answer:
- Raising Exceptions: Python raises exceptions when runtime errors occur (e.g., dividing by zero).
Programmers can raise exceptions manually using the raise statement.
- Catching Exceptions: Exceptions are handled using try...except blocks. Python matches the
exception type with available handlers.
Call Stack:
The call stack is a sequence of function calls made during execution. If an exception is raised,
Python searches the call stack for a matching handler. If no handler is found, the program
terminates with a traceback.
16. Explain the else clause in Python exception handling with an example.
Answer:
The else clause executes only if no exception occurs in the try block.
OR
If there is no exceptions raised from the try block then code inside the try block will be executed
and also else block will be executed:
Example:
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print(f"Division successful: {result}")
44. Which exception is raised if the following code is executed and the input is abc?
try:
num = int(input("Enter a number: "))
except ValueError:
print("Invalid input!")
a) ValueError b) TypeError c) SyntaxError d) NameError
45. What does exception handling ensure?
a) Errors are ignored b) Code runs faster
c) Program does not crash abruptly d) Syntax errors are corrected automatically
46. What is the primary benefit of a try…finally structure?
a) Better syntax b) Clean termination or recovery
c) Handling specific exceptions d) Ignoring runtime errors
47. What exception is raised if input() encounters EOF?
a) ValueError b) EOFError c) TypeError d) SyntaxError
48. When is the OverFlowError raised?
a) A file cannot be opened
b) Division by zero occurs
c) A calculation exceeds the max limit for a numeric type
d) An undefined variable is accessed
49. What is the process of finding an exception handler called?
a) Raising an exception b) Catching an exception
c) Searching the call stack d) None of the above
50. What happens when an exception is successfully caught?
a) It propagates b) Execution terminates
c) Control resumes after the try block d) None of the above
51. The exception is raised when the requested module definition is not found
a) io error b) Syntax error c) import error d) index error
52. Given Q=N/D, if D=0 and N=50, which built-in exception occur?
a) Syntax Error b) Index Error c) Value Error d) ZeroDivisionError
53. The exception raised when the local or global variable is not defined is
a) Import Error b) TypeError c) ValueError d) NameError
54. What is the primary purpose of the assert statement in Python?
a) To catch exceptions during program execution
b) To define functions for debugging
c) To Test if a condition is True and raise an exception if it is True
d) To handle error in user input
55. Why should exceptions be handled in Python?
a) To ensure that errors are ignored b) To make program run faster
c) To avoid the program crashing abruptly d) To execute the program without error
1. A ________ error occurs when the rules of the programming language are not followed.
Answer: Syntax
2. Errors that occur during program execution and disrupt its normal flow are called ________.
Answer: Exceptions
3. The ________ block in Python is used to catch exceptions and handle them appropriately.
Answer: except
4. A division by zero operation raises the ________ exception.
Answer: ZeroDivisionError
5. The ________ exception is raised when a variable is referenced but has not been defined.
Answer: NameError
6. The Python statement used to manually raise an exception is ________.
Answer: raise
7. A ________ block is always executed, regardless of whether an exception occurred or not.
Answer: finally
8. The ________ exception occurs when the file specified in a program cannot be opened.
Answer: IOError
9. The process of identifying and handling exceptions is called ________.
Answer: Exception handling
10. The ________ statement is used in Python to test conditions and raise an AssertionError if
the condition evaluates to False.
Answer: assert
11. A block of code suspected to raise exceptions is enclosed within a ________ block.
Answer: try
12. A(n) ________ exception can be created by programmers to handle specific errors not covered
by built-in exceptions.
Answer: user-defined
13. The exception raised when an input operation hits the end of the file without reading any
data is ________.
Answer: EOFError
14. Python provides a structured block of text, known as ________, that contains information
about the sequence of function calls during an exception.
Answer: traceback
15. The ________ clause in Python is executed only if the try block completes successfully without
any exceptions.
Answer: else
16. A(n) ________ exception is raised when an invalid value is passed to a built-in method or
operation.
Answer: ValueError
17. The exception raised due to incorrect indentation in Python is ________.
`Answer: IndentationError
18. The Python runtime system searches the ________ to find an appropriate handler for the
raised exception.
Answer: call stack
19. A(n) ________ exception occurs when an index is out of the valid range of a sequence.
Answer: IndexError
20. The process of identifying a suitable handler for a raised exception is called ________ the
exception.
Answer: catching
21. The exception raised when the requested module is not found is ________.
Answer: ImportError
22. The exception raised when a key is not found in a dictionary is ________.
Answer: KeyError
23. The exception raised when a calculation exceeds the maximum limit for a numeric type is
________.
Answer: OverflowError
24. The ________ block is placed after a try block to handle multiple exceptions using separate
handlers.
Answer: except
25. When no specific handler is defined for an exception, a generic ________ block can be used.
Answer: except
26. The exception raised when the user presses an interrupt key like Ctrl+C is ________.
Answer: KeyboardInterrupt
27. The method or block of code responsible for responding to a specific type of exception is called
a(n) ________.
Answer: exception handler
28. Python’s standard library includes numerous ________ exceptions to handle commonly
occurring errors.
Answer: built-in
29. When an exception occurs, the normal flow of the program is ________.
Answer: interrupted
30. The try block is mandatory when using the ________ clause in Python exception handling.
Answer: except
CHAPTER – 02
FILE HANDLING IN PYTHON
In this chapter:
Introduction to Files
Types of Files
Opening and Closing a Text File
Writing to a Text File
Reading from a Text File
Setting Offsets in a File
Creating and Traversing a Text File
The Pickle Module
1. Introduction
File handling refers to the process of performing operations on a file such as creating, opening,
reading, writing and closing it, through a programming interface. It involves managing the data
flow between the program and the file system on the storage device, ensuring that data is
handled safely and efficiently.
In Python, data stored in variables is temporary and disappears after the program ends.
To store data permanently, we use files, which are saved on secondary storage (e.g., hard
disks).
Files allow us to store inputs, outputs, and objects for later use.
A Python file (source code) is saved with a .py extension
2. File
A file is a named location on a secondary storage media, where data are permanently stored for
later access.
Types of files:
i. Text file
ii. Binary file
i. Text file:
[Link] is a file that stores information in the form of ASCII, UNICODE characters.
[Link] contains sequence of characters, consisting of alphabets, numbers and other special symbols.
[Link] is in human readable or understandable form
[Link] files can be opened and edited using any text editor (Ex: Notepad).
[Link] with extensions like .txt, .py, .csv, .doc etc. are examples of text files
[Link] line of a text file is terminated by a special character, called End of Line (EOL) or
Delimiters
g. In this file, certain internal translation takes place
h. The default EOL character in python is newline (\n)
i. The contents in the text file are usually separated by whitespace, but comma (,) and tab (\t) are
also commonly used to separate values in a text file.
Example:
The ASCII value of 'A' is 65 → Binary: 1000001
Example-1:
myobject=open (“[Link]”, “r+”)
Example-2:
myobject=open (“[Link]”, “a”)
This function returns a file object called file handle which is stored in the variable
file_object.
Example:
with open (“myfile”, “r+”) as myobject :
The advantage of using with clause is that any file that is opened using this clause is closed
automatically, once the control comes outside the with clause.
In case the user forgets to close the file explicitly or if an exception occurs, the file is closed
automatically.
5. Access Modes:
The access mode is an optional argument that represents the mode in which the file has to be
accessed by the program. It is also referred to as processing mode.
Examples:
myobject = open("[Link]", "r")
myobject = open("[Link]", "r+")
myobject = open("[Link]", "a+")
Syntax:
file_object.write(string)
Syntax:
file_object.writelines(list_of_strings)
Example:
myobject=open(“myfi [Link]”,‘w’)
lines = [“Hello everyone\n”, “I have offered Computer Science\n”, “Learning Python
programming”]
[Link](lines)
[Link]()
Syntax-01: read(n)
file_object.read(n)
Syntax-02: read()
file_object.read()
Syntax:
file_object.readline(n)
Example: readline(n)
myobject = open("[Link]", 'r')
print([Link](10))
[Link]()
Syntax:
file_object.readlines( )
Example: readlines(n)
myobject = open("[Link]", 'r')
print([Link]( ))
[Link]()
Output:
[“Hello everyone\n”, “ I have offered Computer Science\n”, “Learning Python language”]
a. Split ( ):
This method is used to splits each line into list of words separately from the text file.
Example:
for line in d:
words = [Link]()
print(words)
Output:
[‘Hello’, ‘ everyone’]
[‘I’. ‘have’, ‘offered’, ‘Computer’,’ Science’]
[‘Learning’, ‘ Python’, ‘language’]
b. Splitlines ( ):
This method is used to split a string into a list of lines from the text file.
Example:
for line in d:
words = [Link]()
print(words)
Output:
[‘Hello everyone’]
[‘I have offered Computer Science’]
[‘Learning Python language’]
a. tell( ):
This method returns an integer that specifies the current position of the file object in the file.
Syntax:
file_object.tell()
Example:
[Link]()
b. seek( ):
This method is used to position the file object at a particular position in a file
Syntax:
file_object.seek(offset [, reference_point] )
Example:
[Link](5, 0) # Move to 5th byte from start
• Moves pointer to specified position from reference point (0 = start, 1 = current, 2 = end).
• Moves pointer to specified position.
tell(): It returns the current position of the file object in bytes from beginning
seek():To move the file object to a specific position in a file.
Example:
fileobject=open(“[Link]”, “w+”)
Example:
fileobject=open(“[Link]”, “r”)
Serialization (pickling):
It is the process of converting python objects into byte stream to store in a binary file.
- Using a [Link]( )
Deserialization (unpickling):
It is the process of converting byte stream to python object. (Reverse process of pickling)
- Using a [Link]( )
a. dump( ) method:
This method is used for serializing (Pickling) and writing the python objects into a binary file.
The file in which data to be dumped should open with binary write mode (wb).
Syntax;
[Link](data_object, file_object)
Example:
import pickle
listvalues = [1, "Geetika", 'F', 26]
fileobject = open("[Link]", "wb")
[Link](listvalues, fileobject)
[Link]()
b. load( ) method:
This method is used for deserializing (unpickling) and reading the python objects from a
binary file.
The file to be loaded should be open in binary read mode (rb).
Syntax;
variable = [Link](file_object)
Example-01:
import pickle
print(“The data that were stored in file are:”)
fileobject=open(“[Link]”,”rb”)
objectvar=[Link](fileobject)
[Link]( )
print(objectvar)
Example-02:
fileobject = open("[Link]", "rb")
objectvar = [Link](fileobject)
[Link]()
print(objectvar)
import pickle
while True:
print("[Link] Binary file, [Link] the file, [Link]")
a=int(input("choose a command 1-2-3-exit:"))
if a==1:
f=open("[Link]","wb")
x=int(input("how many students:"))
for i in range(x):
name=input("Name:")
english=int(input("English marks:"))
lang=int(input("Language marks:"))
phy=int(input("physics marks:"))
chem=int(input("Chemistry marks:"))
maths=int(input("maths marks:"))
cs=int(input("cs marks:"))
t=[name,english,lang,phy,chem,maths,cs]
[Link](t,f)
[Link]()
elif a==2:
f=open("[Link]","rb")
try:
while True:
p=[Link](f)
print(p)
except:
[Link]()
11. Exercise:
1. Explain in detail the various file opening modes with their file pointer positions and suitable
use cases
Mode Use Case Pointer Position
“r” Read existing files Beginning of the file
“w” Create/overwrite files Beginning of the file
“r+” or “+r” Read/write existing files Beginning of the file
“w+” or “+w” Create/overwrite with read Beginning of the file
capability
“b” Binary mode suffix: Beginning of the file
Ex: “rb” , “wb”
“a” Append to existing files End of the file
“a+” or “+a” Append with read capability End of the file
2. Explain the complete file handling process in Python with proper syntax and examples for
each step.
The file handling process in Python:
• Opening: file = open("[Link]", "r") or with open("[Link]", "w") as file:
• Writing: [Link]("Content") or [Link](["Line1\n", "Line2\n"])
• Reading: content = [Link]() or lines = [Link]()
• Positioning: pos = [Link]() and [Link](offset)
• Closing: [Link]() (automatic in with statement)
• Example:
with open("[Link]", "w+") as f:
[Link]("Sample text\n")
[Link](0)
print([Link]())
3. Compare and contrast text files and binary files with respect to: storage format, readability,
extensions, and use cases.
Ans:
• Storage Format: Text uses ASCII/Unicode; Binary uses raw bytes
• Readability: Text is human-readable; Binary requires special programs
• Extensions: Text (.txt, .py); Binary (.dat, .jpg)
• Use Cases: Text for configuration/data; Binary for media/executables
• Example:
# Text file operation
with open("[Link]", "w") as f:
[Link]("Hello")
4. Explain the file object attributes and methods with suitable examples for each. Answer:
• Attributes:
– name: print([Link]) # Shows filename
– mode: print([Link]) # Shows access mode
– closed: print([Link]) # True/False
• Methods:
– read(): content = [Link](10) # First 10 bytes
– seek(): [Link](5) # Move to 5th byte
– tell(): pos = [Link]() # Current position
– flush(): [Link]() # Force write to disk
5. Create a comprehensive program that demonstrates all file object methods (read, write,
seek, tell, flush) with proper documentation.
Answer:
# Demonstrate all key file methods
# FLUSH
[Link]() # Force write to disk
# SEEK
[Link](0) # Rewind to start
print(f"After seek(0) - Position: {[Link]()}") # 0
# READ
content = [Link](10) # First 10 chars
print(f"Partial read: {content}")
print(f"After read(10) - Position: {[Link]()}") # 10
# READLINE
[Link](0)
print("Full content:")
while True:
line = [Link]()
if not line: break
print([Link]())
6. Write a program to accept string/sentences from the user till the user enters “END”.
Save the data in a text file and then display only those sentences which begin with an
uppercase alphabet.
Answer:
with open("[Link]", "w") as f:
while True:
line = input("Enter sentence (END to stop): ")
if line == "END": break
[Link](line + "\n")
Answer:
import pickle
# Writing records
with open("[Link]", "wb") as f:
while True:
item_no = int(input("Enter Item No (0 to stop): "))
if item_no == 0: break
name = input("Item Name: ")
qty = int(input("Quantity: "))
price = float(input("Price: "))
[Link]([item_no, name, qty, price], f)
# Reading records
with open("[Link]", "rb") as f:
while True:
try:
item = [Link](f)
print(f"\nItem No: {item[0]}")
print(f"Item Name: {item[1]}")
print(f"Quantity: {item[2]}")
print(f"Price per item: {item[3]}")
print(f"Amount: {item[2] * item[3]}")
except EOFError:
break
1. A file is a named location on ________ storage media where data is permanently stored.
Answer: secondary
2. The two main types of files are ________ files and binary files.
Answer: text
3. Text files store data using ________ or Unicode encoding schemes.
Answer: ASCII
4. The default End of Line (EOL) character in Python is ________.
Answer: \n
5. Binary files store data in ________ format that is not human-readable.
Answer: byte
6. The ________ function is used to open a file in Python.
Answer: open()
7. The default file opening mode is ________.
Answer: ‘r’ (read mode)
8. To open a file for both reading and writing, we use ________ mode.
Answer: ‘r+’
9. The ________ method returns the current position of the file pointer.
Answer: tell()
10. To move the file pointer to a specific position, we use the ________ method.
Answer: seek()
11. The ________ clause automatically closes the file when the block ends.
Answer: with
12. The ________ method writes a single string to a file.
Answer: write()
13. The ________ method writes multiple strings from an iterable to a file.
Answer: writelines()
14. To read a specified number of bytes from a file, we use the ________ method.
Answer: read()
15. The ________ method reads one complete line from a file.
Answer: readline()
16. The ________ method reads all lines and returns them as a list.
Answer: readlines()
17. The ________ module is used for serializing and deserializing Python objects.
Answer: pickle
18. The ________ method converts Python objects to byte streams for storage.
Answer: dump()
19. The ________ method loads Python objects from binary files.
Answer: load()
20. Files opened in ________ mode will overwrite existing content.
Answer: ‘w’
21. The ________ mode allows appending data to the end of an existing file.
Answer: ‘a’
22. The ________ attribute returns True if a file is closed.
Answer: closed
23. The ________ attribute returns the name of the file.
Answer: name
24. The ________ method forces writing of buffered data to the file.
Answer: flush()
25. To handle non-text data like images, we open files in ________ mode.
Answer: binary (‘b’)
26. The ________ exception occurs when trying to read past EOF in pickle.
Answer: EOFError
27. The ________ method splits strings at whitespace by default.
Answer: split()
28. The ________ method splits strings at line boundaries.
Answer: splitlines()
29. In file operations, ________ refers to converting objects to byte streams.
Answer: serialization
30. The ________ function converts numbers to strings before file writing.
Answer: str()
CHAPTER – 03
STACK
In this chapter:
Introduction
Stack
Operations on Stack
Implementation of Stack in Python
Notations for Arithmetic Expressions
Conversion from Infix to Postfix Notation
Evaluation of Postfix Expression
1. What is a data structure?
A data structure is a specialized format for organizing and storing the data.
Examples: String, List, Set, Tuple. Array, Linked Lists, Stack, Queue, Trees, Graphs, etc.
2. What is a stack?
A Stack is a linear data structure where elements are inserted and deleted from same end (TOP).
This end is commonly referred as “TOP”
6. Operations of Stack
The operations performed on stack are:
a. PUSH( )
Overflow( )
b. POP( )
Underflow( )
c. isEmpty( )
d. isFull( )
e. Peek( )
f. Size( )
# PUSH operation
def opPush(glassStack, element):
[Link](element)
Sample Program:
glassStack = list() # create empty stack
element = 'glass1'
print("Pushing element", element)
opPush(glassStack, element)
element = 'glass2'
print("Pushing element", element)
opPush(glassStack, element)
element = opPop(glassStack)
print("Popped element is", element)
element = 'glass3'
print("Pushing element", element)
opPush(glassStack, element)
a. Infix:
Operators are placed between the operands.
Infix rule BODMAS
Examples:
x+y
x*y+z
3 * (4 + 5)
(x + y) / (z + 5)
(a - b) * c
b. Prefix:
Operators are placed before the corresponding operands.
Examples:
+xy
+*xyz
* 3+45
/+xy*z5
*-abc
c. Postfix:
Operators are placed after the corresponding operands.
Examples:
xy+
xy*z+
345+*
xy+z5*/
ab-c*
Example: (x + y) / (z * 8 )
OR
Example: (x + y) / (z * 8) → xy+z8/
Example-02:
Convert the following infix notation A + B – C * D to Postfix notation Showing stack and string
contents at each steps
Solution:
Symbol: A + B -
Action: Append Push Append Pop
Initial
stack
Empty + + -
Postfix A A AB AB+
String(PostExp)
Symbol: C * D -
Action: Append Push Append pop
* *
- - -
Example-03:
Convert the following infix notation 8 * ( 3 + 5 ) to Postfix notation Showing stack and string
contents at each steps
Solution:
Symbol: 8 * ( 3
Action: Append Push Push Append
Initial
stack ( (
Empty * * *
Postfix 8 8 * 83
String(PostExp)
Symbol: + 5 )
Action: Push Append Pop
+ +
( (
* *
Example-04
Q, Conversion of Infix to postfix: (p+q) / r*3
Symbol Stack Postfix
( (
p ( p
+ (+ p
q (+ pq
) pq+
/ / pq+r
r / pq+r/
* * pq+r/3
3 * pq+r/3*
Example-05
Q. Conversion of Infix to postfix: A+B-C*D
Symbol Stack Postfix
A A
+ + A
B + AB
- - AB+
C - AB+C
* -* AB+C
D -* AB+CD
End AB+CD*-
Example-06
Q. Conversion of Infix to postfix: (a + (b * c) / (d – e) ) = abc*de-/+
Symbol Stack Postfix
( ( Empty
a ( a
+ (+ a
( (+( a
b (+( ab
* (+(* ab
c (+(* abc
) (+ abc*
/ (+/ abc*
( (+/( abc*
d (+/( abc*d
- (+/(- abc*d
e (+/(- abc*de
) (+/ abc*de-
) Empty abc*d-/+
OR
Algorithm: Evaluation of Postfix expression
Step-1: For each character in postfix expression:
* If operand → PUSH to stack
* If operator → POP two operands, apply operation, PUSH result
Step-2: At the end, if one item in stack → Result
Step-3: Else → Invalid expression
Example: 7 8 2 * 4 / + Result 11
Q. What is the role of a stack in evaluating a postfix expression? Explain the process with steps.
To evaluate a postfix expression using stack:
1. Read the postfix expression left to right.
2. If an operand is encountered, push it onto the stack.
3. If an operator is encountered, pop two elements, apply the operator, and push the result back.
4. After processing, the final result will be the only value remaining in the stack.
Examples:
Evaluation of postfix expression
Expression: 7 4 -3 * 1 5 + / *
Example-01:
Q. Evaluate Postfix expression: 7 8 2 * 4 / +
Example-02:
Give a step-by-step evaluation of the postfix expression: A B * C / D *
Where A=3, B=5, C=1. D=4
Solution: Given Postfix expression: A B * C / D *
Substitute the value: A=3, B=5, C=1, D=4; Then the expression becomes: 3 5 * 1 / 4 *
Symbol: 3 5 * 1
Action: Push Push Pop Push
Initial
Stack 5 1
Empty 3 3 15 15
Final
4 Stack
15 15 60 Empty
The Result is 60
Example-03:
Evaluate Postfix expression: 7 4 -3 * 1 5 + / *
Solution:
Symbol: 7 4 -3 *
Action: Push Push Push Pop
Initial -3
stack 4 4 -12
Empty 7 7 7 7
Symbol: 1 5 + /
Action: Push Push Pop Pop
5
1 1 6
-12 -12 -12 -2
7 7 7 7
Final
-14 Empty
Stack
9. Convert the following infix notations to postfix notations. Show stack and string contents at
each
Examples:
a. A + B - C * D
Postfix: AB+CD*-
b. A * ((C + D)/E)
Postfix: ACD+E/*
c. (A + B) * C
Postfix: AB+C*
d. A+B-C
Postfix: AB+C-
e. (A + B) / (X – Y)
Postfix: AB+XY-/
A^B*C-D
f. Postfix: AB^C*D-
CHAPTER – 04
QUEUE
In this chapter:
Introduction to Queue
Operations on Queue
Implementation of Queue using Python
Introduction to Deque
Implementation of Deque using Python
1. What is a data structure?
A data structure is a specialized format for organizing and storing the data.
Examples: String, List, Set, Tuple. Array, Linked Lists, Stack, Queue, Trees, Graphs, etc.
2. What is a Queue?
A Queue is a linear data structure where elements are inserted and deleted from different ends.
5. Operations of Queue
The operations performed on Queue are:
a. Enqueue( )
b. Dequeue( )
c. isEmpty( )
d. isFull( )
e. Peek( )
f. Size( )
enqueue('Z') → Z
enqueue('X') → Z X
enqueue('C') → Z X C
dequeue( ) → X C
enqueue('V') → X C V
dequeue( ) → CV
dequeue( ) →V
Enqueue(Z) F Z R
Enqueue(X) F Z X R
Enqueue(C) F Z X C R
Dequeue( ) F X C R
Enqueue(V) F X C V R
Dequeue( ) F C V R
Dequeue F V R
Enqueue(C) [ Z, X, C ]
Dequeue( ) [ X, C ]
Dequeue( ) [C]
Dequeue( ) []
Note: The append( ) function always adds an element at the end of the list. Hence Rear of the
queue
Programming Example:
Output:
a) InsertFront( ): It is used to add new element into the deque at Front end
b) InsertRear( ): It is used to add new element into the deque at Rear end. (Same as normal queue)
c) DeletionFront( ): It is used to delete an element from deque from Front end (same as normal
Quque)
d) DeletionRear( ): It is used to delete an element from deque from Rear end.
e) isEmpty( ): It is used to check if deck is empty or not.
f) getFront( ): It is used to view Front element without removing
g) getRear( ): It is used to view Rear element without removing
Example:
Algorithm: To check whether string is palindrome using Deque
if choice == 1:
element = input("Data for insertion at rear: ")
insertRear(dQu, element)
print("Data at front:", getFront(dQu))
element = input("Data for insertion at rear: ")
insertRear(dQu, element)
print("Removed:", deletionFront(dQu))
print("Removed:", deletionFront(dQu))
else:
element = input("Data for insertion at front: ")
insertFront(dQu, element)
print("Data at rear:", getRear(dQu))
element = input("Data for insertion at front: ")
insertFront(dQu, element)
print("Removed:", deletionRear(dQu))
print("Removed:", deletionRear(dQu))
23. The operation used to view elements at the front of the queue, without removing it from the queue
is
a) Dequeue b) Peek c) Enqueue d) Tell
24. In which data structure can insertion and deletion of elements occur from both end (any ends)?
a) Stack b) Queue c) Deque d) Enqueue
25. In a queue, the end where elements are added is called
a) Front b) Rear c) HEAD d) START
26. Which built-in method is used to remove an item from REAR end of the Deque?
a) POP(0) b) append(item) c) POP() d) remove(item)
Exercise
Fill in the Blanks:
1. ____________________ is a linear list of elements in which insertion and deletion takes place
from different ends.
Answer: Queue
2. Operations on a queue are performed in __________________ order.
Answer: FIFO (First In First Out)
3. Insertion operation in a queue is called ______________ and deletion operation in a queue is
called ___________________.
Answer: enqueue, dequeue
4. Deletion of elements is performed from _______________ end of the queue.
Answer: front
5. Elements ‘A’, ‘S’, ‘D’ and ‘F’ are present in the queue, and they are deleted one at a time,
________________________ is the sequence of element received.
Answer: A, S, D, F
6. _______________ is a data structure where elements can be added or removed at either end, but
not in the middle.
Answer: Deque
7. A deque contains ‘z’, ‘x’, ‘c’, ‘v’ and ‘b’. Elements received after deletion are ‘z’, ‘b’, ‘v’, ‘x’ and
‘c’. ____________________________ is the sequence of deletion operation performed on deque.
Answer: deletionFront(), deletionRear(), deletionRear(), deletionFront(), deletionFront()
8. A queue is a linear list of elements in which insertion takes place at the __________ and deletion at
the __________.
Answer: rear, front
9. Queue follows the __________ strategy, where the first element inserted is the first one to be
removed.
Answer: FIFO (First In First Out)
10. The operation to insert an element into a queue is called __________.
Answer: enqueue
11. The operation to remove an element from a queue is called __________.
Answer: dequeue
12. Attempting to remove an element from an empty queue results in an error called __________.
Answer: underflow
13. In Python, the __________ method is used to add an element at the rear of a list.
Answer: append()
14. A queue implemented using Python list does not require an __________ function because the list
size is dynamic.
Answer: isFull
15. The __________ function is used to check if the queue contains no elements.
Answer: isEmpty()
16. To view the front element of a queue without removing it, the __________ operation is used.
Answer: peek
17. A __________ allows insertion and deletion from both ends of the list.
Answer: deque (double-ended queue)
18. In Python, elements can be inserted at the front of a deque using the __________ method.
Answer: insert(0, element)
19. To delete an element from the rear of a deque, the __________ method is used in Python.
Answer: pop()
20. To remove the front element from a deque, the __________ method is used with index 0.
Answer: pop(0)
21. A data structure that can behave like both a queue and a stack is known as __________.
Answer: deque
22. In palindrome checking using deque, characters are compared by removing from __________ and
__________ ends.
Answer: front, rear
Exercise:
1. Compare and contrast queue with stack.
[Link] Queue Stack
01 Follows FIFO (First In First Out) Follows LIFO (Last In First Out)
02 Insertion at rear, deletion at front Insertion and deletion at the same end
03 Used in print queues, job scheduling Used in undo operations, expression
evaluation
3. Explain with examples how queues are used in real life and in computer science applications.
Answer:
Real-life applications:
a. Bank queues: First customer is served first.
b. Toll booths: Vehicles are allowed in FIFO order.
c. Customer care calls (IVRS): Callers wait in order of arrival.
7. Write a menu-driven Python program using queue to implement movement of shuttlecock in its
box.
Solution:
(Interpretation: Assuming each shuttlecock is added and removed in FIFO order)
def dequeue(box):
if len(box) > 0:
return [Link](0)
else:
return "Box is empty"
def isEmpty(box):
return len(box) == 0
def main():
box = []
while True:
print("\n1. Add Shuttlecock")
print("2. Remove Shuttlecock")
print("3. Exit")
choice = int(input("Enter choice: "))
if choice == 1:
shuttle = input("Enter shuttlecock code: ")
enqueue(box, shuttle)
elif choice == 2:
print("Removed:", dequeue(box))
elif choice == 3:
break
else:
print("Invalid choice")
peek()
dequeue()
dequeue()
dequeue()
dequeue()
enqueue(1)
10. Write a Python program to check whether the given string is palindrome or not using deque.
def isPalindrome(string):
deque = [ ]
for ch in string:
[Link](ch)
Example usage
s = input("Enter a string: ")
if isPalindrome(s):
print("Palindrome")
else:
print("Not a palindrome”)
11. Explain any five applications of deque from real life and computer science contexts.
A deque (double-ended queue) is a linear data structure that allows insertion and deletion at both
ends—front and rear. Due to this flexibility, deque is used in various real-life and computer science
scenarios:
Thus, deque is a versatile data structure capable of handling complex real-world and
programming scenarios efficiently.
CHAPTER – 05
SORTING
In this chapter:
Introduction
Bubble Sort
Selection Sort
Insertion sort
Time Complexity of Algorithm
1. What is a sorting?
It is a process of placing or re-arranging a collection of elements into a particular order (i.e.
Ascending, Descending, Alphabetical etc.) in a list.
Advantages:
It is essential for easy data retrieval
It is used for efficient searching
It is used for rearranging elements for efficient access
Common Applications:
Dictionaries (Alphabetical order)
Exam seating arrangements (Register number, name subject wise etc.)
Sorting by weight or height
i. Bubble Sort:
Bubble sort is the simplest sorting algorithm that works repeatedly swapping the adjacent
elements in case they are unordered in n-1 passes.
• The result in a time complexity of bubble sort is O(n2)
Example-01 :
Arrange the elements of the following list1 having 6 elements
list1 = [8, 7, 13, 1. -9, 4]
Pass 2:
[7, 8, 1, -9, 4, 13]
→ No Swap (7,8)
→ Swap 8 and 1 → [7, 1, 8, -9, 4, 13]
→ Swap 8 and -9 → [7, 1, -9, 8, 4, 13]
→ Swap 8 and 4 → [7, 1, -9, 4, 8, 13]
Pass 3:
[7, 1, -9, 4, 8, 13]
Pass 4:
[1, -9, 4, 7, 8, 13]
→ Swap 1 and -9 → [-9, 1, 4, 7, 8, 13]
Pass 5:
No swaps → Sorting complete.
Final list: [-9, 1, 4, 7, 8, 13]
Optimization Tip: If no swaps occur in a pass, the list is already sorted — the algorithm can
be terminated early
Step-3: Set j = 0
Step-7: SET j = j + 1
Step-8: SET i = i + 1
The time complexity of selection sort is O(n2) in all cases (best, average, and worst)
Demonstrates the working of the Selection sort method (Arranging the elements in Ascending
order)
Example-01 :
Arrange the elements of the following list1 having 6 elements
list1 = [8, 7, 13, 1. -9, 4]
Solution:
Selection Sort Passes:
Let us consider a list having 6 elements as list1 = [8, 7, 13, 1, -9, 4]
8 7 13 1 -9 4 -9 7 13 1 8 4
8 7 13 1 -9 4 -9 7 13 1 8 4
8 7 13 1 -9 4 -9 7 13 1 8 4
8 7 13 1 -9 4 -9 7 13 1 8 4
Swap
8 7 13 1 -9 4 -9 7 13 1 8 4
Swap Swap 1 with 7
8 7 13 1 -9 4 -9 1 13 7 8 4
Swap -9 with 8 Sorted Unsorted
-9 7 13 1 8 4
Sorted Unsorted
Pass-3 Pass-4
-9 1 13 7 8 4 -9 1 4 7 8 13
-9 1 13 7 8 4 -9 1 4 7 8 13
No Swap
-9 1 13 7 8 4 -9 1 4 7 8 13
Swap No Swap already sorted
-9 1 13 7 8 4 -9 1 4 7 8 13
Swap 4 with 13 Sorted Unsorted
-9 1 4 7 8 13
Sorted Unsorted
-9 1 4 7 8 13 -9 1 4 7 8 13
No Swap
-9 1 4 7 8 13
No Swap already sorted
-9 1 4 7 8 13
Sorted
Example-02:
Write the process to sort the following elements using selection sort method. 90, 30, -2, 6, 45, 72
Selection Sort Method
Pass-1 Pass-2
90 30 -2 6 45 72 -2 30 90 6 45 72
90 30 -2 6 45 72 -2 30 90 6 45 72
90 30 -2 6 45 72 -2 30 90 6 45 72
90 30 -2 6 45 72 -2 30 90 6 45 72
Swap
90 30 -2 6 45 72 -2 30 90 6 45 72
Swap Swap 6 with 30
90 30 -2 6 45 72 -2 6 90 30 45 72
Swap -2 with 90 Sorted Unsorted
-2 30 90 6 45 72
Sorted Unsorted
Pass-3 Pass-4
-2 6 90 30 45 72 -2 6 30 90 45 72
-2 6 90 30 45 72 -2 6 30 90 45 72
Swap
-2 6 90 30 45 72 -2 6 30 90 45 72
Swap Swap 45 with 90
-2 6 90 30 45 72 -2 6 30 45 90 72
Swap 30 with 90 Sorted Unsorted
-2 6 30 90 45 72
Sorted Unsorted
Pass-5 Final Sorted list is:
-2 6 30 45 90 72 -2 6 30 45 72 90
Swap
-2 6 30 45 90 72
Swap 72 with 90
-2 6 30 45 72 90
Sorted
Step-4: Set j = i + 1
Step-7: min = j
Step-8: flag = 1
Step-9: If flag == 1:
Step-11: Set i = i + 1
Output:
The sorted list is :
-9 1 4 7 8 13
OR
Program: Selection Sort (Method-2)
def selection_Sort(list2):
n = len(list2)
for i in range(n):
min = i
for j in range(i + 1, n):
if list2[j] < list2[min]:
min = j
list2[i], list2[min] = list2[min], list2[i]
Example-02:
Write the process to sort the following elements using insertion sort method, 80, 60, 20, 40, 50, 11
Insertion Sort Method
Pass-1 Pass-4
Swap Swap
80 60 20 40 50 11 20 40 60 80 50 11
Swap
60 80 20 40 50 11
20 40 60 50 80 11
Pass-2 No Swap
Swap
20 40 50 60 80 11
60 80 20 40 50 11
Swap 20 40 50 60 80 11
60 20 80 40 50 11
20 60 80 40 50 11
Pass-3 Pass-5
Swap Swap
20 60 80 40 50 11 20 40 50 60 80 11
Swap Swap
20 60 40 80 50 11 20 40 50 60 11 80
No Swap Swap
20 40 60 80 50 11 20 40 50 11 60 80
Swap
20 40 60 80 50 11
20 40 11 50 60 80
Swap
20 11 40 50 60 80
11 20 40 50 60 80
Final Sort list is:
11 20 40 50 60 80
Step-4: Set j = i - 1
Step-7: Set j = j - 1
Step-9: Set i = i + 1
Output:
The sorted list is :
-9 1 4 7 8 13
Note: All three sorting algorithms (Bubble sort, Selection sort, Insertion sort) have O(n²)
complexity due to nested loops.
OR
Time complexity of algorithm
The amount of time taken for execution of an algorithm is called Time complexity
• Time complexity is performed to explain how an algorithm will perform when the input grows
larger and how fast an algorithm will execute.
• Helps choose suitable algorithms for large datasets
• Time complexity is expressing using Big-O notation
Note: Based on the time complexity we decide which algorithm is good case and worst case.
5. What is swapping?
Swapping means changing the position of two elements with each other
6. Insertion Sort
Example-03: Visual View
Let us consider a list having 6 elements as list1 = [23, 1, 10, 1, 5, 2]
Initial List: [23, 1, 10, 1, 5, 2]
Summary:
Sorting: Re-arranging elements for efficient access.
Bubble Sort: Repeated adjacent swaps, n-1 passes.
Selection Sort: Select and place smallest, reduce unsorted list.
Insertion Sort: Insert each element into sorted part at the correct position.
Time Complexity: Helps choose suitable algorithms for large datasets
21. The Bubble sort makes how many passes to sort a list of n elements?
a) n b) n2 c) n-1 d) n+1
22. The Selection sort makes how many passes to sort a list of n elements?
b) n b) n2 c) n-1 d) n+1
23. The Insertion sort makes how many passes to sort a list of n elements?
c) n b) n2 c) n-1 d) n+1
CHAPTER – 06
SEARCHING
In this chapter:
Introduction
Linear search
Binary Search
Searching by Hashing
1. What is a searching?
It is the process of locating a particular element (called key) in a collection of elements
OR
It is a process of finding or locating a particular element (key) in a list of elements
It determines whether the key (particular element) is present or not.
3. Linear Search:
It compares each element of the list with the key until a match is found or the list ends.
It works on both sorted and unsorted lists
Searching the elements from beginning to end
Simpler to implement
It is also called as Sequential Search or serial search
Time complexity: O(n)
Advantages: Useful for unsorted or small-sized lists.
Disadvantage: This searching is slow and Time consuming, when list contains large number of
elements.
Example-01:
Consider the following elements stored in the list
List: L = [5, 7, 2, 9, 3]
Searching element Key = 9 using linear search method
Number of elements/size of list: n=5
Solution:
Index 0 1 2 3 4
Values (L) 5 7 2 9 3
Example-02:
Consider the following elements stored in the list
List: L = [5, 7, 2, 9, 3]
Searching element Key = 8 using linear search method
Number of elements/size of list: n=5
Solution:
Index 0 1 2 3 4
Values (L) 5 7 2 9 3
list1 = [ ]
maximum = int(input("How many elements in your list? "))
print(“Enter each element and press enter:”)
for i in range(0, maximum):
n = int(input())
[Link](n)
4. Binary Search :
Repeatedly divides list into halves and compares key with the middle element.
Requires a sorted list.
More efficient than linear search.
[ This searching method will be used only when items are in sorted order, Here elements will be
checked and splits collection of items into two parts and again do the same ]
Example-01:
Consider the following elements stored in the list
List: L = [10, 20, 30, 40, 50]
Searching element Key = 40 using binary search method
Number of elements/size of list: n=5
Solution:
Index 0 1 2 3 4
Values (L) 10 20 30 40 50
Example-02:
Consider the following elements stored in the list
List: L = [10, 20, 30, 40, 50, 60]
Searching element Key = 70 using binary search method
Number of elements/size of list: n=6
Solution:
Index 0 1 2 3 4 5
Values (L) 10 20 30 40 50 60
5. Search by Hashing:
Hashing is a technique used to search an element in a single step by Hash function to calculate
value an index in the list.
OR
Hashing is a technique used to find the presence of key in a list in just one step
Example:
List1= [56, 24, 93, 17, 70, 31, 45] Hash Table size=10
• Let us consider a list of number [56, 24, 93, 17, 70, 31, 45]
List1= [56, 24, 93, 17, 70, 31, 45]
• After computing the hash value, each element is inserted at its designated position in the has table.
Index 0 1 2 3 4 5 6 7 8 9
Value 70 31 None 93 24 45 56 17 None None
• Now, To search for a key, we can calculate the index using the hashing function to compare the
element at that index with the key to declare whether the element is present in the list or not
• This search operation involves just one comparison and hence the same amount of time is always
required to search a key irrespective of the size of the list
OR
Output:
6. Collision in hashing:
Collision occurs when multiple elements hash to the same index.
[When two or more elements map to the same slot in the hash table, it is called collision]
Exercise:
1. What is searching? Which method is used in simple hash function that works with numerical values?
• Searching: It is the process of finding the position of a particular element in a collection of elements
(Searching means locating a particular element in a collection of elements)
• Remainder (Modulus %) method is used in simple hash function that works with numerical values