0% found this document useful (0 votes)
20 views64 pages

Python Exception Handling Explained

Uploaded by

v68273934
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views64 pages

Python Exception Handling Explained

Uploaded by

v68273934
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

IMPORTANT QUESTIONS ON EXCEPTIONS HANDLING IN PYTHON

❖ Five Marks Questions:


1. Explain the different types of errors with example.
Ans: 1. Syntax Error: Syntax errors are detected when we have not followed the rules of the particular
programming language while writing a [Link] errors are also known as parsing errors.
Example: marks=98
print(“Good score”
SyntaxError: missing parenthesis in print statement.
2. Logical Error: Logical errors will produce incorrect results. These errors will not stop a program from
running/executing.
Example: l=4 b=6
Perimeter=2 * l + b
Perimeter=2*4+6
Result=14
Logical Error: should be 2*(l+b)
3. Runtime Error: Run-time occurs during a program’s execution. Run-time errors are also known as
Exceptions.
Example: A number divide by zero results in runtime error.
C=3/0
Run-time Error: zero division error.

[Link] try…except block with an example.


try block-
While writing a program, a user might doubt an exception to occur in a particular part of the code. Such
suspicious lines of codes are put inside a try block.
Syntax:
try:
[ program statements where exceptions might occur]
Except block-
An except block contains additional code that will be executed only if some exception is raised in the try
block. But if there is no error then none of the except blocks will be executed.
Syntax:
except ExceptionName:
[ code for exception handling if the exception-name error is encountered]
Example:
try:
n=50
d=int(input("Enter the denominator"))
q=(n/d)
print(q)
print ("Division successfull")
except ZeroDivisionError:
print ("Denominator as ZERO.... not allowed")
• In the above example, if d value is non-zero, then q=n/d operation is performed and q value will be
displayed along with “Division successful”. And except block will be skipped.
• If the user enters the value of d=0, then the execution of the try block will stop. The control will shift to
the except block and the message “Denominator as Zero…. not allowed” will be displayed.
[Link] try…except..else block with an example.
Ans: try block-
While writing a program, a user might doubt an exception to occur in a particular part of the code. Such
suspicious lines of codes are put inside a try block.
Syntax:
try:
[ program statements where exceptions might occur]

Except block-
An except block contains additional code that will be executed only if some exception is raised in the try block.
But if there is no error then none of the except blocks will be executed.
except Exception Name:
[ code for exception handling]
Else block- If there is no error then none of the except blocks will be executed. In this case, the statements
inside the else block will be executed.
Example:
try:
n=50
d=int (input ("Enter the denominator"))
q=(n/d)
except ZeroDivisionError:
print ("Denominator as ZERO.... not allowed")
else:
print(q)
print ("Division successful")
In the above example, if there is no error in the try block then, except block will not execute, in this case else
block statements that is q value and “Division successful” is displayed.
[Link] try..except..else…finally block with an example.
Ans: try block-
While writing a program, a user might doubt an exception to occur in a particular part of the code. Such
suspicious lines of codes are put inside a try block.
Syntax:
try:
[ program statements where exceptions might occur]
Except block-
An except block contains additional code that will be executed only if some exception is raised in the try block.
But if there is no error then none of the except blocks will be executed.
except ExceptionName:
[ code for exception handling]
Else block- If there is no error then none of the except blocks will be executed. In this case, the statements
inside the else block will be executed.
Finally block: - The statements inside the finally block is always executed whether an exception has occurred
in the try block or not. If used, finally should always be placed at the end after try, except and else block.
Example:
try:
n=50
d=int (input ("Enter the denominator"))
q=(n/d)
except ZeroDivisionError:
print ("Denominator as ZERO.... not allowed")
else:
print(q)
print ("Division successful")
finally:
print (“Program Ends”)
In the above program, the message “Program Ends” will be displayed irrespective of whether an exception
is raised or not.
4. Explain any five built-in exceptions that can be raised in python.
Ans. 1. ImportError: It is raised when the requested module definition is not found.
Example: import Math
ModuleNotFoundError: No module named 'Math'

[Link]: It is raised when the file specified in a program statement cannot be opened.
Example: file = open ("[Link]", "r")
IOError: No such file: '[Link]'
3. ZeroDivisionError: It is raised when the denominator in a division operation is zero.
Example: print (50/0)
ZeroDivisionError: division by zero
4. IndexError: It is raised when the index in a sequence is out of range.
Example: n= [40,50,60]
print (n [4])
IndexError: list assignment index out of range

5. NameError: It is raised when a local or global variable name is not defined.


Example: print (var + 40)
NameError: name 'var' is not defined.

6. EOFError: It is raised when the end of file condition is reached without


reading any data by input().

7. TypeError: It is raised when an operator is supplied with a value of


incorrect data type.

8. ValueError: It is raised when an operation receives an argument that has


the right data type but mismatched values.

9. KeyboardInterrupt: It is raised when the user accidentally hits the


Delete or Esc key while executing a program due to which the normal flow
of the program is interrupted.

THREE MARKS QUESTIONS:


1. What is a raise statement? Explain syntax and example.
Ans: The raise statement is used to throw an exception.
Syntax:
raise exception-name [(optional argument)]
The argument is a string that is displayed when the exception is raised.
Example:
a=5
if a % 2 != 0:
raise exception(“number should not be an odd integer”)
3. What is an assert statement? Explain syntax and example.
Ans: An assert statement in Python is used to test an expression in the program code. If the result after
testing comes false, then the exception is raised.
Syntax:
assert Expression[arguments]
Example:
def negativecheck(number):
assert(number>=0) “OOPS... Negative Number"
print (number * number)
print (negativecheck (-350))
Output
AssertionError: OOPS... Negative Number
4. Explain finally block with an example.
Ans: Finally block: - The statements inside the finally block is always executed whether an exception
has occurred in the try block or not. If used, finally should always be placed at the end after try, except and else
block.
try:
n=50
d=int (input ("Enter the denominator"))
q=(n/d)
except ZeroDivisionError:
print ("Denominator as ZERO.... not allowed")
else:
print(q)
print ("Division successful")
finally:
print (“Program Ends”)
In the above program, the message “Program Ends” will be displayed irrespective of whether an exception
is raised or not.

5. What are the needs of exception handling?


Ans:
1. Python categorizes exceptions into distinct types so that specific exception handlers (code to handle that
particular exception) can be created for each type.
2. Exception handlers separate the main logic of the program from the error detection and correction code.
3. The segment of code where there is any possibility of error or exception, is placed inside one block. The
code to be executed in case the exception has occurred, is placed inside another block.
4. The interpreter keeps track of the exact position where the error has occurred.
6. Explain the process of handling exception:
Ans:
1. When an error occurs, Python interpreter creates an object called the exception object, which contains
information about the error like its filename, and position in the program where the error has occurred.
2. The object is handed over to the runtime system so that it can find an appropriate code to handle this
particular exception. This process of creating an exception is called throwing an exception.
3. The runtime system searches the entire program for a block of code, called the exception handler that
can handle the raised exception.
4. The hierarchical search in reverse order continues till the exception handler is found. This entire list of
methods is known as call stack.
5. When a suitable handler is found in the call stack, it is executed by the runtime process.

[Link] multiple except clauses with syntax and example.


Ans: In python we can use multiple except clauses to catch and handle different types of exceptions in a
single try block.
Syntax:
try:
[statements]
except [exception-name]:
[statements]
except [exception-name]:
[statements]
Example:
print ("Handling multiple exceptions")
try:
n=50
d=int (input ("Enter the denominator: "))
print (n/d)
print ("Division performed successfully")
except ZeroDivisionError:
print ("Denominator as ZERO is not allowed")
except ValueError:
print ("Only INTEGERS should be entered")
TWO MARKS QUESTIONS:
[Link] is an exception?
2. What is try block?
[Link] is except block?
[Link] is exception handling?
[Link] is catching exception?
[Link] is throwing an exception?

CH-2 IMPORTANT QUESTIONS ON FILE HANDLING IN PYTHON


❖ Five Marks Questions:
1. Explain various file access modes to open the file.

Ans:
2. Explain pickle module. [5m]
• The pickle module deals with binary files.
• Here, data are not written but dumped and similarly, data are not read but loaded.
• The Pickle Module must be imported to load and dump data.
• The pickle module provides two methods –
dump() and load() to work with binary files for pickling and unpickling, respectively.
• Serialization is the process of transforming data or an object in memory (RAM) to a stream of bytes called
byte streams.
• De-serialization or unpickling is the inverse of pickling process where a byte stream is converted back to
Python object

3. Explain the creating file and writing data with example.


Ans: 1. To create a text file, we use the open() method and provide the filename and the mode.
[Link] it is in write mode (w), then all the existing contents of file will be lost, and an empty file will be
created with the same name.
3. if the file is created in append mode (a), then the new data will be written after the existing data.
4. In both cases, if the file does not exist, then a new empty file will be created.
Example:
fileobject=open("[Link]","w+")
while True:
data= input("Enter data to save in the text file: ")
[Link](data)
ans=input("Do you wish to enter more data?(y/n): ")
if ans=='n':
break
[Link]()
THREE MARKS QUESTIONS:
[Link] the differences between Text file and Binary file.

Ans:
[Link] a note on opening a file.
Ans: 1. To open a file in Python, we use the open() function.
Syntax of open() :
file_object= open(file_name, access_mode)
[Link] file_object establishes a link between the program and the data file stored in the permanent storage.
3. file_name- refers the name of the file that has to be opened.
4. access_mode- Here mode means the operation for which the file has to be opened like for reading,
writing, or for appending. The default mode is read mode.

[Link] opening a file using with clause.


Ans: Using with clause, any file that is opened using this clause is closed automatically, once the control
comes outside the with clause.
Syntax of with clause is:
with open (file_name, access_mode) as file_ object:
Example:
with open (“[Link]”, ” r+”) as myObject:
content = [Link]()
Here, we don’t have to close the file explicitly using close() statement. Python will automatically close the file.
[Link] is a File? Mention the types of Files.
Ans: A file is a named location on a secondary storage media where data are permanently stored for later
access.
Two types of Files are:
[Link] File
2. Binary File.
5. Explain Dump() and Load() method.
Ans: The dump() method
▪ This method is used to convert (pickling) Python objects for writing data in a binary file.
▪ The file in which data are to be dumped, needs to be opened in binary write mode (wb).
Syntax of dump() :
dump(data_object, file_object)
where data_object is the object that has to be dumped to the file with the file handle named file_object.
Example:
import pickle
listvalues=[1,"Geetika",'F', 26] fileobject=open("[Link]", "wb") [Link](listvalues,fileobject)
[Link]()

The load() method


▪ This method is used to load (unpickling) data from a binary file.
▪ The file to be loaded is opened in binary read (rb) mode.
Syntax of load()
Store_object = load(file_object)
Example:
import pickle
print("The data that were stored in file are: ") fileobject=open("[Link]","rb")
objectvar=[Link](fileobject)
[Link]()
print(objectvar
[Link] tell() and seek() method
Ans: tell() method:
▪ This function returns an integer that specifies the current position of the file object in the file.
Syntax of tell() is:
file_object.tell()

seek() method:
This method is used to position the file object at a particular position in a file.
The syntax of seek() is:
file_object.seek(offset [, reference_point])
where, offset is the number of bytes by which the file object is to be moved.
reference_point indicates the starting position of the file object.
That is, with reference to which position, the offset has to be counted. It can have any of the following
values:
0 - beginning of the file
1 - current position of the file
2 - end of file
By default, the value of reference point is 0.
TWO MARKS QUESTIONS:
1. Differentiate between the following-
i. write () and writelines() method
Ans: i. write () –
• write() method takes a string as an argument and writes it to the text file.
• write() returns the number of characters written on to the file.
ii. writelines() –
• This method is used to write multiple strings to a file. We need to pass an iterable object like lists,
tuple, etc. containing strings to the writelines() method.
• The writelines() method does not return the number of characters written in the file.
[Link] the different forms of read statement.
Ans: i. read() – This method is used to read a specified number of bytes of data from a data file.
The syntax of read() method is:
file_object.read(n)
example:
>>>myobject=open("[Link]",'r’)
>>> [Link](10)
[Link]( ) - This method reads one complete line from a file where each line terminates with a newline
(\n) character.
>>>myobject=open("[Link]",'r’)
>>> print ([Link]())
iii. readlines()- This method reads all the lines and returns the lines along with newline as a list of strings.
>>> myobject=open("[Link]", 'r’)
>>> print([Link]()) ['Hello everyone\n', 'Writing multiline strings\n', 'This is the third line’]
>>> [Link]()
2. Write a note on Binary file.
Ans: 1. Binary files are stored in terms of bytes (0s and 1s)
[Link] files are not human readable.
3. Binary files are having extension .dat

3. What is serialization and Deserialization?


Ans: Serialization is the process of transforming data or python object in memory (RAM) to a stream of
bytes called byte streams.

De-serialization or unpickling is the inverse of pickling process where a byte stream is converted back to
Python object.

STACK
MCQs
[1] A ____________ is a way to store, organize, or manage data in efficient and productive manner.
Data Structure
[2] A stack is one of the following types of data structure?
a) Linear b) Dynamic c) Circular d) All of these
[3] Stack data structure is following ____________ principle.
LIFO
[4] In stack data can be inserted or deleted from ____________ only.
Top
[5] The insert operation in the stack is known as pop. (True/False)
[6] You can replace any element position in the stack. (True/False)
7] The peek operation refers to accessing/inspecting the top element in the stack. (True/False)
[8] A condition raise due to the stack is full is known as ___________.
a) Underflow b) Overflow c) List is full d) Completely Filled
[9] While popping the element from the stack, a condition will be raised, this condition is known as
____________.
a) Underflow b) Overflow c) List is Empty d) Blank List
[10] Stack overflow condition is raised in ____________ operation whereas Stack underflow condition is raised in
_____________ operations.
Push, Pop
Two Marks Questions:
1] What do you mean by data structure. Give example.
Ans: A data structure defines a mechanism to store, organize and access data along with operations that can be
efficiently performed on the data.
1. String – Contains sequence of characters
2. List – Contains sequence of different data types

2. What is stack? Give one real life example.


Ans: A stack is an ordered collection of elements where the insertion and deletion of element takes place at the
same end or one end called Top.
Real-life example-
• Pile of clothes in an almirah
• Pile of chairs
• . Books in the shelf
3. What do you mean by the LIFO structure?
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.
[Link] are the fundamental operations performed on stack?
Ans: 1. PUSH-inserting an element into a stack.
2. POP-deleting an element from the stack.

5. Mention the methods that are used for implementation of the stack.
Ans: 1. Append ()
2. pop ()
[Link] are the underflow and overflow conditions?
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.
[Link] is the significance of top in stack?
Ans: The top function returns the topmost element of the stack.
8. What is the Top status when stack is underflow & overflow?
Ans: Top=-1 indicates stack is underflow.
Top=n-1 indicates stack is overflow.

9. Write a python function to push an element into the stack.


Ans: def push (stack, element):
stack. append (element)

THREE MARKS QUESTIONS:


[Link] out the applications of stack in programming concepts.
Ans: 1. Browsers History
2. Mobile Phone Call log
3. Undo and redo commands in software
4. To reverse a string
5. Expression evaluation like Parenthesis checking.
2. Write a python function named isEmpty () to check a stack is an underflow or empty.
def isEmpty(Stack):
if len(Stack)==0:
return True
else:
return False
3. Write a python function to delete an element from the stack.
def opPop(StackName):
if len(Stack)==0:
print('underflow’)
return None
else: return([Link]())
4. Write a function to inspect an element (to read the most recent or top element) from the stack.
def top(glassStack):
if len(Stack)==0:
print('Stack is empty’)
return None
else:
x =len(StackName)
element=StackName[x-1]
return element

5. Write a function to display the stack elements.


def display(StackName):
x=len(StackName)
print("Current elements in the stack are: ")
for i in range(x-1,-1,-1):
print(StackName[i])
[Link] the different types of Arithmetic expressions.
Ans:
FIVE MARKS QUESTIONS:
[Link] PUSH & POP Operations.
Ans: PUSH Operations:
1. PUSH operation performs insertion operation.
2. PUSH adds a new element at the TOP of the stack.
3. We can add elements to stack until it is full.
4. When stack is full no more element can be added.
5. Trying to add an element to a full stack it results an exception called overflow.
POP Operations:
1. POP operation performs deletion operation.
2. POP delete the existing element from top of the stack.
3. We can delete elements from a stack until it becomes empty.
4. When stack is empty no more deletion can be done.
5. Trying to delete an element from an empty stack result in an exception called underflow.
2. Explain the stack operations with an example by showing the status of stack.
Ans:

(Explain the example)


2. Convert a given following infix expression into equivalent postfix expression using a stack:
i. (x+y)/(2*8)
ii. A*((C+D)/E)
Answer
Given,
A * (( C + D)/E)
Scanning from left to right:

Postfix
Symbol Action Stack
Expression

*
* Push

A
(*
( Push

( Push ((*

+((* AC
+ Push

D ACD

(*
Pop till one opening bracket is popped and
)
add popped operator to expression

ACD+
/(*
/ Push

E ACD+E

*
Pop till one opening bracket is popped and
) ACD+E/
add popped operator to expression

End of
Pop all and add to expression #Empty ACD+E/*
expression

iii. A+B-C*D
Answer
Given,
A+B-C*D
Scanning from left to right:

Postfix
Symbol Action Stack
Expression

+ A
+ Push in stack

B AB

- - AB+
Equal precedence to +. Pop from stack, add in

expression then push this operator(-)

*- AB+C
* Higher precedence than (-), hence Push

D AB+CD

End of
Pop all and add to expression #Empty AB+CD*-
expression

3. Evaluate the following postfix expression


i. 782*4/+
ii. AB+C* WHERE A=3, B=5, C=1, D=4
Scanning from left to right :

Intermediate
Symbol Action Stack
output
3
3 Push

53
5 Push

#Empty

+ Pop twice and Evaluate and Push back 8 3+5=8

18
1 Push

#Empty

* Pop twice, Evaluate Push back 8 1*8=8

Hence, AB + C * = 35 + 1 * = 8
[Link]*C/D* WHERE A=3, B=5, C=1, D=4
Answer
AB * C / D * = 35 * / 4 *
Scanning from left to right :

Intermediate
Symbol Action Stack
output

3 Push 3

53
5 Push

#Empty

* Pop twice, Evaluate and Push back 15 3 * 5 = 15

1 Push 1 15

#Empty

/ Pop twice, Evaluate and Push back 15 15/1 = 15

4 15
4 Push

#Empty
15 * 4 = 60
* Pop twice, Evaluate and Push back 60

Hence, AB * C / D * = 35 * / 4 * = 60

4. For the following Arithmetic expression:


((2+3)*(4/2))+2
Show step by step process for matching parenthesis using stack data structure.
Ans. For matching parenthesis push the opening parenthesis of the expression in the stack and pop from the stack
for each closing parenthesis.
Symbol Stack Action
( ( push
( (( push
2 (( -
+ (( -
3 (( -
) ( pop parenthesis
*
( (( push
4 (( -
/ (( -
2 (( -
) ( pop parenthesis
) Empty pop parenthesis
+ Empty -
2 Empty -
Stack is empty so it’s a balanced parenthesis.
[Link] the output of the following code:
result = 0
numberList = [10, 15, 32]
[Link](45)
result = result + [Link]()
result = result + [Link]()
print("Result=", result)
Output
QUEUE
TWO MARKS QUESTIONS:
1. What is Queue? Show the representation of queue.
Ans: Queue is an ordered linear list of elements, having different ends for adding and removing elements in it.
(deletion)Front Rear(insertion)
2. What is Deque? Show the representation of Deque.
Ans: Deque is a data structure in which addition and removal of element(s) can happen from any end, i.e.
front or rear.
Deque is also known as double-ended queue.
3. List out any two applications of queue in data structure or in computer science.
Ans: 1. Web server: To serve thousands of user requests.
2. Multitasking operating system: Jobs are queued and given access to processor in FIFO order.
3. Resource sharing: Queues are the best way to implement sharing of resources.
4. List out any two applications of queue in real life.
Ans: 1. Banking customers are served in the order they arrive.
[Link] cashier line in the store.
3. Patients waiting outside the doctor’s clinic.
5. Write the differences between queue & Deque.
Ans: Queue:
• It allows insertion in one end called rear and deletion from another end called front.
• Operations of queue are – ENQUEUE DEQUEUE, IS EMPTY, PEEK, IS FULL.
Deque:
• It allows insertion and deletion from both the ends i.e. From rear end and front end.
• Operations of deque- INSERTREAR, INSERTFRONT, DELETIONREAR, DELETIONFRONT.
6. Give any two applications of deque in real life.
Ans: 1. Vehicles in a highway toll tax booth are served following the principle of queue.
2. There are multiple queues if there are parallel booths at the toll gate.
7. Give any two applications of deque in computer science.
Ans; 1. Providing the DO and Undo option in any text editor.
2. To check whether a given string is palindrome or not.
THREE MARKS QUESTIONS:
[Link] the differences between Stack & Queue.
Ans: Stack:
1. Stack follows LIFO (Last In First Out) principle.
2. In stack insertion and deletion takes place at one end only.
3. In stack, Push operation is used for insertion and pop operation is used for deletion.
Queue:
1. Queue follows FIFO (First In First Out) principle.
2. In queue, insertion occurs at the rear end and deletion occurs at the front end.
3. In queue, enqueue operation is used for insertion and dequeue operation is used for deletion.
[Link] explain the concept of FIFO.
Ans: 1. Queue follows the principle of First In First Out (FIFO), since the element entering first in the queue will be
the first one to come out of it.
[Link] the implementation of enqueue and dequeue operations.
Ans: enqueue: An enqueue function to insert a new element at the end of queue. The function has two
parameters - name of the queue and element which is to be inserted in the queue.
def enqueue(myQueue, element):
[Link](element)
dequeue: A function (dequeue) to delete an element from the front of the queue. It has one parameter -
name of the queue and returns the deleted element. The function first checks if the queue is empty or not,
for successful deletion.
def dequeue(myQueue):
if (len(myQueue)==0):
print(“Queue is empty”)
else:
return [Link](0)

3. Mention the operations that can be performed on deque.


Ans:
1. INSERTFRONT
[Link]
[Link]
[Link]

FIVE MARKS QUESTIONS:


1. Explain the Operations on Queue:
Ans: ENQUEUE: It is used to insert a new element to the queue at the rear end.
DEQUEUE: It is used to remove one element at a time from the front of the queue.
IS EMPTY: It is used to check whether the queue has any element or not.
PEEK: It is used to view elements at the front of the queue, without removing it from the queue.
IS FULL: used to check whether any more elements can be added to the queue or not.
[Link] the implementation of deque.
[Link]:
def INSERTREAR(mydeque, element):
[Link](element)
[Link]:
def insertFront(myDeque, element):
[Link](0,element)
[Link]:
def deletionRear(myDeque):
if (len(mydeque)==0):
print(“Deque empty”)
else:
return [Link]()

[Link]:
def DELETIONFRONT(mydeQue):
if (len(mydeQue)==0):
print(“deque is empty”)
else:
return [Link](0)

3a. Show the status of queue after each operation.


(Do it. I didn’t shown the status of queue.)
enqueue(34)
enqueue(54)
dequeue()
enqueue(12)
peek()
dequeue()
dequeue()
dequeue()
dequeue()
enqueue(1)
b. Show the status of deque after each operation.
Peek()
InsertFront(12)
insertRear(67)
deletionFront()
insertRear(43)
deletionRear()
deletionFront()
deletionRear()

CHAPTER-5 SORTING
FIVE MARKS QUESTIONS:
[Link] the bubble sort with an example.
Ans: Bubble sort is a sorting technique, that sorts a given list of elements by repeatedly comparing
the adjacent elements and swapping them if they are unordered.
➢ In order to arrange elements in ascending order, the largest element is identified after each
pass and placed at the correct position in the list. This can be considered as the largest
element being ‘bubbled up’. Hence the name Bubble sort.
➢ Example: list = [8, 7, 13, 1, -9, 4]
[Link] the selection sort with an example.
• Ans: In Selection Sort, the list is considered to be divided into two lists –
[Link] left list containing the sorted elements.
[Link] right list containing the unsorted elements.
• The smallest element is selected from the unsorted array and swapped with the leftmost
element, and that element becomes a part of the sorted array. The process continues for the
next element in the unsorted array till the list is sorted.
➢ Example: list = [8, 7, 13, 1, -9, 4]
[Link] the insertion sort with an example.
Ans: Insertion sort divides the list into sorted and unsorted list. Each element in the unsorted list is
considered one by one and is inserted into the sorted list at its appropriate position.
In each pass, the sorted list is traversed from the backward direction to find the position where the
unsorted element could be inserted. Hence the sorting method is called insertion sort.

Example:
THREE MARKS QUESTIONS:
[Link] is sorting? Mention different types of sorting.
Ans: Sorting is the process of ordering or arranging a given collection of elements in some particular
order.
Different types of sorting are-
[Link] sort
[Link] sort
[Link] sort.
[Link] an Algorithm of Bubble sort.
Ans: BUBBLESORT (numList, n)
Step 1: SET i = 0
Step 2: WHILE i< n REPEAT STEPS 3 to 8
Step 3: SET j = 0
Step 4: WHILE j< n-i-1, REPEAT STEPS 5 to 7
Step 5: IF numList[j] > numList[j+1] THEN
Step 6: swap(numList[j] , numList[j+1])
Step 7: SET j=j+1
Step 8: SET i=i+1
[Link] an Algorithm of Selection sort.
Ans: SELECTIONSORT( numList, n)
Step 1: SET i=0
Step 2: WHILE i< n REPEAT STEPS 3 to 11
Step 3: SET min = i, flag = 0
Step 4: SET j= i+1
Step 5: WHILE j< n REPEAT steps 6 to 10
Step 6 : If numlist[j] < numlist[min] Then
Step 7: min = j
Step 8: flag = 1
Step 9: IF flag = 1 THEN
Step 10: swap(numList[i],numList[min])
Step 11: SET i=i+1
[Link] an Algorithm of Insertion sort.
Ans: INSERTIONSORT( numList, n)
Step 1: SET i=1
Step 2: WHILE i< n REPEAT STEPS 3 to 9
Step 3: temp = numList[i]
Step 4: SET j = i-1
Step 5: WHILE j> = 0 and numList[j]>temp,REPEAT STEPS 6 to 7
Step 6: numList[j+1] = numList[j]
Step 7: SET j=j-1
Step 8: numList[j+1] = temp
Step 9: set i=i+1
[Link]:
a. Constant time algorithms.
Ans: Any algorithm that does not have any loop will have time complexity as 1. Such
algorithms are known as Constant time algorithms.
b. Linear time algorithms.
Ans: Any algorithm that has a loop will have the time complexity as n. Such algorithms are
known as Linear time algorithms.
c. Quadratic time algorithms.
Ans: A loop within a loop (nested loop) will have the time complexity as n2. Such algorithms
are known as Quadratic time algorithms.,
CH – 6 SEARCHING
TWO MARKS QUESTIONS:
[Link] is searching?
• Ans: Searching means locating a particular element in a collection of elements.
[Link] a note on Linear search.
• Ans: It is a searching technique where every element of a given list is compared with the item to be
searched. This process continues until an element matching the key is found and we declare that the search
is successful else search is unsuccessful.
• It is also called sequential search or serial search.
[Link] a note on Binary search.
Ans: Binary search takes a sorted/ordered list and divides it in the middle. It then compares the middle element
with the key to be searched. If the middle element matches the key, the search is declared successful and the
program ends. If the middle element is greater than the key, the search repeats only in the first half of the list. If
the middle element is lesser than the key, the search repeats only in the second half of the list.
[Link] a note on Search by Hashing.
Ans: • Hash based searching requires only one key comparison to discover the presence or absence of a key,
provided every element is present at its designated position decided by a hash function.
5. What is collision and collision resolution?
• Ans: When two elements map to the same slot in the hash table, it is called collision.
• The process of identifying a slot for the second and further items in the hash table in the event of collision,
is called collision resolution.
[Link] the applications of binary search.
Ans:1. – Searching a dictionary or a telephone directory, finding the element with minimum value or maximum
value in a sorted list, etc.
2. Indexing in databases, implementing routing tables in routers, data compression code, etc.
7. What is perfect hash function?
Ans. A perfect hash function maps every input key to a unique index in the hash table. If the hash function is
perfect, collisions will never occur.
THREE MARKS QUESTIONS:
1. Mention the types of searching methods.
Ans: 1. Linear Search
2. Binary Search
3. Search by Hashing
2. Write an algorithm of Linear search.
Ans: LinearSearch(numList, key, n)
Step 1: SET index = 0
Step 2: WHILE index < n, REPEAT Step 3
Step 3: IF numlist[index]= key THEN
PRINT “Element found at position”, index+1
STOP
ELSE
index = index+1
Step 4: PRINT “Search unsuccessful”

3. Write an algorithm of Binary search.


Ans. BinarySearch(numList, key)
Step 1: SET first = 0, last = n-1
Step 2: Calculate mid = (first+last)//2
Step 3: WHILE first <= last REPEAT Step 4
Step 4: IF numList[mid] = key
PRINT “Element found at position”, " mid+1
STOP
ELSE
IF numList[mid] > key, THEN
last = mid-1
ELSE
first = mid + 1
Step 5: PRINT “Search unsuccessful”
4. Explain collision in hashing with example.
• Ans. When two elements map to the same index in the hash table, it is called collision
• The process of identifying a slot for the second and further items in the hash table in the event of collision,
is called collision resolution.
• Consider a list [34, 16, 2, 26, 80]. While applying the hash function say, list [i]%10, two elements (16 and 26)
would have a hash value 6.
• This is a problematic situation, because according to our definition, two or more elements cannot be in the
same position in the list. This situation is called collision in hashing.
FIVE MARKS QUESTIONS:
1. Explain linear search with example.
• Ans: It is a searching technique where every element of a given list is compared with the item to be
searched. This process continues until an element matching the key is found and we declare that the search
is successful else search is unsuccessful.
• Example : Assume that the numList has seven elements [8, -4, 7, 17, 0, 2, 19] so,
n = 7. We need to search for the key, say 17 in numList.
The step-by-step process of linear search using Algorithm:

Observe that after four comparisons, the algorithm found the key 17 and will display ‘Element found at
position 4’.
2. Explain binary search with example.
• Ans. In binary search, the key to be searched is compared with the element in the middle of a sorted list.
This could result in either of the three possibilities:
i) the element at the middle position itself matches the key or
ii) the element at the middle position is greater than the key or
iii) the element at the middle position is smaller than the key
• If the element at the middle position matches the key, we declare the search successful and the searching
process ends.
• If the middle element is greater than the key it means that if the key is present in the list, it must surely be
in the first half.
• If the middle element is less than the key, it means if the key is present in the list, it must be in the second
half.
Example : let us search for key 2 in the list. numList = [2,3,5,7,10,11,12,17,19,23,29,3 1,37,41,43]

3. Explain search by hashing with example.


• Ans: Hashing is a technique which can be used to know the presence of a key in a list in just one step.
• A formula called hash function is used to calculate the value at an index in the list
• h(element) = element % size(hash table)
• Thus, a hash function takes elements of a list one by one and generates an index value for every element.
This will generate a new list called the hash table. Each index of the hash table can hold only one item and
the positions are indexed by integer values starting from 0.
• Let us consider a list of numbers (34, 16, 2, 93, 80, 77, 51)
• Table: hash function element % 10 applied on the elements of list


• After computing the hash values, each element is inserted at its designated position in the hash table:


4. Use the hash function: h(element)= element%10 to store the collection of numbers: [44, 121, 55, 33, 110,
77, 22, 66] in a hash table. Display the hash table created. Search if the values 11, 44, 88 and 121 are
present in the hash table, and display the search results.
5. Following is a list of unsorted/unordered numbers: [50, 31, 21, 28, 72, 41, 73, 93, 68, 43] • Use linear
search to determine the position of 72 in the list.
• Sort the above list and use binary search to determine the position of 93 in the sorted list.
{For the above two questions (4Q & 5Q) refer workbook}

CHAPTER-7 UNDERSTANDING DATA


II TWO MARKS QUESTIONS:

1. What is structured data? Give example.


2. What is unstructured data? Give example.

I THREE MARKS QUESTIONS:


1. Explain the data processing.

II FIVE MARKS QUESTIONS:

1. Consider the temperature (in Celsius) of 7 days of a week as 34, 34, 27, 28, 27, 34, 34. Identify the
appropriate statistical technique to be used to calculate the following:
i. Find the average temperature.
ii. Find the temperature Range of that week.
iii. Find the standard deviation temperature.
2. Consider the marks scored by students in a subject given [90,80,70,95,95,85,80] calculate the statistical
technique for the following:
• Find the range of marks scored.
• Find the standard deviation of marks.
2. The following are the runs scored by two batsman A and B of team Alpha on the first five innings of three
consecutive test matches
Batsman A:77,89,45,63,70 runs per innings
Batsman B: 100,45,122,88,99 runs per innings
a. Find standard deviation of scores of both Batsman A and B
b. Based on standard deviation who is more consistent in scoring.

Difference Between Standard deviation and Range.


• Standard Deviation – Analyze variations within a dataset.
• Range – Quick estimate of spread.
CH – 8 DATABASE CONCEPTS
[Link]:
1. The number of attributes in a relation is called:
a) Degree b) cardinality c) domain d) tuple
2. Identify the DBMS software:
a) Microsoft Access b) Microsoft Outlook c) Microsoft PowerPoint d) Microsoft Excel
3. The purpose of constraint in database is:
a) To ensure reliability b) To define size of database
c)To specify format d) To speedup query
II. FILL IN THE BLANKS:
1. Each row of a table is called_________
2. ___________means same data are duplicated in different places.
3. ___________refers to duplication of data in a database.
[Link] MARKS QUESTIONS:
1. Define Database and DBMS.
➢ Ans: Database - A database is an organized collection of structured information, or data, stored
electronically in a computer system.
➢ DBMS - A database management system (DBMS) is a software that can be used to create and manage
databases. Ex: MySQL, Oracle, PostgreSQL, SQL Server, Microsoft Access, MongoDB.
2. List out the two limitations of DBMS.
Ans: 1. Increased Complexity: like maintaining security, consistency, sharing and integrity.
[Link] data vulnerability: Loss of data due to failure of hardware or software.
3. Write the rules which are imposed on an attribute of the relation.
• Each attribute in a relation has a unique name.
• Sequence of attributes in a relation does not matter.
4. List any two uses of database in real life application.
Ans: 1. Banking – customer information, account details, loan details, transaction details,
2. Inventory management - product details, customer information, order details, delivery data, etc.
[Link] Shopping – items description, user login details, users’ preferences details, etc.

5. Explain the role of UNIQUE constraint in a database.


• Ans: A UNIQUE constraint in SQL is a rule applied to a column or a set of columns within a table to
ensure that all values in that column or set of columns are distinct.
• It prevents the insertion or update of duplicate values in the specified column(s).
[Link] MARKS QUESTIONS:
1. Briefly explain database schema, data constraint and data manipulation.
• Database Schema: It is the design of the database that represents the structure of the table their
columns and its data types, constraints on the data and the relationships among the tables.
• Database Constraint: A database constraint is a restriction on the type of data that can be
inserted into the table.
• Data Manipulation: Data manipulation means the Modification of database that consists of
operations like Insertion, Deletion or Update.
2. Explain limitations of manual record keeping.
Ans: 1. Loss of data in case attendance register is lost or damaged.
[Link] calculations while consolidating attendance record manually.
3. Finding or deleting or modifying information from a huge volume of papers is a difficult task in pen
and paper-based approach.
3. Define the following:
a) Database Engine: Database engine is the set of programs used by a DBMS to create database and
handle various queries for data retrieval and manipulation.
b) Meta-data: The database schema along with various constraints on the data is stored by DBMS in a
database catalog or dictionary, called meta-data.
c) Query: A query is a request to a database for obtaining information in a desired way.
[Link] MARKS QUESTIONS:
1. What is a key in relational database? Explain types of keys.
Ans: In relational databases, keys are columns that uniquely identify rows within a table and establish
relationships between different tables.
1. Candidate key: A candidate key is a set of attributes that are uniquely identify tuples in a relation.
or
A relation can have one or more attribute that takes distinct values. Any of these attributes can be used to
uniquely identify the tuples of the relation. Such attributes are called candidate keys. 26
2. Primary key: Out of one or more candidate keys, the attribute chosen by the database designer to uniquely
identify the tuples in a relation is called the primary key .
3. Composite Primary key: If a single key cannot be uniquely identifying the tuples in relations, then a
combination of attributes is used as composite primary key.
or
If no single attribute in a relation is able to uniquely distinguish the tuples, then more than one attribute is
taken together as a composite primary key.
4. Foreign key: A foreign key is an attribute in one table that refers to the primary key in another table and
establishes the relationship between two tables.
5. Alternate keys: The remaining attribute in the list of candidate keys are called the alternate keys.
2. Define the below terms:
a) attribute – The columns of a relation are called attributes.
b) tuple – Each row of data in a relation is called a tuple.
c) domain – It is a set of values from which an attribute can take a value in each row.
d) degree – The number of attributes in a relation is called the Degree of the relation.
e) cardinality - The number of tuples in a relation is called the Cardinality of the relation.
3. Explain the limitations of File system.
Ans: 1. Difficulty in Access:
• Files themselves do not provide any mechanism to access data.
• Data maintained in a file system are accessed through application programs.
2. Data Redundancy:
• Redundancy means same data are duplicated in different places (files).
• Redundancy leads to excess storage use and may cause data inconsistency also.
[Link] Inconsistency:
If the same data exists in multiple files and one is updated but not the other, then inconsistency occurs.
For example, name spelling corrections not reflected in all files.
4. Data Isolation:
Files being created in isolation by different person in different formats, it becomes difficult to write separate
programs to retrieve related data.
5. Data Dependence:
Data are stored in a specific format in a file. If the format itself is changed, all the existing application
programs accessing that file also need to be changed.
6. Controlled Data sharing:
Not every user should be able to access all the data stored in file. It is very difficult to maintain the kind of
access control in a file system while accessing files through application programs.

You might also like