0% found this document useful (0 votes)
51 views50 pages

Computer Science Made by MPS

The document discusses exception handling and file handling in Python, covering topics such as built-in exceptions, the use of try-except blocks, and the importance of closing files. It explains various methods for reading and writing files, differentiates between text and binary files, and provides code examples for handling exceptions and file operations. Additionally, it emphasizes best practices for managing exceptions and file resources in Python programming.
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)
51 views50 pages

Computer Science Made by MPS

The document discusses exception handling and file handling in Python, covering topics such as built-in exceptions, the use of try-except blocks, and the importance of closing files. It explains various methods for reading and writing files, differentiates between text and binary files, and provides code examples for handling exceptions and file operations. Additionally, it emphasizes best practices for managing exceptions and file resources in Python programming.
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
You are on page 1/ 50

Chapter 1

Exception Handling in Python


Question 1

"Every syntax error is an exception but every exception cannot be a syntax error." Justify the statement.
Answer
A syntax error is a specific type of exception that is detected when we have not followed the rules of the
particular programming language while writing a program. On the other hand, an exception is a Python
object that represents any type of error or exceptional condition encountered during program execution.
This includes not only syntax errors but also runtime errors and logical errors. Therefore, every syntax error
is an exception but every exception cannot be a syntax error.

Question 2

When are the following built-in exceptions raised? Give examples to support your answers.

1. ImportError
2. IOError
3. NameError
4. ZeroDivisionError

Answer
1. ImportError — It is raised when the requested module definition is not found.
Example :
import module

Output

ModuleNotFoundError: No module named 'module'


2. IOError — It is raised when the file specified in a program statement cannot be opened.
Example :
file = open("file1.txt", "r")

Output

FileNotFoundError: [Errno 2] No such file or directory: 'file1.txt'


3. NameError — It is raised when a local or global variable name is not defined.
Example :
print(var+40)

Output

NameError: name 'var' is not defined.


4. ZeroDivisionError — It is raised when the denominator in a division operation is zero.
Example :
print(50/0)

Output

ZeroDivisionError: division by zero

Question 3

What is the use of a raise statement? Write a code to accept two numbers and display the quotient.
Appropriate exception should be raised if the user enters the second number (denominator) as zero (0).
Answer
The raise statement is used to throw an exception during the execution of a program.
numerator = float(input("Enter the numerator: "))
denominator = float(input("Enter the denominator: "))
if denominator == 0:
raise ZeroDivisionError("Error: Denominator cannot be zero.")
else:
quotient = numerator / denominator
print("Quotient:", quotient)

Output

Enter the numerator: 25


Enter the denominator: 5
Quotient: 5.0

Enter the numerator: 2


Enter the denominator: 0
Traceback (most recent call last):
File "c:\PythonPlayground\q3.py", line 4, in <module>
raise ZeroDivisionError("Error: Denominator cannot be zero.")
ZeroDivisionError: Error: Denominator cannot be zero.

Question 4

Use assert statement in Question No. 3 to test the division expression in the program.
Answer
numerator = float(input("Enter the numerator: "))
denominator = float(input("Enter the denominator: "))
assert denominator != 0, "Error: Denominator cannot be zero."
quotient = numerator / denominator
print("Quotient:", quotient)

Output

Enter the numerator: 12


Enter the denominator: 3
Quotient: 4.0

Enter the numerator: 5


Enter the denominator: 0
Traceback (most recent call last):
File "c:\PythonPlayground\q3.py", line 3, in <module>
assert denominator != 0, "Error: Denominator cannot be zero."
AssertionError: Error: Denominator cannot be zero.

Question 5
Define the following:

1. Exception Handling
2. Throwing an exception
3. Catching an exception

Answer

1. Exception Handling — The process of writing additional code in a program to give proper messages
or instructions to the user upon encountering an exception is known as exception handling.
2. Throwing an exception — Throwing an exception refers to the process of creating an exception
object and passing it to the runtime system or the appropriate exception handler.
3. Catching an exception — Catching an exception refers to the process of executing a suitable
handler or block of code specifically designed to handle that particular exception when it occurs
during program execution.

Question 6

Explain catching exceptions using try and except block.


Answer
An exception is said to be caught when a code that is designed to handle a particular exception is
executed. Exceptions, if any, are caught in the try block and handled in the except block. While writing or
debugging 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. Every try block is followed by an except block. The
appropriate code to handle each of the possible exceptions (in the code inside the try block) are written
inside the except clause. While executing the program, if an exception is encountered, further execution of
the code inside the try block is stopped and the control is transferred to the except block. The syntax of t ry
… except clause is as follows:
try:
[ program statements where exceptions might occur]
except [exception-name]:
[ code for exception handling if the exception-name error is encountered]

Question 7

Consider the code given below and fill in the blanks.


print("Learning Exceptions...")
try:
num1 = int(input("Enter the first number"))
num2 = int(input("Enter the second number"))
quotient = (num1/num2)
print("Both the numbers 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")

Answer
print("Learning Exceptions...")
try:
num1 = int(input("Enter the first number"))
num2 = int(input("Enter the second number"))
quotient = (num1 / num2)
print("Both numbers entered were correct")
except ValueError: # 1 : to enter only integers
print("Please enter only numbers")
except ZeroDivisionError: # 2 : Denominator should not be zero
print("Number 2 should not be zero")
else:
print("Great.. you are a good programmer")
finally: # 3 : to be executed at the end
print("JOB OVER... GO GET SOME REST")

Explanation

1. When using int(input("Enter the first number")) or int(input("Enter the second number")) , the user is expected
to input an integer. If the user enters a non-integer value (like a string or a floating-point number), a
ValueError will be raised during the conversion to an integer. The except ValueError: block is used to
handle this situation by displaying a message asking the user to enter only numbers.
2. In the line quotient = (num1 / num2), if num2 is entered as zero, it will lead to a ZeroDivisionError during
the division operation (num1 / num2). The except ZeroDivisionError: block is used to handle this scenario
by displaying a message informing the user that the second number should not be zero.
3. The finally: block is used to define code that should be executed regardless of whether an exception
occurs or not.

Question 8
You have learnt how to use math module in Class XI. Write a code where you use the wrong number of
arguments for a method (say sqrt() or pow()). Use the exception handling process to catch the ValueError
exception.
Answer
Note — The TypeError occurs when an incorrect number of arguments is provided for a function, while
the ValueError occurs when the number of arguments are correct but they contain inappropriate values.
Hence, in the following code TypeError is raised due to providing an incorrect number of arguments to
the math.sqrt() and math.pow() function and it is handled using except.
import math

try:
result = math.pow(2, 3, 4, 5) # pow() expects 2 arguments,
# but 4 are provided
except TypeError:
print("TypeError occurred with math.pow()")
else:
print("Result:", result)

try:
result = math.sqrt(9, 2) # sqrt() expects 1 argument,
# but 2 are provided
except TypeError:
print("TypeError occurred with math.sqrt()")
else:
print("Result:", result)

Output
TypeError occurred with math.pow()
TypeError occurred with math.sqrt()

Question 9

What is the use of finally clause ? Use finally clause in the problem given in Question No. 7.
Answer
The statements inside the finally block are always executed, regardless of whether an exception has
occurred in the try block or not. It is a common practice to use the finally clause while working with files to
ensure that the file object is closed.
print("Learning Exceptions...")
try:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
quotient = (num1 / num2)
print(quotient)
print("Both numbers entered were correct")
except ValueError:
print("Please enter only numbers")
except ZeroDivisionError:
print("Number 2 should not be zero")
else:
print("Great.. you are a good programmer")
finally:
print("JOB OVER... GO GET SOME REST")

Output
Learning Exceptions...
Enter the first number: 12
Enter the second number: 4
3.0
Both numbers entered were correct
Great.. you are a good programmer
JOB OVER... GO GET SOME REST

Learning Exceptions...
Enter the first number: var
Please enter only numbers
JOB OVER... GO GET SOME REST

Learning Exceptions...
Enter the first number: 33
Enter the second number: 0
Number 2 should not be zero
JOB OVER... GO GET SOME REST
Chapter 2
File Handling in Python

Exercise

Question 1(a)

Differentiate between text file and binary file.


Answer

Text File Binary File

A text file consists of human readable A binary file is made up of non-human readable
characters, which can be opened by any characters and symbols, which require specific
text editor. programs to access its contents.

A text file is a file that stores information


A binary file is a file that stores the information in
in the form of a stream of ASCII or
the form of a stream of bytes.
Unicode characters.
Text File Binary File

In text files, each line of text is terminated


In a binary file, there is no delimiter for a line and
with a special character known as EOL
no character translations occur here.
(End of Line) character.

Files with extensions like .txt, .py, .csv etc Files with extensions like .jpg, .pdf etc are some
are some examples of text files. examples of binary files.

Question 1(b)

Differentiate between readline() and readlines().


Answer

readline() readlines()

The readline() function reads from a file in read The readlines() function, also reads from
mode and returns the next line in the file or a blank a file in read mode and returns a list of
string if there are no more lines. all lines in the file.

The returned data is of string type. The returned data is of list type.
Question 1(c)

Differentiate between write() and writelines().


Answer

write() writelines()

The write() method is used to write a The writelines() method is used to write multiple
single string to a file. strings to a file.

The write() method takes a string as The writelines() method takes an iterable object like
an argument. lists, tuple, etc. containing strings as an argument.

The write() method returns the number The writelines() method does not return the number
of characters written on to the file. of characters written in the file.

Question 2

Write the use and syntax for the following methods:

1. open()
2. read()
3. seek()
4. dump()
Answer
1. open() — The open() method opens the given file in the given mode and associates it with a file
handle. Its syntax is file_object = open(file_name, access_mode) .
2. read() — The read() method is used to read data from a file object. It reads at most 'n' bytes from the
file, where 'n' is an optional parameter. If no 'n' is specified, the read() method reads the entire
contents of the file. Its syntax is: file_object.read(n).
3. seek() — This method is used to position the file object at a particular position in a file. Its syntax
is: file_object.seek(offset [, reference_point]) .
4. dump() — This method is used to convert (pickling) Python objects for writing data in a binary file. Its
syntax is : dump(data_object, file_object) .

Question 3

Write the file mode that will be used for opening the following files. Also, write the Python statements to
open the following files:

1. a text file “example.txt” in both read and write mode.


2. a binary file “bfile.dat” in write mode.
3. a text file “try.txt” in append and read mode.
4. a binary file “btry.dat” in read only mode.

Answer
1. File Mode: 'r+'
fh = open("example.txt", "r+")
2. File Mode: 'wb'
fh = open("bfile.dat", "wb")
3. File Mode: 'a+'
fh = open("try.txt", "a+")
4. File Mode: 'rb'
fh = open("btry.dat", "rb")

Question 4

Why is it advised to close a file after we are done with the read and write operations? What will happen if
we do not close it ? Will some error message be flashed ?
Answer
It is a good practice to close a file once we are done with the read and write operations. When we close a
file, the system frees the memory allocated to it. Python ensures that any unwritten or unsaved data is
flushed (written) to the file before it is closed. Therefore, it is always advised to close the file once our work
is done. If we do not close file explicitly it will close automatically later when it's no longer in use or when
the program terminates, without displaying any error message.

Question 5

What is the difference between the following set of statements (a) and (b):
(a)
P = open("practice.txt", "r")
P.read(10)
(b)
with open("practice.txt", "r") as P:
x = P.read()
Answer
The code given in (a) will open file "practice.txt" in read mode and will read 10 bytes from it. Also, it will not
close the file explicitly. On the other hand, the code given in (b) will open file "practice.txt" in read mode
and will read the entire content of the file. Furthermore, it will automatically close the file after executing the
code due to the with clause.

Question 6

Write a command(s) to write the following lines to the text file named hello.txt. Assume that the file is
opened in append mode.
“ Welcome my class”
“It is a fun place”
“You will learn and play”
Answer
file = open("hello.txt", "a")
lines = [
"Welcome my class\n",
"It is a fun place\n",
"You will learn and play"
]
file.writelines(lines)
file.close()

Question 7
Write a Python program to open the file hello.txt used in question no 6 in read mode to display its contents.
What will be the difference if the file was opened in write mode instead of append mode?
Answer
f = open("hello.txt", "r")
st = " "
while st:
st = f.readlines()
print(st)
f.close()
If the file "hello.txt" was opened in write mode instead of append mode, it would have overwritten the
existing content of the file. In write mode ("w"), opening the file truncates its content if it already exists and
starts writing from the beginning. Therefore, the previous contents of the file would have been replaced
with the new lines provided in the write mode code snippet.

Question 8

Write a program to accept string/sentences from the user till the user enters “END” to. Save the data in a
text file and then display only those sentences which begin with an uppercase alphabet.
Answer
f = open("new.txt", "w")
while True:
st = input("Enter next line:")
if st == "END":
break
f.write(st + '\n')
f.close()
f = open("new.txt", "r")
while True:
st = f.readline()
if not st:
break
if st[0].isupper():
print(st)
f.close()

Output
Enter next line:Hello world
Enter next line:welcome to
Enter next line:Python programming
Enter next line:END
Hello world

Python programming

Question 9

Define pickling in Python. Explain serialization and deserialization of Python object.


Answer
The pickling process serializes objects and converts them into a byte stream so that they can be stored in
binary files.
Serialization is the process of transforming data or an object in memory (RAM) into a stream of bytes
called byte streams. These byte streams, in a binary file, can then be stored on a disk, in a database, or
sent through a network. The serialization process is also called pickling. Deserialization or unpickling is the
inverse of the pickling process, where a byte stream is converted back into a Python object.

Question 10

Write a program to enter the following records in a binary file :


Item No — integer
Item_Name — string
Qty — integer
Price — float
Number of records to be entered should be accepted from the user. Read the file to display the records in
the following format:
Item No :
Item Name :
Quantity :
Price per item :
Amount : ( to be calculated as Price * Qty)
Answer
import pickle

with open("item.dat", 'wb') as itemfile:


n = int(input("How many records to be entered? "))
for i in range(n):
ino = int(input("Enter item no: "))
iname = input("Enter item name: ")
qty = int(input("Enter quantity: "))
price = float(input("Enter price: "))
item = {"Item no": ino, "Item Name": iname, "Qty": qty, "Price": price}
pickle.dump(item, itemfile)
print("Successfully written item data")

with open("item.dat", "rb") as file:


try:
while True:
item = pickle.load(file)
print("\nItem No:", item["Item no"])
print("Item Name:", item["Item Name"])
print("Quantity:", item["Qty"])
print("Price per item:", item["Price"])
print("Amount:", item["Qty"] * item["Price"])
except EOFError:
pass

Output
How many records to be entered? 5
Enter item no: 11
Enter item name: Mobile
Enter quantity: 4
Enter price: 20000
Enter item no: 12
Enter item name: Laptop
Enter quantity: 2
Enter price: 35000
Enter item no: 13
Enter item name: Computer
Enter quantity: 1
Enter price: 50000
Enter item no: 14
Enter item name: Television
Enter quantity: 4
Enter price: 25000

Item No: 11
Item Name: Mobile
Quantity: 4
Price per item: 20000.0
Amount: 80000.0

Item No: 12
Item Name: Laptop
Quantity: 2
Price per item: 35000.0
Amount: 70000.0

Item No: 13
Item Name: Computer
Quantity: 1
Price per item: 50000.0
Amount: 50000.0

Item No: 14
Item Name: Television
Quantity: 4
Price per item: 25000.0
Amount: 100000.0
Stack
Class 12 - NCERT Computer Science Solutions

Exercise

Question 1

State TRUE or FALSE for the following cases:

(a) Stack is a linear data structure.

(b) Stack does not follow LIFO rule.

(c) PUSH operation may result into underflow condition.

(d) In POSTFIX notation for expression, operators are placed after operands.

Answer

(a) True
Reason — A stack is a linear data structure following the Last In, First Out (LIFO) principle, where elements are arranged sequentially.

(b) False
Reason — A stack follows the Last In, First Out (LIFO) rule. In a stack, the last element added is the first one to be removed from the stack.
(c) False
Reason — When attempting to remove an element (POP operation) from an empty stack, it leads to an underflow condition, resulting in an
exception being raised.

(d) True
Reason — In POSTFIX notation for expression, operators are placed after the corresponding operands.

Question 2(a)

Find the output of the following code:

result = 0
numberList = [10, 20, 30]
numberList.append(40)
result = result + numberList.pop()
result = result + numberList.pop()
print("Result=", result)
Answer

Output

Result= 70

Explanation

The code initializes result to 0 and creates a list [10, 20, 30]. It appends 40 to the list and then performs two pop() operations on the list, which
removes and returns the last element (40 and 30). These values are added to result, resulting in result being 70. Finally, the code prints
"Result=" followed by the value of result, which is 70.

Question 2(b)

Find the output of the following code:


answer = []; output = ''
answer.append('T')
answer.append('A')
answer.append('M')
ch = answer.pop()
output = output + ch
ch = answer.pop()
output = output + ch
ch = answer.pop()
output = output + ch
print("Result=", output)
Answer

Output

Result= MAT

Explanation

The code initializes an empty list answer and an empty string output. It appends the characters 'T', 'A', and 'M' to the answer list. After
appending, answer list becomes ['T', 'A', 'M'].
After that, three pop() operations are performed on answer, removing and returning the last element each time ('M', 'A', and 'T' respectively).
These characters are concatenated to the output string. So, output string becomes MAT which is printed as the final output.

Question 3

Write a program to reverse a string using stack.

Answer

def push(stack, item):


stack.append(item)
def pop(stack):
if stack == []:
return
return stack.pop()

def reverse(string):
n = len(string)
stack = []
for i in range(n):
push(stack, string[i])
string = ""
for i in range(n):
string += pop(stack)
return string

string = input("Enter a string: ")


print("String:", string)
reversedStr = reverse(string)
print("Reversed String:", reversedStr)

Output

Enter a string: Hello world


String: Hello world
Reversed String: dlrow olleH

Question 4

For the following arithmetic expression:

((2 + 3) * (4 / 2)) + 2
Show step-by-step process for matching parentheses using stack data structure.

Answer

For matching parentheses, we can push in the stack for each opening parenthesis of the expression and pop from the stack for each closing
parenthesis.

Scanning from left to right:

Symbol Stack Action

( ↑ — top
( Push

((
( Push

2 ..........

+ ..........

3 ..........

) ( Pop

* ..........

((
( Push

4 ..........

/ ..........

2 ..........

(
) Pop

) #Empty Pop

+ ..........

2 #Empty ..........

Empty stack => Balanced Parentheses


Question 5(a)

Evaluate following postfix expression while showing status of stack after each operation given A = 3, B = 5, C = 1, D = 4.

AB + C *

Answer

AB + C * = 35 + 1 *

Scanning from left to right :

Intermediate
Symbol Action Stack
output

3
3 Push

53
5 Push

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

18
1 Push

#Empty

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

Hence, AB + C * = 35 + 1 * = 8

Question 5(b)

Evaluate following postfix expression while showing status of stack after each operation given A = 3, B = 5, C = 1, D = 4.

AB * C / D *

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 15
1 Push

#Empty

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


4 15
4 Push

#Empty

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

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

Question 6(a)

Convert the following infix notation to postfix notation, showing stack and string contents at each step.

A+B-C*D

Answer

Given,

A+B-C*D

Scanning from left to right :

Postfix
Symbol Action Stack
Expression
A

+ A
+ Push in stack

B AB

-
- Equal precedence to +. Pop from stack, add in expression then push this operator(-) AB+

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

D AB+CD

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

Postfix notation of A + B - C * D = AB+CD*-

Question 6(b)
Convert the following infix notation to postfix notation, showing stack and string contents at each step.

A * (( C + D)/E)

Answer

Given,

A * (( C + D)/E)

Scanning from left to right:

Symbol Action Stack Postfix Expression

*
* Push

(* A
( Push

((*
( Push

C

+((* 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 add popped operator to expression ACD+E/

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

Postfix notation of A * (( C + D)/E) = ACD+E/*


Question 7

Write a program to create a Stack for storing only odd numbers out of all the numbers entered by the user. Display the content of the Stack along
with the largest odd number in the Stack. (Hint. Keep popping out the elements from stack and maintain the largest element retrieved so far in a
variable. Repeat till Stack is empty)

Answer

def push(stack, item):


stack.append(item)

def pop(stack):
if stack == []:
return
return stack.pop()

def oddStack(num):
if num % 2 == 1:
push(stack, num)

def GetLargest(stack):
elem = pop(stack)
large = elem
while elem != None:
if large < elem:
large = elem
elem = pop(stack)
return large

n = int(input("How many numbers?"))


stack = []
for i in range(n):
number = int(input("Enter number:"))
oddStack(number)
print("Stack created is", stack)
bigNum = GetLargest(stack)
print("Largest number in stack", bigNum)

Output

How many numbers?8


Enter number:1
Enter number:2
Enter number:3
Enter number:4
Enter number:5
Enter number:6
Enter number:7
Enter number:8
Stack created is [1, 3, 5, 7]
Largest number in stack 7
Chapter 4
Queue
Class 12 - NCERT Computer Science Solutions
Exercise

Question 1

Fill in the blank

(a) ............... is a linear list of elements in which insertion and deletion takes place from different ends.

(b) Operations on a queue are performed in ............... order.

(c) Insertion operation in a queue is called ............... and deletion operation in a queue is called ............... .

(d) Deletion of elements is performed from ............... end of the queue.

(e) 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.

(f) ............... is a data structure where elements can be added or removed at either end, but not in the middle.
(g) 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

(a) Queue

(b) FIFO

(c) enqueue, dequeue

(d) front

(e) 'A', 'S', 'D', 'F'

(f) Deque

(g)

deletionFront()
deletionRear()
deletionRear()
deletionFront()
deletionFront()

Question 2

Compare and contrast queue with stack.

Answer
Stack Queue

Stack follows LIFO (Last in First out) principle. Queue follows FIFO (First in First out) principle.

In queue, insertion occurs at the rear end and deletion occurs


In stack, insertion and deletion occurs at one end only.
at the front end.

In stack, Push operation is used for element insertion and Pop In queue, enqueue is used for element insertion and dequeue
operation is used for element deletion. is used for element deletion.

There are no variations of stack. A queue may be circular or deque.

Question 3

How does FIFO describe queue ?

Answer

FIFO, First In First Out, defines a queue because in a queue, elements are retrieved from one end (called the front end) and inserted at another
end (rear end). Thus, at any time, in a queue, retrieval gets the oldest element, while always adding to the rear of the queue. Thus, items are
processed in first-in, first-out (FIFO) order.

Question 4

Write a menu driven python program using queue, to implement movement of shuttlecock in it's box.

Answer
queue = []

def display_queue():
if not queue:
print("Queue is empty")
else:
print("Current queue:", queue)

def enqueue(item):
queue.append(item)

def dequeue():
if queue:
removed = queue.pop(0)
print("Removed", removed, "from the queue")
else:
print("Queue is empty, cannot remove")

while True:
print("\nMENU:")
print("1. Add movement to the queue")
print("2. Remove movement from the queue")
print("3. Display current queue")
print("4. Exit")

choice = input("Enter your choice (1-4): ")

if choice == '1':
movement = input("Enter the movement (up/down): ")
enqueue(movement)
print("Added", movement, "to the queue")
elif choice == '2':
dequeue()
elif choice == '3':
display_queue()
elif choice == '4':
print("Exiting program...")
break
else:
print("Invalid choice, please try again")

Output

MENU:
1. Add movement to the queue
2. Remove movement from the queue
3. Display current queue
4. Exit
Enter your choice (1-4): 1
Enter the movement (up/down): up
Added up to the queue

MENU:
1. Add movement to the queue
2. Remove movement from the queue
3. Display current queue
4. Exit
Enter your choice (1-4): 1
Enter the movement (up/down): down
Added down to the queue

MENU:
1. Add movement to the queue
2. Remove movement from the queue
3. Display current queue
4. Exit
Enter your choice (1-4): 3
Current queue: ['up', 'down']

MENU:
1. Add movement to the queue
2. Remove movement from the queue
3. Display current queue
4. Exit
Enter your choice (1-4): 2
Removed up from the queue

MENU:
1. Add movement to the queue
2. Remove movement from the queue
3. Display current queue
4. Exit
Enter your choice (1-4): 3
Current queue: ['down']

MENU:
1. Add movement to the queue
2. Remove movement from the queue
3. Display current queue
4. Exit
Enter your choice (1-4): 4
Exiting program...

Question 5

How is queue data type different from deque data type?


Answer

Queues only allow insertion in one end (rear end) and retrieval from the other end (front end). A deque, on the other hand, is a double-ended
queue, which allows flexibility with insertion or deletion such that one of these operations is allowed at both ends rather than having a fixed end
for the operations.

Question 6

Show the status of queue after each operation

enqueue(34)
enqueue(54)
dequeue()
enqueue(12)
dequeue()
enqueue(61)
peek()
dequeue()
dequeue()
dequeue()
dequeue()
enqueue(1)
Answer

34

enqueue(34) ↑↑

fr
34 54

enqueue(54) ↑ ↑

f r

54

dequeue() ↑↑

fr

54 12

enqueue(12) ↑ ↑

f r

12

dequeue() ↑↑

fr
12 61

enqueue(61) ↑ ↑

f r

Peek() 12

61

dequeue() ↑↑

fr

dequeue() #Empty

dequeue() underflow

dequeue() underflow

1
enqueue(1)
↑↑
fr

Question 7

Show the status of deque after each operation.

peek()
insertFront(12)
insertRear(67)
deletionFront()
insertRear(43)
deletionRear()
deletionFront()
deletionRear()
Answer

peek() #Empty

12

insertFront(12) ↑↑

fr

insertRear(67) 12 67
↑ ↑

f r

67

deletionfront() ↑↑

fr

67 43

insertRear(43) ↑ ↑

f r

67

deletionRear() ↑↑

fr

deletionfront() #Empty
deletionRear() Underflow

Question 8

Write a python program to check whether the given string is palindrome or not, using deque. (Hint : refer to algorithm 4.1)

Answer

def Deque():
return []

def addRear(deque, ch):


deque.append(ch)

def removeFront(deque):
if len(deque) == 0:
return None
return deque.pop(0)

def removeRear(deque):
if len(deque) == 0:
return None
return deque.pop()

def palchecker(aString):
chardeque = Deque()
for ch in aString:
addRear(chardeque, ch)
while len(chardeque) > 1:
first = removeFront(chardeque)
last = removeRear(chardeque)
if first != last:
return False
return True

string1 = input("Enter a string: ")


pal = palchecker(string1.lower())
if pal:
print(string1, "is a palindrome.")
else:
print(string1, "is not a palindrome.")

Output

Enter a string: anupama


anupama is not a palindrome.

Enter a string: malayalam


malayalam is a palindrome.

You might also like