12 IIT PB3 – ANSWER KEY
SECTION – A 1 X 18 = 18
1. c. Error
2. machine[capacity]+=4500
3. AttributeError: 'tuple' object has no attribute 'clear'
4. b. in
5. ['Mumbai', 'Delhi']
6. a b c=100 200 300
7. d. ("f","o","obar")
8. (d) ‘rb+’
9. (a) start(10)
10. b. Optical fiber
11. 19 27
12. 20
13. a) Global variables can only be read inside the function declaring the
variable as global inside the function.
14. a) x , y = 20
15. d) 15
16. a) if - keyword
b) roll_no - identifier
c) “hello” - string literal value
d) 0j - complex literal value
17. (a) Both A and R are true and R is the correct explanation for A
18. (c) a- true, r-false
SECTION – B 2 X 7 = 14
19. Overflow Underflow
Stack Overflow occurs when an Stack Underflow occurs when an
attempt is made to push an item onto attempt is made to pop an item
a stack that is already full. In this from a stack that is empty. This
case, there is no more space means there are no elements to
available to add new elements. remove from the stack.
Cause: Overflow happens when the
Cause: Underflow happens when
stack exceeds its fixed size
there is no data in the stack. It
(maximum capacity). It happens
happens during a pop operation
during a push operation when the
when the stack is empty.
stack is full.
Example: Consider a stack with a Example: If the stack is empty
capacity of 3. After pushing 3 and you try to pop an element
Overflow Underflow
elements, if you try to push another
from it, an underflow occurs.
element, an overflow occurs.
Stack = []
Stack = [A, B, C]
Trying to pop causes Underflow.
Trying to push D causes Overflow.
Effect: The stack cannot
Effect: There are no elements to
accommodate more elements beyond
remove, leading to a potential
its capacity. The program may throw
error or exception indicating
an overflow error or handle it using an
underflow.
exception.
Illustrative Example:
1. Overflow Example:
python
Copy
stack = [1, 2, 3] # Stack is full with a max size of 3
# Trying to push 4 causes overflow
[Link](4) # This would be an overflow if the stack has a limited
size
In this case, if the stack has a fixed capacity of 3, attempting to push a
fourth item will cause an overflow.
2. Underflow Example:
python
Copy
stack = [] # Empty stack
# Trying to pop from an empty stack causes underflow
[Link]() # This will cause underflow since the stack is empty
Here, since the stack is empty, trying to perform a pop operation causes
an underflow.
20. def say(message, times=1):
print(message * times, end=' ')
say('Hello and ', times=10)
say('World')
21. Coaxial Cable Fiber Optic Cable
Electrical signals transmitted Light signals transmitted through
through copper. glass/plastic fibers.
Lower bandwidth and slower Higher bandwidth and much faster
data speeds. data speeds.
22. Referential integrity is a concept in relational database
management systems (RDBMS) that ensures relationships between
tables remain consistent. Specifically, it ensures that a foreign key
in one table correctly points to a valid primary key in another table
(or the same table). This helps prevent orphaned records (i.e.,
records that reference non-existent data) and maintains the
integrity of the database structure.
The referential integrity constraint ensures that relationships
between tables remain consistent by making sure foreign keys
always refer to valid primary keys. To enforce this, the foreign key
must match the primary key’s data type, and mechanisms such as
cascading updates/deletes may be implemented to maintain
consistency when records are changed.
23. a. [1, 2, 3, 4] [1, 2, 3, 4, 10] [1, 2, 3, 4, 10]
b. [30, 18, 10]
24. (a) degree - 9
cardinality - 15.
(b) SUPCODE
(c) SUP
PID PNAME QTY PRICE COMPANY SNAME CITY
CODE
DIGITAL
101 120 12000 RENBIX S01 GET ALL INC KOLKATTA
CAMERA
DIGITAL DIGI BUSY
102 100 22000 DIGI POP S02 CHENNAI
PAD GROUP
PEN DRIVE
104 500 1100 STORE KING S01 GET ALL INC KOLKATTA
16GB
LED DISP DIGI BUSY
106 70 28000 S02 CHENNAI
SCREEN EXPERTS GROUP
EASY
CAR GPS
105 60 12000 MOVEON S03 MARKET DELHI
SYSTEM
CORP
(d) CREATE TABLE prod AS SELECT * FROM product;
25. (a) Expansion
SMTP: Simple Mail Transfer Protocol
HTTP: HyperText Transfer Protocol
(b) POP3 IMAP
Emails are stored on the
Emails are downloaded and
server, and accessed
stored locally on the device.
remotely.
Does not sync actions (e.g., Syncs actions across all
POP3 IMAP
devices (e.g., delete,
delete, move) across devices.
move).
SECTION – C 3 X 5 = 15
26. def countNow(PLACES):
for key, place in [Link]():
if len(place) > 5 and place[0].upper() in ['L', 'M', 'N']:
print([Link]())
PLACES = {1: "Delhi", 2: "London", 3: "Paris", 4: "New York", 5: "Doha"}
countNow(PLACES)
27. a. SELECT DEPT, AVG(EXP) AS AVG_EXP
FROM Staff
WHERE GENDER = 'F'
GROUP BY DEPT;
b. SELECT * FROM Staff
WHERE DEPT = 'SALES' AND GENDER = 'M'
ORDER BY EXP DESC;
c. SELECT NAME FROM Staff
WHERE GENDER = 'F' AND YEAR(DOJ) = 2006 AND
NAME LIKE '%A';
d. SELECT * FROM Staff
WHERE DEPT NOT IN ('FINANCE', 'SALES');
e. ALTER TABLE Staff
ADD COLUMN bonus DECIMAL(10, 2) AFTER GENDER;
f. SELECT DEPT, GENDER, COUNT(*) AS TOTAL
FROM Staff
WHERE EXP > 12
GROUP BY DEPT, GENDER;
28. a) def vowelwords():
with open("[Link]", "r") as file1,
open("[Link]", "w") as file2:
content = [Link]()
words = [Link]()
filtered_words = []
for word in words:
if word[0].upper() not in ['A', 'E', 'I', 'O', 'U']:
filtered_words.append(word)
[Link](" ".join(filtered_words))
#main block
vowelwords()
b) def count_lines_with_a():
count = 0
with open("[Link]", "r") as file:
lines = [Link]()
for line in lines:
if [Link]().endswith('a'):
count += 1
print(f"Number of lines ending with 'a': {count}")
#main block
count_lines_with_a()
29. CREATE DATABASE Company;
USE Company;
CREATE TABLE Employee (
Empid INT(5) PRIMARY KEY,
Empname CHAR(25) NOT NULL,
Design CHAR(15) UNIQUE,
Salary FLOAT,
Dob DATE
);
DESCRIBE Employee;
30. def push_to_stack(emp_dict, stack):
for name, salary in emp_dict.items():
if len(name) % 2 == 0 and salary < 85000:
[Link](name)
def pop_and_display(stack):
while stack:
print([Link](), end=" ")
if not stack:
print("\nStack Underflow")
Emp = {
"Ajay": 76000, "Jyothi": 150000,
"David": 89000, "Remya": 65000,
"Karthika": 90000, "Vijay": 82000 }
stack = []
push_to_stack(Emp, stack)
pop_and_display(stack)
SECTION – D 5 X 3 = 15
31. a) fiber optic cable
star topology
b) Wing s more [Link] computers
c) The HUB/SWITCH should be placed in a central location
within the ADMIN (A) wing
d) Wi-Fi router or wireless access point
e) ADMIN
Fiber Optic
SENIOR JUNIOR HOSTEL
f) Firewall
g) iii) BRIDGE
h) (i)switch
i) d) VoIP
j) radio waves / microwaves
32. (a) Advantage of Using a CSV File for Permanent Storage:
The main advantage of using a CSV (Comma Separated Values)
file for permanent storage is its simplicity and portability. Here’s
why:
1. Simple Structure: CSV files are text-based and have a simple
format (comma-separated values), making them easy to
understand and manipulate.
2. Portability: CSV files are widely supported across many
systems, applications, and programming languages. They can
be easily opened in spreadsheet programs (like Excel),
databases, and text editors.
3. Lightweight: CSV files are typically smaller in size and don't
require additional complex software to read or write data,
making them efficient for storing tabular data.
b)
import csv
def add_record():
with open('[Link]', mode='a', newline='') as file:
writer = [Link](file)
roll_number = input("Enter Roll Number: ")
name = input("Enter Name: ")
class_name = input("Enter Class: ")
[Link]([roll_number, name, class_name])
print("Record added successfully.")
def display_class_records(class_name):
with open('[Link]', mode='r') as file:
reader = [Link](file)
count = 0
found_records = False
for row in reader:
if row[2] == class_name:
print(f"Roll No: {row[0]}, Name: {row[1]}, Class: {row[2]}")
count += 1
found_records = True
if found_records:
print(f"\nTotal students in class {class_name}: {count}")
else:
print(f"No records found for class {class_name}.")
while True:
print("\n1. Add/Insert Record")
print("2. Display Records of a Given Class")
print("3. Exit")
choice = input("Enter your choice (1/2/3): ")
if choice == '1':
add_record()
elif choice == '2':
class_name = input("Enter the class name to search for: ")
display_class_records(class_name)
elif choice == '3':
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")
33. Function Operation Type Description Example
remove() Removes the Removes the first [Link](3)
first occurrence occurrence of the specified (removes 3 from
Function Operation Type Description Example
of a value from value. If the value is not
the list)
the list found, it raises a ValueError.
Deletes an element by index
Deletes an
or can remove the entire list del lst[2] (deletes
element at a
del (e.g., del lst). It raises an the element at
specific index or
IndexError if the index is out index 2)
the entire list
of range.
Removes and returns the
Removes and
element at a specified index [Link](1) (removes
returns an
pop() (defaults to the last item if no and returns the
element at a
index is given). Raises element at index 1)
specified index
IndexError if the list is empty.
(b) (i)
import pickle
def CreateEmp():
with open("[Link]", "ab") as file:
EID = int(input("Enter Employee ID: "))
Ename = input("Enter Employee Name: ")
designation = input("Enter Designation: ")
salary = float(input("Enter Salary: "))
employee = [EID, Ename, designation, salary]
[Link](employee, file)
print("Employee record added successfully.")
(b) (ii)
import pickle
def display():
try:
with open("[Link]", "rb") as file:
while True:
employee = [Link](file)
print(f"EID: {employee[0]}, Name: {employee[1]},
Designation: {employee[2]}, Salary: {employee[3]}")
except EOFError:
print("All employee details displayed.")
SECTION – E 4X2=8
34. import [Link]
# Establishing the connection to MySQL
dataBase = [Link](
host="localhost", user="user",
passwd="password", database="gfg" )
# Checking connection established or not
if dataBase.is_connected():
print("Connection established with MySQL")
# Preparing a cursor object
cursorObject = [Link]()
# Creating table
studentRecord = """CREATE TABLE STUDENT (
NAME VARCHAR(100) NOT NULL,
BRANCH VARCHAR(50), ROLL INT NOT NULL,
SECTION VARCHAR(5), AGE INT )"""
# Table creation
[Link](studentRecord)
# Table description
[Link]("DESCRIBE STUDENT")
# Display the table structure
des = [Link]()
for row in des:
print(row)
# Disconnecting from the server
[Link]()
else:
print("Connection not established with MySQL")
35.
a. Exception vs Error
Exception Error
An exception is an event that occurs
An error is a serious issue that
during the execution of a program,
typically occurs during the execution
which disrupts the normal flow of the
or compiling phase, and it is usually
program and can be handled using
fatal to the program, making it
exception handling mechanisms like try-
unable to continue or recover.
except in Python.
Exceptions are usually caused by Errors are typically caused by more
issues that can be recovered from, such severe issues, such as problems
as invalid user input or a file not found, with the system, environment, or
and can often be handled to ensure the programming bugs, and often cannot
program continues running. be handled or recovered from easily.
+EG. +EG.
b. Website vs Web Portal
Website Web Portal
A website is a collection of web A web portal is a web-based platform
pages that are usually that provides a personalized, single point
informational, showcasing content, of access to various resources, tools, and
products, or services to the general services, often for a specific group of
public. users.
Web portals are interactive, and users
Websites are generally static or
typically log in to access personalized
dynamic in nature and are designed
data, services, or tools such as forums,
to provide information to a wide
news, and applications tailored to their
audience.
needs.
+EG. +EG.