0% found this document useful (0 votes)
0 views

Kaish Sample Paper

The document explains the difference between mutable and immutable objects in Python, providing examples of each. It also covers various operators, Python functions for manipulating lists and tuples, SQL commands for database management, and stack operations. Additionally, it includes code snippets for reading and processing CSV files, along with expected outputs for specific queries.

Uploaded by

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

Kaish Sample Paper

The document explains the difference between mutable and immutable objects in Python, providing examples of each. It also covers various operators, Python functions for manipulating lists and tuples, SQL commands for database management, and stack operations. Additionally, it includes code snippets for reading and processing CSV files, along with expected outputs for specific queries.

Uploaded by

Rahul Rudra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

22.

Difference Between Mutable and Immutable Objects in Python

In Python, objects are categorized as mutable or immutable based on whether their values
can be changed after creation.

 Mutable Objects: These objects can be changed after they are created. Their contents
(elements or attributes) can be modified without changing the object’s identity
(memory address).
 Immutable Objects: These objects cannot be changed after they are created. Any
modification results in the creation of a new object in memory.

Identifying Mutable and Immutable Objects

From the given list:

1. Tuple (1,2) → Immutable ✅


2. List [1,2] → Mutable ✅
3. Dictionary {1:1, 2:2} → Mutable ✅
4. String '123' → Immutable ✅

Final Answer

 Mutable Object: [1,2] (List)


 Immutable Object: (1,2) (Tuple)

23. (I) Arithmetic Operators

Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication, etc.

Examples:

1. Addition (+) → 5 + 3 = 8
2. Multiplication (*) → 4 * 2 = 8

(II) Relational Operators

Relational operators (also called comparison operators) are used to compare two values and
return True or False.

Examples:

1. Greater than (>) → 10 > 5 → True


2. Less than or equal to (<=) → 7 <= 7 → True
24. Here are the answers using Python's built-in functions:

(I) Choose One:

A) Count the occurrences of 4 in L1


L1.count(4)

This returns the number of times 4 appears in L1.

OR

B) Sort the elements of L1 in ascending order


L1.sort()

This sorts L1 in place (modifies the original list).


Alternatively, if you want a new sorted list without modifying L1:

sorted_L1 = sorted(L1)

(II) Choose One:

A) Insert all elements of L2 at the end of L1


L1.extend(L2)

This appends all elements of L2 to L1.

OR

B) Reverse the elements of L2


L2.reverse()

This reverses L2 in place (modifies the original list).


Alternatively, if you want a new reversed list without modifying L2:

reversed_L2 = L2[::-1]

25. Understanding the Code:


import random
a = "Wisdom"
b = random.randint(1, 6) # Generates a random integer between 1 and 6
(inclusive)
for i in range(0, b, 2): # Loops from 0 to (b-1) with a step of 2
print(a[i], end='#') # Prints character at index `i` followed by `#`

Possible Values of b
Since b is chosen randomly from {1, 2, 3, 4, 5, 6}, the minimum possible value is 1,
and the maximum is 6.

Loop Behavior

 The loop iterates from 0 to b-1 in steps of 2.


 The printed output depends on b because the range will only include indexes within
[0, b-1].

Checking Outputs

Let's analyze for different values of b:

b Value Loop Range range(0, b, 2) Characters Printed Output Format


1 [0] W# (A) ✅
2 [0] W# (A) ✅
3 [0,2] W#s# (C) ✅
4 [0,2] W#s# (C) ✅
5 [0,2,4] W#s#o# Not listed ❌
6 [0,2,4] W#s#o# Not listed ❌

Final Answer:

 Correct outputs: (A) and (C)


 Minimum value of b: 1
 Maximum value of b: 6

26. Here is the corrected version of the code, with errors underlined and fixed:

Errors and Fixes:

1. Syntax Error: Missing colon (:) after the function header.


o Correction: def swap_first_last(tup):
2. Indentation Error: The return statement should be indented properly.
o Correction: return tup is indented properly.
3. Logical Error: tup[0] should be a tuple, but (tup[0]) is just an integer.
o Correction: (tup[0],) instead of (tup[0])
4. Syntax Error: Missing comma in print() statement.
o Correction: print("Swapped tuple:", result)

Corrected Code:
def swap_first_last(tup): # **Fixed missing colon**
if len(tup) < 2:
return tup # **Fixed indentation**
new_tup = (tup[-1],) + tup[1:-1] + (tup[0],) # **Fixed tuple
creation**
return new_tup

result = swap_first_last((1, 2, 3, 4))


print("Swapped tuple:", result) # **Fixed missing comma**

Expected Output:
Swapped tuple: (4, 2, 3, 1)

27. (I) Choose One:

A) Constraint to Prevent Duplicates but Allow NULL

The UNIQUE constraint ensures that all values in the column are distinct, but it allows NULL values.

CREATE TABLE Example (


column_name INT UNIQUE
);

OR

B) Constraint to Prevent NULL but Allow Duplicates

The NOT NULL constraint ensures that the column cannot have NULL values, but duplicates are
allowed.

CREATE TABLE Example (


column_name INT NOT NULL
);

(II) Choose One:

A) SQL Command to Remove the Primary Key from MOBILE Table


ALTER TABLE MOBILE DROP PRIMARY KEY;

(Note: This works only if no foreign key references M_ID.)

OR

B) SQL Command to Add M_ID as the Primary Key in MOBILE Table


ALTER TABLE MOBILE ADD PRIMARY KEY (M_ID);

28. (I) Choose One:


A) Star Topology

✅ Advantage:

 Easy to troubleshoot and maintain – Since all devices are connected to a central hub, it is
easier to identify and fix issues.

❌ Disadvantage:

 Single point of failure – If the central hub or switch fails, the entire network goes down.

B) SMTP

✅ Expansion: Simple Mail Transfer Protocol

✅ Use:
SMTP is used for sending emails over the internet. It facilitates communication between email
clients and mail servers to deliver outgoing messages.

30. (I) Choose One:

A) Python Function to Display Words Containing @cmail from "Emails.txt"


def find_cmail_emails():
with open("Emails.txt", "r") as file:
for line in file:
words = line.split()
for word in words:
if "@cmail" in word:
print(word)

# Call the function


find_cmail_emails()

Explanation:

 Opens "Emails.txt" in read mode.


 Reads each line, splits it into words, and checks for "@cmail" in each word.
 Prints the matching words.

B) Python Function to Display Words Longer Than 5 Characters from "Words.txt"


def find_long_words():
with open("Words.txt", "r") as file:
for line in file:
words = line.split()
for word in words:
if len(word) > 5:
print(word)
# Call the function
find_long_words()

Explanation:

 Opens "Words.txt" in read mode.


 Reads each line, splits it into words, and checks if the word length is greater than 5.
 Prints the matching words.

31. Here are the Python implementations for both (A) Stack Operations for BooksStack and (B)
Stack Operations for Even Numbers.

(A) Stack Operations for BooksStack


# Function to push a new book record onto the stack
def push_book(BooksStack, new_book):
BooksStack.append(new_book)

# Function to pop the topmost book record from the stack


def pop_book(BooksStack):
if not BooksStack: # Check if stack is empty
print("Underflow")
return None
return BooksStack.pop()

# Function to display the topmost book record without deleting it


def peep(BooksStack):
if not BooksStack: # Check if stack is empty
print(None)
else:
print(BooksStack[-1])

# Example Usage
BooksStack = []
push_book(BooksStack, ["The Great Gatsby", "F. Scott Fitzgerald", 1925])
push_book(BooksStack, ["To Kill a Mockingbird", "Harper Lee", 1960])
push_book(BooksStack, ["1984", "George Orwell", 1949])

print("Peep (Top Book):")


peep(BooksStack) # Displays the topmost book

print("Popped Book:", pop_book(BooksStack)) # Removes and displays the


topmost book
print("Peep (After Pop):")
peep(BooksStack) # Displays the new top book after popping

(B) Stack Operations for Even Numbers


EvenNumbers = [] # Stack for storing even numbers

# Function to push only even numbers into the stack


def push_even(N):
for num in N:
if num % 2 == 0: # Check if number is even
EvenNumbers.append(num)
# Function to pop the topmost even number from the stack
def pop_even():
if not EvenNumbers: # Check if stack is empty
print("Empty")
return None
return EvenNumbers.pop()

# Function to display all even numbers in the stack without deleting them
def Disp_even():
if not EvenNumbers: # Check if stack is empty
print(None)
else:
print(EvenNumbers)

# Example Usage
VALUES = [10, 5, 8, 3, 12]
push_even(VALUES) # Store even numbers in stack

print("Stack after pushing even numbers:")


Disp_even() # Display stack contents

print("Popped Even Number:", pop_even()) # Remove and display topmost even


number
print("Stack after popping:")
Disp_even() # Display updated stack

Expected Output (for (B)):


Stack after pushing even numbers:
[10, 8, 12]
Popped Even Number: 12
Stack after popping:
[10, 8]

Both implementations follow stack principles (LIFO - Last In, First Out) and handle edge cases like
underflow conditions. 🚀

31. (I) Predict the Output of the First Code Snippet


d = {"apple": 15, "banana": 7, "cherry": 9}
str1 = ""
for key in d:
str1 = str1 + str(d[key]) + "@" + "\n"
str2 = str1[:-1]
print(str2)
Step-by-step Execution:

1. d is a dictionary:

json
CopyEdit
{"apple": 15, "banana": 7, "cherry": 9}
2. Loop Iteration:
o For "apple", str1 = "15@\n"
o For "banana", str1 = "15@\n7@\n"
o For "cherry", str1 = "15@\n7@\n9@\n"
3. str2 = str1[:-1], which removes the last newline \n, resulting in:

"15@\n7@\n9@"

4. Final Printed Output:

15@
7@
9@

(II) Predict the Output of the Second Code Snippet


line = [4, 9, 12, 6, 20]
for i in line:
for j in range(1, i % 5):
print(j, '#', end="")
print()
Step-by-step Execution:

1. Iteration over line: [4, 9, 12, 6, 20]


2. Inner loop executes for range(1, i % 5), calculating i % 5:
o 4 % 5 = 4 → range(1, 4) → 1 2 3
o 9 % 5 = 4 → range(1, 4) → 1 2 3
o 12 % 5 = 2 → range(1, 2) → 1
o 6 % 5 = 1 → range(1, 1) → (No output)
o 20 % 5 = 0 → range(1, 0) → (No output)

Final Printed Output:


1 #2 #3 #
1 #2 #3 #
1 #

Final Answers:

1. First Code Output:

15@
7@
9@

2. Second Code Output:

1 #2 #3 #
1 #2 #3 #
1 #

32. (A) Writing SQL Queries:


(I) Display the total Quantity for each Product, excluding products with total
quantity less than 5:
SELECT Product, SUM(Quantity) AS Total_Quantity
FROM Orders
GROUP BY Product
HAVING SUM(Quantity) >= 5;

✅ Explanation:

 Groups data by Product and calculates the total Quantity.


 Uses HAVING to exclude products where SUM(Quantity) < 5.

(II) Display the Orders table sorted by total price (Quantity * Price) in
descending order:
SELECT *, (Quantity * Price) AS Total_Price
FROM Orders
ORDER BY Total_Price DESC;

✅ Explanation:

 Calculates Total_Price as Quantity * Price.


 Orders results in descending order.

(III) Display distinct customer names ( C_Name) from the Orders table:
SELECT DISTINCT C_Name FROM Orders;

✅ Explanation:

 Fetches unique customer names.

(IV) Display the sum of Price for orders where Quantity is NULL:
SELECT SUM(Price) AS Total_Price_Null_Quantity
FROM Orders
WHERE Quantity IS NULL;

✅ Explanation:

 Filters rows where Quantity is NULL.


 Sums up Price for those rows.

(B) Writing the Output:

(I) Output for:


SELECT c_name, SUM(quantity) AS total_quantity
FROM Orders
GROUP BY c_name;
✅ Output (assuming more records exist):

C_Name | Total_Quantity
-------------------------
Jitendra | 1
Mustafa | 2
Dhwani | 1
...

(Each customer's total quantity is displayed.)

(II) Output for:


SELECT * FROM Orders WHERE Product LIKE '%phone%';

✅ Output:

O_Id | C_Name | Product | Quantity | Price


-----------------------------------------------
1003 | Dhwani | Headphone | 1 | 1500
...

(Shows records where Product contains "phone".)

(III) Output for:


SELECT O_Id, C_Name, Product, Quantity, Price
FROM Orders
WHERE Price BETWEEN 1500 AND 12000;

✅ Output:

O_Id | C_Name | Product | Quantity | Price


-----------------------------------------------
1001 | Jitendra | Laptop | 1 | 12000
1003 | Dhwani | Headphone | 1 | 1500
...

(Displays orders where Price is between 1500 and 12000.)

(IV) Output for:


SELECT MAX(Price) FROM Orders;

✅ Output (assuming highest price is 12000):

markdown
CopyEdit
MAX(Price)
12000
33. (I) Read and Display Records Where Population > 5,000,000
import csv

def display_large_population():
with open("Happiness.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
country, population, sample_size, happy = row
if int(population) > 5000000:
print(row)

# Call the function


display_large_population()

✅ Explanation:

 Opens "Happiness.csv" in read mode.


 Reads each row and extracts population.
 Converts population to int and checks if it's greater than 5,000,000.
 If true, prints the record.

(II) Count the Number of Records in the File


def count_records():
with open("Happiness.csv", "r") as file:
reader = csv.reader(file)
count = sum(1 for _ in reader) # Counts number of rows
print("Total Records:", count)

# Call the function


count_records()

✅ Explanation:

 Opens "Happiness.csv" in read mode.


 Iterates through all rows and counts them using sum(1 for _).
 Prints the total number of records.

Example Output (for a sample file)

If "Happiness.csv" contains:
Country,Population,Sample_Size,Happy
Signiland,5673000,5000,3426
Happyland,3000000,4000,2900
Joytopia,8000000,6000,4900
Expected Output:
['Signiland', '5673000', '5000', '3426']
['Joytopia', '8000000', '6000', '4900']
Total Records: 3
34. (I) Display complete details (from both tables) for faculties whose salary is
less than 12000.
SELECT FACULTY.*, COURSES.*
FROM FACULTY
LEFT JOIN COURSES ON FACULTY.F_ID = COURSES.F_ID
WHERE FACULTY.Salary < 12000;

✅ Explanation:

 LEFT JOIN is used to combine both tables based on F_ID.


 Filters faculties with Salary < 12000.

(II) Display details of courses where Fees is between 20000 and 50000 (both
inclusive).
SELECT * FROM COURSES
WHERE Fees BETWEEN 20000 AND 50000;

✅ Explanation:

 BETWEEN ensures selection of fees from 20000 to 50000 (both included).

✅ Expected Output:

C_ID | F_ID | CName | Fees


-----------------------------------------
C21 | 102 | Grid Computing | 40000
C25 | 102 | Computer Network | 20000

(III) Increase the fees of all courses by 500 that have "Computer" in their
course name.
UPDATE COURSES
SET Fees = Fees + 500
WHERE CName LIKE '%Computer%';

✅ Explanation:

 LIKE '%Computer%' filters courses containing "Computer" in their name.


 UPDATE increases their fees by 500.

✅ Affected Courses:

C23 | Computer Security | 8000 → 8500


C25 | Computer Network | 20000 → 20500
(IV)

(A) Display faculty names (FName, LName) who are teaching System Design.
SELECT FName, LName
FROM FACULTY
WHERE F_ID = (SELECT F_ID FROM COURSES WHERE CName = 'System Design');

✅ Expected Output:

FName | LName
------------------------
Sulekha | Srivastava

(B) Display the Cartesian Product of the two tables.


SELECT * FROM FACULTY, COURSES;

✅ Explanation:

 This will produce all possible combinations of rows from FACULTY and COURSES (Cross Join).

✅ Expected Output (Partial, assuming 5 faculty × 6 courses = 30 rows):

F_ID | FName | LName | Hire_Date | Salary | C_ID | F_ID | CName


| Fees
---------------------------------------------------------------------------
--------------
102 | Amit | Mishra | 12-10-98 | 12000 | C21 | 102 | Grid Computing
| 40000
102 | Amit | Mishra | 12-10-98 | 12000 | C22 | 106 | System Design
| 16000
...

35. Here’s the Python function to connect to the ITEMDB database, insert an item into the
STATIONERY table, and then display records where the price is greater than 120.

Python Function for Add and Display


import mysql.connector

def AddAndDisplay():
try:
# Establish connection to MySQL database
conn = mysql.connector.connect(
host="localhost",
user="root",
password="Pencil",
database="ITEMDB"
)
cursor = conn.cursor()

# Input item details from user


itemNo = int(input("Enter Item Number: "))
itemName = input("Enter Item Name: ")
price = float(input("Enter Price: "))
qty = int(input("Enter Quantity: "))

# Insert record into STATIONERY table


insert_query = "INSERT INTO STATIONERY (itemNo, itemName, price,
qty) VALUES (%s, %s, %s, %s)"
cursor.execute(insert_query, (itemNo, itemName, price, qty))
conn.commit()
print("Item added successfully!")

# Fetch and display records where price > 120


select_query = "SELECT * FROM STATIONERY WHERE price > 120"
cursor.execute(select_query)
records = cursor.fetchall()

# Display the records


if records:
print("\nItems with price greater than 120:")
for record in records:
print(record)
else:
print("\nNo items found with price greater than 120.")

except mysql.connector.Error as err:


print("Error:", err)

finally:
# Close connection
if conn.is_connected():
cursor.close()
conn.close()
print("Database connection closed.")

# Call the function


AddAndDisplay()

Explanation:

✅ Step 1: Connects to the ITEMDB MySQL database.


✅ Step 2: Takes user input for itemNo, itemName, price, and qty.
✅ Step 3: Inserts the record into the STATIONERY table.
✅ Step 4: Retrieves and displays records where price > 120.
✅ Step 5: Handles exceptions and ensures the database connection is closed.

Example Run:

User Input:
Enter Item Number: 101
Enter Item Name: Notebook
Enter Price: 150
Enter Quantity: 5
Expected Output:
Item added successfully!

Items with price greater than 120:


(101, 'Notebook', 150, 5)

Database connection closed.

36. (I) Function to Input Data and Append it to a Binary File

We will store candidate data in a binary file named "candidates.dat", using the pickle module.

import pickle

def add_candidate():
try:
# Open file in append-binary mode
with open("candidates.dat", "ab") as file:
Candidate_ID = int(input("Enter Candidate ID: "))
Candidate_Name = input("Enter Candidate Name: ")
Designation = input("Enter Designation: ")
Experience = float(input("Enter Experience (in years): "))

# Store data as a dictionary


candidate = {
"Candidate_ID": Candidate_ID,
"Candidate_Name": Candidate_Name,
"Designation": Designation,
"Experience": Experience
}

# Write data to file


pickle.dump(candidate, file)
print("Candidate record added successfully!")

except Exception as e:
print("Error:", e)

# Call the function


add_candidate()

✅ Explanation:

 Takes candidate details as input.


 Stores them as a dictionary.
 Appends the data to the binary file "candidates.dat" using pickle.dump().

(II) Function to Update Candidates with Experience > 10 Years


We will read, modify, and rewrite the file to update candidates with experience greater than 10
years.

def update_designation():
try:
candidates = []

# Open file in read-binary mode


with open("candidates.dat", "rb") as file:
while True:
try:
candidate = pickle.load(file)
# Check and update designation
if candidate["Experience"] > 10:
candidate["Designation"] = "Senior Manager"
candidates.append(candidate)
except EOFError:
break # End of file

# Write updated data back to file


with open("candidates.dat", "wb") as file:
for candidate in candidates:
pickle.dump(candidate, file)

print("Updated candidates with experience > 10 years to 'Senior


Manager'.")

except Exception as e:
print("Error:", e)

# Call the function


update_designation()

✅ Explanation:

 Reads all candidate records from "candidates.dat".


 Updates the designation to "Senior Manager" if experience is greater than 10 years.
 Rewrites the file with updated data.

(III) Function to Display Candidates Who Are NOT "Senior Manager"


def display_non_senior_managers():
try:
# Open file in read-binary mode
with open("candidates.dat", "rb") as file:
print("\nCandidates who are NOT 'Senior Manager':")
while True:
try:
candidate = pickle.load(file)
if candidate["Designation"] != "Senior Manager":
print(candidate)
except EOFError:
break # End of file

except FileNotFoundError:
print("File not found! Please add some candidate records first.")
except Exception as e:
print("Error:", e)

# Call the function


display_non_senior_managers()

✅ Explanation:

 Reads the file and displays candidates who are NOT "Senior Manager".
 Handles file errors (e.g., if file doesn’t exist).

Example Run:

1️⃣ Adding Candidates


Enter Candidate ID: 101
Enter Candidate Name: Rohan Kumar
Enter Designation: Analyst
Enter Experience (in years): 12
Candidate record added successfully!

2️⃣ Updating Candidates with >10 Years Experience


Updated candidates with experience > 10 years to 'Senior Manager'.

3️⃣ Displaying Non-"Senior Manager" Candidates


Candidates who are NOT 'Senior Manager':
{'Candidate_ID': 102, 'Candidate_Name': 'Aisha Sharma', 'Designation':
'Data Scientist', 'Experience': 5}
{'Candidate_ID': 103, 'Candidate_Name': 'Vikram Singh', 'Designation':
'Software Engineer', 'Experience': 8}

37. (I) Most Appropriate Location for the Server

The server should be placed in the ADMIN block because:

 It has the highest number of computers (30), which ensures fastest access for the majority
of users.
 The ADMIN block is centrally located, minimizing latency and ensuring efficient
communication with other blocks.
 Most administrative tasks and data management are likely to be handled here.

(II) Hardware Device to Connect Computers Within Each Building

A Switch should be used in each building to connect all computers within that block because:
 Switches allow faster and efficient communication between multiple devices.
 They reduce network congestion and allow for full-duplex communication (simultaneous
send/receive).
 They support high-speed LAN (Local Area Network) connections.

(III) Cable Layout & Best Cable Choice for Efficient Data Transfer

Cable Layout Strategy:

1. Use Fiber Optic Cable as the backbone to connect all four buildings because it provides
high-speed, long-distance transmission with minimal data loss.
2. Use CAT6 Ethernet cables within each building to connect computers to the switch.

Suggested Cable Layout:

📍 Cable connections using Fiber Optic:

 ADMIN ↔ MEDIA (96m)


 ADMIN ↔ DECORATORS (48m)
 ADMIN ↔ FOOD (42m)
 FOOD ↔ MEDIA (58m)
 FOOD ↔ DECORATORS (46m)
 MEDIA ↔ DECORATORS (42m)

💡 Why Fiber Optic?

 Higher bandwidth (up to 100 Gbps)


 Long-distance capability with low signal loss
 Better security against signal interception

(IV) Is a Repeater Required?

A repeater is NOT required in the Mumbai campus because:

 The longest distance between any two blocks is 96 meters (ADMIN ↔ MEDIA), which is
well within the limit for fiber optic cables (~2 km before signal degradation).
 Fiber optic cables provide low signal attenuation over short distances.

(V) Recommended Communication & Network Type

(A) Best Communication Method Between Mumbai & Delhi

✅ Recommended Option: Video Conferencing


📌 Justification:
 Real-time face-to-face interaction for better communication.
 Useful for meetings, training sessions, and discussions between Mumbai & Delhi.
 Provides visual cues, which emails, telephony, or instant messaging lack.

(B) Type of Network in Mumbai Campus

 The Mumbai campus will have a LAN (Local Area Network) because:
o All computers are within a single geographical location.
o The distance between buildings is under 100 meters, making LAN the most efficient
choice.
o LAN allows fast data transfer with low latency.

Final Summary of Recommendations

Requirement Recommendation Justification

Highest number of computers, central


Server Location ADMIN Block
location, admin tasks

Hardware Device for Efficient data transfer, reduces congestion,


Switch
Buildings full-duplex communication

Fiber Optic Backbone +


Cable Type High-speed, long-distance, secure
CAT6 Ethernet

Fiber optic handles long distances without


Repeater Needed? No
signal loss

Best Communication
Video Conferencing Real-time, face-to-face communication
with Delhi

Network Type in Mumbai


LAN (Local Area Network) Short distance, high-speed connectivity
Campus

You might also like