0% found this document useful (0 votes)
2 views21 pages

Python QB Answers

Uploaded by

omairkhankabbadi
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)
2 views21 pages

Python QB Answers

Uploaded by

omairkhankabbadi
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

PYTHON PROGRAMMING

U24CS201 — Question Bank Answer Key

All Units | 11-Mark & 13-Mark Questions

Department of AI & DS • Year I • Semester II

Meenakshi Sundararajan Engineering College

■ Important / PYQ questions are marked with stars

■ PYQ = Previous Year Question (Anna University) ■ IMPORTANT = Frequently asked / High-weightage
UNIT 1 — PYTHON BASICS, DATA TYPES &
FUNCTIONS

Q21. (11 Marks) ■ IMPORTANT


Question: Write a Python program to find the Armstrong number.
Answer:
An Armstrong number (also called a narcissistic number) is a number that equals the sum of its own digits
each raised to the power of the number of digits. For example, 153 = 1³ + 5³ + 3³.
Algorithm: (1) Input a number. (2) Count digits. (3) Sum each digit raised to the count power. (4) Compare sum
to original.
def is_armstrong(n): digits = str(n) power = len(digits) total = sum(int(d) ** power for d
in digits) return total == n # Check a single number num = int(input("Enter a number: "))
if is_armstrong(num): print(f"{num} is an Armstrong number") else: print(f"{num} is NOT an
Armstrong number") # Print all Armstrong numbers up to 1000 print("\nArmstrong numbers up
to 1000:") for i in range(1, 1001): if is_armstrong(i): print(i, end=" ")

Output (for input 153): 153 is an Armstrong number


Armstrong numbers up to 1000: 1 2 3 4 5 6 7 8 9 153 370 371 407

Q22. (11 Marks) ■ IMPORTANT


Question: Function-Based Calculator: Create a calculator using functions. Sample Input: 10 5 + →
Sample Output: 15
Answer:
A function-based calculator uses separate functions for each arithmetic operation, improving modularity and
readability.
def add(a, b): return a + b def subtract(a, b): return a - b def multiply(a, b): return a *
b def divide(a, b): if b == 0: raise ValueError("Cannot divide by zero!") return a / b def
calculator(): a = float(input("Enter first number : ")) b = float(input("Enter second
number: ")) op = input("Enter operator (+, -, *, /): ") operations = {'+': add, '-':
subtract, '*': multiply, '/': divide} if op in operations: result = operations[op](a, b)
print(f"Result: {result}") else: print("Invalid operator!") calculator()

Sample Output: Enter first number: 10 | Enter second number: 5 | Enter operator: + | Result: 15.0
Q23. (11 Marks)
Question: Debugging: Identify and fix the errors in Q1–Q5 code snippets (Mutable Default, Return
vs Print, Scope, Recursion, etc.)
Answer:
Q1 – Mutable Default Argument Bug: Default mutable list is shared across calls.
# WRONG def func(x=[]): [Link](2) return x # CORRECT — use None as default def
func(x=None): if x is None: x = [] [Link](2) return x

Q2 – Return vs Print: print() returns None, so result is None.


# CORRECT def add(a, b): return a + b # use return, not print result = add(3, 4)
print(result) # Output: 7

Q3 – Function reference passed instead of call:


# CORRECT def func(x): return x * x print(func(2) + func(3)) # 4 + 9 = 13

Q4 – Variable Scope (UnboundLocalError):


# CORRECT x = 5 def func(): global x # declare global x = x + 1 return x print(func()) #
Output: 6

Q5 – Recursion Missing Base Case:


# CORRECT def fun(n): if n == 0: # base case return 0 return n + fun(n - 1) print(fun(3)) #
Output: 6

Q24. (11 Marks)


Question: Circular Rotation of n Variables: Rotate values of n variables circularly.
Answer:
Circular left rotation: the first element moves to the end, all others shift left.
def circular_left_rotate(lst): if not lst: return lst first = lst[0] lst[:-1] = lst[1:] #
shift left lst[-1] = first # place first at end return lst n = int(input("Enter number of
elements: ")) lst = list(map(int, input("Enter elements: ").split())) print("After left
rotation:", circular_left_rotate(lst))

One-liner using slicing:


lst = [1, 2, 3, 4, 5] rotated = lst[1:] + lst[:1] print(rotated) # [2, 3, 4, 5, 1]

Q25. (11 Marks) ■ IMPORTANT


Question: Write a Python program to calculate the current age of a person with the date of birth.
Answer:
from datetime import date def calculate_age(dob): today = [Link]() age = [Link] -
[Link] # subtract 1 if birthday hasn't occurred yet this year if ([Link],
[Link]) < ([Link], [Link]): age -= 1 return age # Input from user year =
int(input("Enter birth year : ")) month = int(input("Enter birth month: ")) day =
int(input("Enter birth day : ")) dob = date(year, month, day) print(f"Your current age is:
{calculate_age(dob)} years")

Sample Output: Enter birth year: 2005 | Enter birth month: 6 | Enter birth day: 15 | Your current age is: 19 years

Q26. (11 Marks)


Question: Write a Python program to swap two numbers using temporary variables.
Answer:
# Method 1 — Using a temporary variable a = int(input("Enter first number : ")) b =
int(input("Enter second number: ")) print(f"Before swap: a = {a}, b = {b}") temp = a a = b
b = temp print(f"After swap : a = {a}, b = {b}") # Method 2 — Python tuple unpacking
(Pythonic) a, b = b, a print(f"After swap (tuple): a = {a}, b = {b}") # Method 3 — Using
arithmetic a = a + b b = a - b a = a - b print(f"After swap (arith): a = {a}, b = {b}")
Q27. (13 Marks) ■ PYQ — Anna University
Question: Write a simple Python script to perform all arithmetic operations.
Answer:
def add(a, b): return a + b def subtract(a, b): return a - b def multiply(a, b): return a *
b def divide(a, b): return a / b if b != 0 else "Undefined (div by 0)" def floor_div(a, b):
return a // b if b != 0 else "Undefined" def modulus(a, b): return a % b if b != 0 else
"Undefined" def power(a, b): return a ** b a = float(input("Enter first number : ")) b =
float(input("Enter second number: ")) print(f"\nAddition : {a} + {b} = {add(a, b)}")
print(f"Subtraction : {a} - {b} = {subtract(a, b)}") print(f"Multiplication : {a} * {b} =
{multiply(a, b)}") print(f"Division : {a} / {b} = {divide(a, b)}") print(f"Floor Division
: {a} // {b} = {floor_div(a, b)}") print(f"Modulus : {a} % {b} = {modulus(a, b)}")
print(f"Exponentiation : {a} ** {b} = {power(a, b)}")

Sample Output (a=10, b=3): Addition: 13.0 | Subtraction: 7.0 | Multiplication: 30.0 | Division: 3.333 | Floor
Division: 3.0 | Modulus: 1.0 | Exponentiation: 1000.0

Q28. (13 Marks) ■ PYQ — Anna University


Question: What is a statement? Explain Assignment and Print statements. Demonstrate rules of
precedence.
Answer:
Statement: A statement is a unit of code that Python can execute. Types include assignment, print, if, for, while,
return, etc.
Assignment Statement: Binds a value (or expression result) to a variable name.
x = 10 # simple assignment a = b = c = 5 # chained assignment x, y = 3, 7 # tuple unpacking
x += 1 # augmented assignment (x = x + 1)

Print Statement (function in Python 3):


print("Hello, World!") print("a =", 10, "b =", 3.14) print(f"Sum = {10 + 3}") # f-string
print("pi =", round(3.14159, 2))

Operator Precedence (PEMDAS/BODMAS — highest to lowest):


1. Parentheses () 2. Exponentiation ** 3. Unary -, + 4. *, /, //, % 5. +, - 6. Comparison 7. Logical (not, and, or)
print(2 + 3 * 4) # 14 (multiplication first) print((2 + 3) * 4) # 20 (parentheses override)
print(2 ** 3 ** 2) # 512 (right-associative: 2**(3**2)=2**9) print(10 - 4 + 2) # 8 (left to
right) print(10 / 2 * 3) # 15.0

Q29. (13 Marks)


Question: Find Data Type Frequency: Count occurrences of int, float, string, and boolean in input.
Answer:
def find_type_frequency(data): freq = {"Integer": 0, "Float": 0, "String": 0, "Boolean":
0} for item in data: # Check Boolean BEFORE int (bool is subclass of int) if
isinstance(item, bool): freq["Boolean"] += 1 elif isinstance(item, int): freq["Integer"]
+= 1 elif isinstance(item, float): freq["Float"] += 1 elif isinstance(item, str):
freq["String"] += 1 return freq # Taking mixed input data = [10, 5.5, "hello", True, 20,
"world", False] freq = find_type_frequency(data) for dtype, count in [Link]():
print(f"{dtype}: {count}")

Output: Integer: 2 | Float: 1 | String: 2 | Boolean: 2


Key insight: In Python, bool is a subclass of int, so isinstance(True, int) returns True. Always check for bool
first.
Q30. (13 Marks)
Question: Write a Python program to check if a number is odd or even.
Answer:
def check_odd_even(n): if n % 2 == 0: return "Even" else: return "Odd" # Single number num
= int(input("Enter a number: ")) print(f"{num} is {check_odd_even(num)}") # Check multiple
numbers numbers = list(map(int, input("Enter numbers separated by space: ").split())) for
n in numbers: print(f"{n} -> {check_odd_even(n)}") # One-liner using ternary result =
"Even" if num % 2 == 0 else "Odd" print(f"Using ternary: {num} is {result}")

Q31. (13 Marks) ■ IMPORTANT


Question: Write a Python program to find the distance between two points.
Answer:
Distance formula: d = √((x2-x1)² + (y2-y1)²)
import math def euclidean_distance(x1, y1, x2, y2): return [Link]((x2 - x1)**2 + (y2 -
y1)**2) def manhattan_distance(x1, y1, x2, y2): return abs(x2 - x1) + abs(y2 - y1) x1, y1
= map(float, input("Enter point 1 (x y): ").split()) x2, y2 = map(float, input("Enter
point 2 (x y): ").split()) print(f"Euclidean distance :
{euclidean_distance(x1,y1,x2,y2):.4f}") print(f"Manhattan distance :
{manhattan_distance(x1,y1,x2,y2):.4f}")

Sample Output (points (0,0) and (3,4)): Euclidean distance: 5.0000 | Manhattan distance: 7.0000

Q32. (13 Marks)


Question: Write a Python program to display product lists/items in the grocery store.
Answer:
grocery_store = { "Fruits" : [("Apple", 45.0), ("Banana", 30.0), ("Mango", 80.0)],
"Vegetables": [("Tomato", 25.0), ("Onion", 20.0), ("Potato", 18.0)], "Dairy" : [("Milk",
60.0), ("Curd", 40.0), ("Butter",120.0)], } print("=" * 45) print(f"{'GROCERY STORE —
PRODUCT LIST':^45}") print("=" * 45) for category, items in grocery_store.items():
print(f"\n {[Link]()}") print(" " + "-" * 35) for name, price in items: print(f"
{name:<20} Rs. {price:>6.2f}") print("=" * 45) print(f"Total categories:
{len(grocery_store)}") total_items = sum(len(v) for v in grocery_store.values())
print(f"Total items : {total_items}")
UNIT 2 — CONTROL FLOW, STRINGS & RECURSION

Q11. (11 Marks) ■ PYQ — Anna University


Question: Write a Python program to generate the pattern: A A A A A A A A A A (triangle of A's).
Answer:
# Pattern: increasing A's per row rows = 5 for i in range(1, rows + 1): print(("A " *
i).strip()) # Output: # A # A A # A A A # A A A A # A A A A A

The outer loop controls rows; the inner repetition multiplies 'A' by row number.

Q12. (11 Marks) ■ PYQ — Anna University


Question: Write a Python program to check palindrome ignoring case and special characters.
Answer:
import re def is_palindrome(s): # Keep only alphanumeric, convert to lowercase cleaned =
[Link](r'[^a-zA-Z0-9]', '', s).lower() return cleaned == cleaned[::-1] test_cases =
["racecar", "A man a plan a canal Panama", "hello", "Was it a car or a cat I saw"] for s in
test_cases: result = "Palindrome" if is_palindrome(s) else "Not a Palindrome"
print(f'"{s}" -> {result}')

Output: 'racecar' → Palindrome | 'A man a plan a canal Panama' → Palindrome | 'hello' → Not a Palindrome

Q13. (11 Marks) ■ IMPORTANT


Question: Automate student grading using conditional statements and functions.
Answer:
def get_grade(marks): if marks >= 90: return 'O (Outstanding)' elif marks >= 80: return
'A+ (Excellent)' elif marks >= 70: return 'A (Very Good)' elif marks >= 60: return 'B+
(Good)' elif marks >= 50: return 'B (Average)' elif marks >= 40: return 'C (Pass)' else:
return 'F (Fail)' def process_student(name, marks): grade = get_grade(marks) status =
"PASS" if marks >= 40 else "FAIL" print(f"Student: {name:<15} Marks: {marks:>3} Grade:
{grade} Status: {status}") n = int(input("Enter number of students: ")) for _ in range(n):
name = input("Student name : ") marks = int(input("Marks (0-100): "))
process_student(name, marks)

Why if-elif-else? It evaluates conditions sequentially and stops at the first true one, making it ideal for
range-based grading without overlapping checks.

Q14. (11 Marks) ■ PYQ — Anna University


Question: Write a program that prints 1 to 50: 'Fizz' if div by 3, 'Buzz' if div by 5, 'FizzBuzz' if both.
Answer:
for i in range(1, 51): if i % 3 == 0 and i % 5 == 0: print("FizzBuzz", end=" ") elif i % 3
== 0: print("Fizz", end=" ") elif i % 5 == 0: print("Buzz", end=" ") else: print(i, end="
")

Output (1-20): 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz ...

Q15. (11 Marks)


Question: Write a Python program to get a string input and find the number of vowels.
Answer:
def count_vowels(s): vowels = "aeiouAEIOU" count = 0 vowel_found = [] for ch in s: if ch in
vowels: count += 1 vowel_found.append(ch) return count, vowel_found text = input("Enter a
string: ") count, found = count_vowels(text) print(f"Number of vowels: {count}")
print(f"Vowels found : {found}") # One-liner print(sum(1 for c in text if c in
"aeiouAEIOU"))

Sample (input='Hello World'): Number of vowels: 3 | Vowels found: ['e', 'o', 'o']
Q16. (11 Marks) ■ IMPORTANT
Question: Analyze employee salary list: total, average, and employees earning above average.
Answer:
employees = [ ("Alice", 55000), ("Bob", 72000), ("Carol", 48000), ("Dave", 90000), ("Eve",
63000), ] salaries = [sal for _, sal in employees] total = sum(salaries) average = total /
len(salaries) print(f"Total Salary : Rs. {total:,}") print(f"Average Salary : Rs.
{average:,.2f}") print("\nEmployees earning above average:") for name, sal in employees:
if sal > average: print(f" {name:<10} Rs. {sal:,}")

Output: Total: Rs. 3,28,000 | Average: Rs. 65,600 | Above average: Bob (72000), Dave (90000)

Q17. (13 Marks) ■ PYQ — Anna University


Question: Write a program to determine the factorial of a given number with and without recursion.
Answer:
Method 1 — Iterative (without recursion):
def factorial_iterative(n): if n < 0: return "Undefined for negative numbers" result = 1
for i in range(2, n + 1): result *= i return result

Method 2 — Recursive:
def factorial_recursive(n): if n < 0: return "Undefined" if n == 0: return 1 # base case
return n * factorial_recursive(n - 1) n = int(input("Enter number: ")) print(f"Iterative :
{n}! = {factorial_iterative(n)}") print(f"Recursive : {n}! = {factorial_recursive(n)}") #
Built-in import math print(f"[Link]: {[Link](n)}")

Sample Output (n=5): Iterative: 5! = 120 | Recursive: 5! = 120


Trace of recursive call for n=4: factorial(4) → 4×factorial(3) → 4×3×factorial(2) → 4×3×2×factorial(1) →
4×3×2×1×1 = 24

Q18. (13 Marks)


Question: Text-processing system: perform string operations (concatenate, reverse, compare,
etc.) based on op code.
Answer:
def text_operations(s1, s2, op): ops = { 'concat' : lambda: s1 + s2, 'reverse' : lambda:
s1[::-1], 'upper' : lambda: [Link](), 'lower' : lambda: [Link](), 'compare' : lambda:
"Equal" if s1 == s2 else ("s1>s2" if s1>s2 else "s1<s2"), 'length' : lambda: (len(s1),
len(s2)), 'count' : lambda: [Link](s2), 'replace' : lambda: [Link](s2, "***"),
'palindrome': lambda: "Palindrome" if s1==s1[::-1] else "Not Palindrome", } return
[Link](op, lambda: "Unknown operation")() s1 = input("Enter string 1: ") s2 =
input("Enter string 2: ") op = input("Enter operation
(concat/reverse/upper/lower/compare/length/count/replace/palindrome): ") print("Result:",
text_operations(s1, s2, op))

Q19. (13 Marks) ■ PYQ — Anna University


Question: Compute GCD using Euclidean algorithm, compute LCM, check if numbers are coprime.
Answer:
def gcd(a, b): while b: a, b = b, a % b # Euclidean algorithm return a def lcm(a, b):
return abs(a * b) // gcd(a, b) def are_coprime(a, b): return gcd(a, b) == 1 a =
int(input("Enter first number : ")) b = int(input("Enter second number: "))
print(f"GCD({a}, {b}) = {gcd(a, b)}") print(f"LCM({a}, {b}) = {lcm(a, b)}")
print(f"Coprime? {'Yes' if are_coprime(a,b) else 'No'}") # Verify with math module import
math print(f"Verified GCD (math): {[Link](a, b)}")

Euclidean Algorithm trace (a=48, b=18): gcd(48,18) → gcd(18,12) → gcd(12,6) → gcd(6,0) = 6


Sample Output: GCD(12,8)=4 | LCM(12,8)=24 | Coprime: No
Q20. (13 Marks)
Question: Compute sum of individual digits and reverse of a given integer using two functions.
Answer:
def sum_of_digits(n): n = abs(n) # handle negatives total = 0 while n > 0: total += n % 10
n //= 10 return total def reverse_integer(n): negative = n < 0 n = abs(n) reversed_n =
int(str(n)[::-1]) return -reversed_n if negative else reversed_n num = int(input("Enter an
integer: ")) print(f"Sum of digits : {sum_of_digits(num)}") print(f"Reversed :
{reverse_integer(num)}")

Sample (n=12345): Sum = 1+2+3+4+5 = 15 | Reversed = 54321

Q21(U2). (13 Marks)


Question: Find the first number between 1 and N divisible by 7 but NOT by 3. Use loops only.
Answer:
n = int(input("Enter N: ")) found = -1 for i in range(1, n + 1): if i % 7 == 0 and i % 3 !=
0: found = i break print(found) # prints -1 if none found # Explanation: # i % 7 == 0 →
divisible by 7 # i % 3 != 0 → NOT divisible by 3

Sample (N=50): Output = 7 (7÷7=1 ✓, 7÷3=2.33 → not divisible ✓)

Q22(U2). (13 Marks)


Question: Convert each character to ASCII, add 2, convert back to string using functional style.
Answer:
# Functional style using map and lambda def shift_string(s, shift=2): shifted = map(lambda
c: chr(ord(c) + shift), s) return ''.join(shifted) text = input("Enter a string: ") result
= shift_string(text) print(f"Original : {text}") print(f"Shifted : {result}") #
Step-by-step for 'abc': # 'a' -> 97+2=99 -> 'c' # 'b' -> 98+2=100-> 'd' # 'c' -> 99+2=101->
'e' => 'cde'

Sample (input='abc'): Shifted: 'cde'


UNIT 3 — LISTS, TUPLES, DICTIONARIES & SORTING

Q21(U3). (11 Marks) ■ IMPORTANT


Question: Merge duplicate shopping cart items by summing quantities using loops and
dictionaries.
Answer:
cart = [ {"item": "apple", "qty": 3}, {"item": "banana", "qty": 2}, {"item": "apple",
"qty": 1}, {"item": "orange", "qty": 4} ] merged = {} for entry in cart: name =
entry["item"] qty = entry["qty"] if name in merged: merged[name] += qty else: merged[name]
= qty result = [{"item": k, "qty": v} for k, v in [Link]()] print(result) #
[{'item': 'apple', 'qty': 4}, {'item': 'banana', 'qty': 2}, {'item': 'orange', 'qty': 4}]

Q22(U3). (11 Marks) ■ IMPORTANT


Question: Write a program to perform Quick Sort algorithm.
Answer:
Quick Sort picks a pivot, partitions the list, and recursively sorts sub-lists. Average O(n log n).
def quick_sort(arr): if len(arr) <= 1: return arr # base case pivot = arr[len(arr) // 2] #
middle element as pivot left = [x for x in arr if x < pivot] mid = [x for x in arr if x ==
pivot] right = [x for x in arr if x > pivot] return quick_sort(left) + mid +
quick_sort(right) arr = list(map(int, input("Enter numbers: ").split())) print("Sorted:",
quick_sort(arr))

Sample: Input: 3 6 8 10 1 2 1 → Sorted: [1, 1, 2, 3, 6, 8, 10]

Q23(U3). (11 Marks)


Question: Rotate an array to the left by d positions. Input: n d, then n integers. Output: rotated list.
Answer:
n, d = map(int, input().split()) arr = list(map(int, input().split())) d = d % n # handle
d > n rotated = arr[d:] + arr[:d] print(*rotated) # Sample: n=5 d=2 arr=[1,2,3,4,5] -> 3 4
5 1 2

Q24(U3). (11 Marks)


Question: Calculate average marks of a student by name query.
Answer:
n = int(input()) students = {} for _ in range(n): line = input().split() name = line[0]
scores = list(map(float, line[1:])) students[name] = scores query = input() if query in
students: avg = sum(students[query]) / len(students[query]) print(f"{avg:.2f}") else:
print("Student not found") # Malika: (52+56+60)/3 = 56.00

Sample Output: 56.00

Q25(U3). (11 Marks) ■ PYQ — Anna University


Question: Perform list operations based on commands: insert, append, remove, pop, sort, reverse,
print.
Answer:
lst = [] n = int(input()) for _ in range(n): cmd = input().split() op = cmd[0] if op ==
"insert": [Link](int(cmd[1]), int(cmd[2])) elif op == "append":
[Link](int(cmd[1])) elif op == "remove": [Link](int(cmd[1])) elif op == "pop":
[Link]() elif op == "sort": [Link]() elif op == "reverse": [Link]() elif op ==
"print": print(lst)
Q26(U3). (11 Marks)
Question: Find the frequency of each element in tuple test_tup = (4, 5, 4, 5, 6, 6, 5).
Answer:
test_tup = (4, 5, 4, 5, 6, 6, 5) # Method 1 — Manual dictionary freq = {} for item in
test_tup: freq[item] = [Link](item, 0) + 1 print(freq) # {4: 2, 5: 3, 6: 2} # Method 2 —
Counter from collections import Counter print(dict(Counter(test_tup)))

Output: {4: 2, 5: 3, 6: 2}

Q27(U3). (13 Marks) ■ PYQ — Anna University


Question: Shop items with names and prices; store using OrderedDict, print total price per item in
insertion order.
Answer:
from collections import OrderedDict n = int(input()) od = OrderedDict() for _ in range(n):
parts = input().rsplit(' ', 1) # split on last space to handle multi-word names name =
parts[0] price = int(parts[1]) if name in od: od[name] += price else: od[name] = price for
name, total in [Link](): print(name, total)

Sample Input: 9 lines of item+price → Output: BANANA FRIES 24 | POTATO CHIPS 60 | APPLE JUICE 20 |
CANDY 15

Q28(U3). (13 Marks) ■ IMPORTANT


Question: Rank students using Merge Sort on marks.
Answer:
def merge_sort(arr): if len(arr) <= 1: return arr mid = len(arr) // 2 left =
merge_sort(arr[:mid]) right = merge_sort(arr[mid:]) return merge(left, right) def
merge(left, right): result, i, j = [], 0, 0 while i < len(left) and j < len(right): if
left[i] <= right[j]: [Link](left[i]); i += 1 else: [Link](right[j]); j += 1
return result + left[i:] + right[j:] n = int(input("Enter number of students: ")) marks =
list(map(int, input("Enter marks: ").split())) print("Sorted Marks:", merge_sort(marks)) #
Input: 5 78 45 90 32 67 -> [32, 45, 67, 78, 90]

Time Complexity: O(n log n) — suitable for large datasets.

Q29(U3). (13 Marks)


Question: Use Insertion Sort to maintain a sorted list of product prices added one by one.
Answer:
def insertion_sort(arr): for i in range(1, len(arr)): key = arr[i] j = i - 1 while j >= 0
and arr[j] > key: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key return arr n =
int(input("Enter number of products: ")) prices = list(map(int, input("Enter prices:
").split())) print("Sorted Prices:", insertion_sort(prices)) # Input: 4 1200 800 1500 600
-> [600, 800, 1200, 1500]

Q30(U3). (13 Marks)


Question: Arrange student roll numbers in ascending order using Selection Sort.
Answer:
def selection_sort(arr): n = len(arr) for i in range(n): min_idx = i for j in range(i + 1,
n): if arr[j] < arr[min_idx]: min_idx = j arr[i], arr[min_idx] = arr[min_idx], arr[i]
return arr rolls = list(map(int, input("Enter roll numbers: ").split())) print("Sorted
Roll Numbers:", selection_sort(rolls))

How it works: Find the minimum in the unsorted portion and swap it to the front. Repeat for each position.
Time: O(n²).
Q31(U3). (13 Marks)
Question: Shop: multiple customers buy items; store in OrderedDict, calculate total price per item.
Answer:
from collections import OrderedDict import sys n = int(input()) od = OrderedDict() for _
in range(n): *name_parts, price = input().split() name = ' '.join(name_parts) price =
int(price) od[name] = [Link](name, 0) + price for k, v in [Link](): print(k, v)

This is identical to Q27 logic extended to multi-word item names split on last space token.

Q32(U3). (13 Marks) ■ PYQ — Anna University


Question: Recollect various dictionary operations and explain them with examples.
Answer:
Dictionary: An unordered (Python 3.7+ ordered by insertion), mutable collection of key-value pairs. Keys must
be unique and hashable.
# Creation d = {"name": "Alice", "age": 21, "city": "Chennai"} # Access print(d["name"]) #
Alice print([Link]("email", "N/A")) # N/A (safe access) # Add / Update d["email"] =
"alice@[Link]" # add d["age"] = 22 # update # Delete del d["city"] # remove key val =
[Link]("email") # remove and return value # Iteration for key, val in [Link](): print(key,
"->", val) print(list([Link]())) print(list([Link]())) # Membership print("name" in d) #
True # Other methods d2 = [Link]() # shallow copy [Link]({"grade": "A"}) # merge another
dict [Link]() # empty the dict # Dict comprehension squares = {x: x**2 for x in range(1,
6)} print(squares) # {1:1, 2:4, 3:9, 4:16, 5:25}

Q33(U3). (13 Marks)


Question: Write a program to create a Histogram using Dictionary.
Answer:
def create_histogram(data): freq = {} for item in data: freq[item] = [Link](item, 0) + 1
return freq def print_histogram(freq): print("\nHistogram:") print("-" * 30) for key in
sorted(freq): bar = "#" * freq[key] print(f"{key:>5} | {bar} ({freq[key]})") print("-" *
30) # Example: grades grades = list(input("Enter data (space-separated): ").split()) freq
= create_histogram(grades) print_histogram(freq) # Sample Input: A B A C B A D B C A # A |
#### (4) # B | ### (3) # C | ## (2) # D | # (1)
UNIT 4 — FILES, EXCEPTIONS, MODULES &
FUNCTIONAL TOOLS

Q21(U4). (11 Marks) ■ PYQ — Anna University


Question: Write a Python program to: Create a text file, write multiple lines, read and display
content.
Answer:
# Writing to a file filename = "[Link]" with open(filename, "w") as f: [Link]("Hello,
World!\n") [Link]("Python file handling is easy.\n") [Link]("This is the third line.\n")
print("File created and written successfully!") # Reading the file with open(filename,
"r") as f: content = [Link]() print("\nFile Content:") print(content) # Reading line by
line with open(filename, "r") as f: print("\nLine by line:") for i, line in enumerate(f,
1): print(f"Line {i}: {line}", end="")

Output: Prints 'File created...' then displays all 3 lines.

Q22(U4). (11 Marks) ■ IMPORTANT


Question: Simulate a login system with try-except-finally; allow only 3 attempts.
Answer:
MAX_ATTEMPTS = 3 VALID_USER = "admin" VALID_PASS = "pass123" def login(): for attempt in
range(1, MAX_ATTEMPTS + 1): try: username = input(f"Attempt {attempt} - Username: ")
password = input("Password: ") if username == VALID_USER and password == VALID_PASS:
print("Login Successful! Welcome!") return True else: raise ValueError("Invalid username
or password!") except ValueError as e: print(f"Error: {e}") remaining = MAX_ATTEMPTS -
attempt if remaining > 0: print(f"{remaining} attempt(s) remaining.\n") finally:
print(f"[Attempt {attempt} complete]") print("Account locked! Max attempts reached.")
return False login()

Q23(U4). (11 Marks)


Question: Write a program to copy contents from one file to another.
Answer:
def copy_file(source, destination): try: with open(source, "r") as src: content =
[Link]() with open(destination, "w") as dst: [Link](content) print(f"Copied
'{source}' -> '{destination}' successfully!") return True except FileNotFoundError:
print(f"Error: '{source}' not found!") except PermissionError: print("Permission denied!")
return False src_file = input("Enter source filename : ") dest_file = input("Enter
destination filename : ") copy_file(src_file, dest_file) # Also using shutil (simpler)
import shutil [Link]("[Link]", "[Link]")

Q24(U4). (11 Marks)


Question: Write a Python program that accepts command-line arguments and prints their sum.
Answer:
import sys def sum_arguments(): args = [Link][1:] # skip script name if not args:
print("Usage: python [Link] num1 num2 ...") return try: numbers = [float(a) for a in
args] total = sum(numbers) print(f"Arguments : {numbers}") print(f"Sum : {total}") except
ValueError: print("Error: All arguments must be numbers!") sum_arguments() # Run as:
python [Link] 10 20 30 # Output: Sum: 60.0
Q25(U4). (11 Marks) ■ IMPORTANT
Question: File operations: count lines/words, append new line, read+write mode with overwrite.
Answer:
filename = "[Link]" # Create initial file with open(filename, "w") as f: [Link]("Hello
world\nPython is easy\nFile handling\n") # 1. Count lines and words with open(filename,
"r") as f: lines = [Link]() words = sum(len([Link]()) for line in lines)
print(f"Lines: {len(lines)}, Words: {words}") # 2. Append a new line with open(filename,
"a") as f: [Link]("Analysis Complete\n") print("Appended 'Analysis Complete'") # 3.
Read+Write mode: display then overwrite first line with open(filename, "r+") as f: content
= [Link]() print("\nFull content:\n", content) [Link](0) first_line_len = len(lines[0])
[Link]("Modified Line".ljust(first_line_len - 1) + "\n") print("First line overwritten!")

Q26(U4). (11 Marks) ■ PYQ — Anna University


Question: Write a program to handle multiple exceptions (ZeroDivisionError and ValueError).
Answer:
def safe_divide(): try: a = float(input("Enter numerator : ")) b = float(input("Enter
denominator: ")) result = a / b except ZeroDivisionError: print("Error: Cannot divide by
zero!") except ValueError: print("Error: Invalid input — enter numbers only!") except
Exception as e: print(f"Unexpected error: {e}") else: print(f"Result: {result:.4f}")
finally: print("Operation complete.") safe_divide()

Sample outputs: div by 0 → ZeroDivisionError | 'abc' → ValueError | 10/2 → Result: 5.0

Q27(U4). (11 Marks) ■ PYQ — Anna University


Question: Write a Python program to demonstrate user-defined exceptions.
Answer:
# Define custom exceptions class InvalidAgeError(Exception): def __init__(self, age,
msg="Age must be between 0 and 150"): [Link] = age [Link] = msg
super().__init__(f"{msg}. Got: {age}") class NegativeAmountError(Exception): pass def
validate_age(age): if age < 0 or age > 150: raise InvalidAgeError(age) return f"Valid age:
{age}" def process_payment(amount): if amount < 0: raise NegativeAmountError(f"Amount
cannot be negative: {amount}") return f"Payment of Rs. {amount} processed" # Test for
test_age in [25, -5, 200]: try: print(validate_age(test_age)) except InvalidAgeError as e:
print(f"Custom Error: {e}") try: print(process_payment(-100)) except NegativeAmountError
as e: print(f"Payment Error: {e}")

Q29(U4). (11 Marks)


Question: Write a program using itertools to generate permutations of a list.
Answer:
from itertools import permutations, combinations, combinations_with_replacement lst =
list(input("Enter elements (space-separated): ").split()) r = int(input("Permutation
length r: ")) print(f"\nAll permutations of length {r}:") for p in permutations(lst, r):
print(p) print(f"\nAll combinations of length {r}:") for c in combinations(lst, r):
print(c) # Example: lst=['A','B','C'], r=2 # Permutations:
('A','B'),('A','C'),('B','A'),('B','C'),('C','A'),('C','B') # Combinations:
('A','B'),('A','C'),('B','C')
Q30(U4). (11 Marks)
Question: Write a Python program using [Link]() to find the product of a list.
Answer:
from functools import reduce import operator numbers = list(map(int, input("Enter numbers:
").split())) # Method 1 — reduce with lambda product = reduce(lambda x, y: x * y, numbers)
print(f"Product (lambda): {product}") # Method 2 — reduce with [Link] (faster)
product2 = reduce([Link], numbers, 1) print(f"Product ([Link]): {product2}") #
Also useful: sum using reduce total = reduce(lambda x, y: x + y, numbers) print(f"Sum:
{total}") # Sample: [2, 3, 4, 5] -> Product: 120

Sample (2 3 4 5): Product: 120 | Sum: 14

Q32(U4). (13 Marks) ■ IMPORTANT


Question: Accept student details, store in file, read and display formatted output using format
operators.
Answer:
def write_students(filename): n = int(input("Number of students: ")) with open(filename,
"w") as f: [Link](f"{'Name':<20} {'Roll':<10} {'Marks':<8} {'Grade'}\n") [Link]("-" * 50
+ "\n") for _ in range(n): name = input("Name : ") roll = input("Roll : ") marks =
int(input("Marks: ")) grade = "A" if marks>=80 else ("B" if marks>=60 else "C")
[Link](f"{name:<20} {roll:<10} {marks:<8} {grade}\n") print("Data saved!") def
read_students(filename): try: with open(filename, "r") as f: print("\n--- Student Report
---") print([Link]()) except FileNotFoundError: print("File not found!") fname =
"[Link]" write_students(fname) read_students(fname)

Q33(U4). (13 Marks)


Question: Program that handles file-not-found exception, takes filename from command-line, reads
and counts lines/words.
Answer:
import sys def analyze_file(filename): try: with open(filename, "r") as f: lines =
[Link]() words = sum(len([Link]()) for line in lines) print(f"File : {filename}")
print(f"Lines : {len(lines)}") print(f"Words : {words}") return len(lines), words except
FileNotFoundError: print(f"Error: File '{filename}' not found!") [Link](1) except
PermissionError: print(f"Error: Cannot read '{filename}' — permission denied!")
[Link](1) if len([Link]) < 2: print("Usage: python [Link] <filename>") [Link](1)
analyze_file([Link][1])

Q34(U4). (13 Marks) ■ IMPORTANT


Question: Accept marks, raise exception if marks < 0 or > 100, store valid marks in a file.
Answer:
class InvalidMarksError(Exception): pass def validate_marks(marks): if marks < 0: raise
InvalidMarksError(f"Marks cannot be negative! Got {marks}") if marks > 100: raise
InvalidMarksError(f"Marks cannot exceed 100! Got {marks}") return marks def
store_marks(filename, marks): with open(filename, "a") as f: [Link](f"{marks}\n")
filename = "[Link]" n = int(input("How many students? ")) for i in range(n): try: m =
int(input(f"Enter marks for student {i+1}: ")) validate_marks(m) store_marks(filename, m)
print(f"Marks {m} saved successfully!") except InvalidMarksError as e: print(f"Error:
{e}") except ValueError: print("Please enter a valid integer!") print(f"\nAll valid marks
saved to '{filename}'")
Q35(U4). (13 Marks) ■ PYQ — Anna University
Question: Create a module with arithmetic functions, import into another file, organize into a
package.
Answer:
Step 1: Create package structure
# mypackage/ # ■■■ __init__.py # ■■■ [Link] # ■■■ [Link]

[Link]
# mypackage/[Link] def add(a, b): return a + b def subtract(a, b): return a - b def
multiply(a, b): return a * b def divide(a, b): if b == 0: raise ZeroDivisionError("b
cannot be zero") return a / b def power(a, b): return a ** b

__init__.py
# mypackage/__init__.py from .arithmetic import add, subtract, multiply, divide, power

[Link] — Importing and using the module


# [Link] from mypackage import add, subtract, multiply, divide from [Link]
import power print(add(10, 5)) # 15 print(subtract(10, 5)) # 5 print(multiply(4, 3)) # 12
print(divide(20, 4)) # 5.0 print(power(2, 8)) # 256

Q36(U4). (13 Marks)


Question: Write a Python program using itertools to generate all combinations of given elements.
Answer:
from itertools import combinations, combinations_with_replacement, permutations elements =
list(input("Enter elements (space-separated): ").split()) print("\n=== All Combinations
===") for r in range(1, len(elements) + 1): print(f"\nC({len(elements)},{r}):") for c in
combinations(elements, r): print(" ", c) print("\n=== Combinations with Replacement ===")
r = int(input("Enter r: ")) for c in combinations_with_replacement(elements, r): print("
", c) print("\n=== All Permutations ===") for p in permutations(elements): print(" ", p)

Q37(U4). (13 Marks) ■ IMPORTANT


Question: Use reduce() to compute factorial and lru_cache to optimize repeated calculations.
Answer:
from functools import reduce, lru_cache # Factorial using reduce def factorial_reduce(n):
if n == 0: return 1 return reduce(lambda x, y: x * y, range(1, n + 1)) print(f"5! =
{factorial_reduce(5)}") # 120 print(f"0! = {factorial_reduce(0)}") # 1 # Fibonacci with
lru_cache for memoization @lru_cache(maxsize=None) def fibonacci(n): if n <= 1: return n
return fibonacci(n - 1) + fibonacci(n - 2) print("\nFibonacci with lru_cache:") for i in
range(10): print(f" fib({i}) = {fibonacci(i)}") print("\nCache info:",
fibonacci.cache_info())

Why lru_cache? It stores previously computed results (memoization), so fibonacci(30) won't recompute fib(5)
multiple times. Dramatic speedup for recursive algorithms.
Q38(U4). (13 Marks) ■ PYQ — Anna University
Question: Program: user input, division, multiple exceptions, else and finally blocks.
Answer:
def safe_division(): try: a = float(input("Enter numerator : ")) b = float(input("Enter
denominator : ")) result = a / b except ZeroDivisionError: print("Math Error: Division by
zero is undefined!") except ValueError: print("Input Error: Please enter valid numbers!")
except OverflowError: print("Overflow Error: Number is too large!") except Exception as e:
print(f"Unexpected Error: {type(e).__name__}: {e}") else: # Runs ONLY if no exception
occurred print(f"Result: {a} / {b} = {result:.4f}") print("Division performed
successfully!") finally: # ALWAYS runs print("Program execution complete.")
safe_division()

Block summary: try → attempt risky code | except → handle specific errors | else → success path | finally →
always executes (cleanup)
UNIT 5 — NumPy, Pandas, Matplotlib & Dask

Q16(U5). (11 Marks) ■ IMPORTANT


Question: Write a program to create a NumPy array and print elements greater than 50.
Answer:
import numpy as np arr = [Link]([10, 55, 30, 80, 45, 70, 20, 90, 35, 60])
print("Original Array:", arr) # Boolean indexing — elements > 50 mask = arr > 50 filtered
= arr[mask] print("Elements greater than 50:", filtered) # Using where indices =
[Link](arr > 50) print("Indices of elements > 50:", indices[0]) print("Values at those
indices :", arr[indices])

Output: Elements greater than 50: [55 80 70 90 60]

Q17(U5). (11 Marks) ■ IMPORTANT


Question: Explain style properties in Matplotlib (color, marker, linestyle) and demonstrate in a line
graph.
Answer:
Style Properties in Matplotlib:
• color: 'red', '#FF0000', 'r', (0.1, 0.2, 0.5) | • marker: 'o'(circle), 's'(square), '^'(triangle), 'D'(diamond) | •
linestyle: '-'(solid), '--'(dashed), '-.'(dash-dot), ':'(dotted)
import [Link] as plt import numpy as np x = [Link](0, 10, 50)
[Link](figsize=(10, 6)) [Link](x, [Link](x), color='red', marker='o', linestyle='-',
linewidth=2, markersize=4, label='sin(x)') [Link](x, [Link](x), color='blue',
marker='s', linestyle='--', linewidth=2, markersize=4, label='cos(x)') [Link](x,
[Link](x), color='green', marker='^', linestyle='-.', linewidth=1, markersize=3,
label='tan(x)') [Link]('Trigonometric Functions — Style Demo', fontsize=14)
[Link]('X axis') [Link]('Y axis') [Link]() [Link](-2, 2) [Link](True,
linestyle=':', alpha=0.7) plt.tight_layout() [Link]('styles_demo.png') [Link]()

Q18(U5). (11 Marks)


Question: Create NumPy array [45,10,30,25,50,15], slice index 1-4, sort ascending.
Answer:
import numpy as np arr = [Link]([45, 10, 30, 25, 50, 15]) print("Original array :", arr)
# Slice index 1 to 4 (exclusive of 4) sliced = arr[1:4] print("Sliced (index 1-4) :",
sliced) # Sort ascending sorted_arr = [Link](sliced) print("Sorted (ascending) :",
sorted_arr) # Also sort the full array print("Full array sorted :", [Link](arr))

Output: Original: [45 10 30 25 50 15] | Sliced: [10 30 25] | Sorted: [10 25 30]

Q19(U5). (11 Marks) ■ IMPORTANT


Question: Create Pandas DataFrame with student data, display first 3 rows, filter marks > 75.
Answer:
import pandas as pd data = { 'Name' : ['Alice', 'Bob', 'Carol', 'Dave', 'Eve', 'Frank'],
'Age' : [20, 21, 19, 22, 20, 21], 'Marks' : [85, 72, 91, 68, 79, 55], 'Grade' : ['A', 'B',
'A', 'C', 'B', 'C'], } df = [Link](data) print("=== First 3 Rows ===")
print([Link](3)) print("\n=== Students with Marks > 75 ===") high_scorers =
df[df['Marks'] > 75] print(high_scorers) print(f"\nTotal students : {len(df)}")
print(f"Students with marks>75: {len(high_scorers)}")

Output: head(3) shows Alice, Bob, Carol | Filter gives Alice(85), Carol(91), Eve(79)
Q20(U5). (11 Marks) ■ IMPORTANT
Question: Plot two lines on same graph for x=[1,2,3], y1=[10,20,30], y2=[30,20,10]. Add legend and
title.
Answer:
import [Link] as plt x = [1, 2, 3] y1 = [10, 20, 30] y2 = [30, 20, 10]
[Link](figsize=(8, 5)) [Link](x, y1, color='blue', marker='o', linestyle='-',
linewidth=2, markersize=8, label='Line 1 (y1)') [Link](x, y2, color='red', marker='s',
linestyle='--', linewidth=2, markersize=8, label='Line 2 (y2)') [Link]('Two-Line
Graph', fontsize=14) [Link]('X axis', fontsize=12) [Link]('Y axis', fontsize=12)
[Link](fontsize=11) [Link](True, alpha=0.4) [Link](x) plt.tight_layout()
[Link]('two_lines.png') [Link]()

Q21(U5). (11 Marks) ■ IMPORTANT


Question: Scatter plot: Study Hours vs Exam Score. Analyze relationship.
Answer:
import [Link] as plt import numpy as np study_hours = [1, 2, 3, 4, 5, 6] scores
= [40, 50, 65, 70, 80, 85] [Link](figsize=(8, 5)) [Link](study_hours, scores,
color='blue', s=100, edgecolors='black', linewidth=1, zorder=5, label='Students') # Trend
line m, b = [Link](study_hours, scores, 1) x_line = [Link](0.5, 6.5, 100)
[Link](x_line, m * x_line + b, 'r--', linewidth=1.5, label=f'Trend: y={m:.1f}x+{b:.1f}')
[Link]('Study Hours vs Exam Score', fontsize=14) [Link]('Study Hours', fontsize=12)
[Link]('Exam Score', fontsize=12) [Link]() [Link](True, alpha=0.4)
plt.tight_layout() [Link]('[Link]') [Link]() print(f"Correlation:
{[Link](study_hours, scores)[0,1]:.4f}")

Analysis: Strong positive correlation (~0.99). As study hours increase, exam scores increase almost linearly.

Q22(U5). (11 Marks) ■ IMPORTANT


Question: Explain statistical functions in Pandas. Program to calculate mean, median, and
maximum.
Answer:
Key Pandas Statistical Functions: [Link]() — arithmetic average | [Link]() — middle value | [Link]() /
[Link]() | [Link]() — standard deviation | [Link]() — full summary stats
import pandas as pd data = { 'Student': ['A','B','C','D','E','F'], 'Maths' : [85, 92, 78,
65, 88, 73], 'Science': [79, 88, 84, 70, 91, 68], 'English': [90, 75, 82, 88, 77, 85], } df
= [Link](data).set_index('Student') print("=== Statistical Summary ===")
print(f"Mean :\n{[Link]().round(2)}") print(f"\nMedian :\n{[Link]()}")
print(f"\nMaximum:\n{[Link]()}") print(f"\nMinimum:\n{[Link]()}") print(f"\nStd
Dev:\n{[Link]().round(2)}") print(f"\n--- Full describe() ---\n{[Link]().round(2)}")
Q23(U5). (13 Marks) ■ IMPORTANT
Question: Develop a weather data visualization program using Pandas & Matplotlib.
Answer:
import pandas as pd import [Link] as plt import numpy as np # Sample weather
dataset data = { 'Month' : ['Jan','Feb','Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov','Dec'], 'Temperature' : [18, 21, 26, 31, 35, 37, 34, 33, 30,
26, 22, 18], 'Rainfall_mm' : [10, 5, 12, 30, 60, 90,150,140, 80, 40, 15, 8],
'Humidity_pct': [60, 58, 55, 62, 65, 72, 80, 82, 75, 68, 63, 60], } df =
[Link](data) print("=== Weather Statistics ===") print([Link]().round(2)) fig,
axes = [Link](3, 1, figsize=(10, 10)) # 1. Temperature line
axes[0].plot(df['Month'], df['Temperature'], 'ro-', linewidth=2, markersize=7)
axes[0].fill_between(df['Month'], df['Temperature'], alpha=0.2, color='red')
axes[0].set_title('Monthly Temperature (°C)'); axes[0].set_ylabel('°C') axes[0].grid(True,
alpha=0.4) # 2. Rainfall bar axes[1].bar(df['Month'], df['Rainfall_mm'],
color='steelblue', edgecolor='black') axes[1].set_title('Monthly Rainfall (mm)');
axes[1].set_ylabel('mm') axes[1].grid(True, axis='y', alpha=0.4) # 3. Humidity
axes[2].plot(df['Month'], df['Humidity_pct'], 'g^--', linewidth=2)
axes[2].set_title('Monthly Humidity (%)'); axes[2].set_ylabel('%') axes[2].set_ylim(50,
90); axes[2].grid(True, alpha=0.4) plt.tight_layout() [Link]('[Link]', dpi=150)
[Link]()

Q24(U5). (13 Marks) ■ PYQ — Anna University


Question: Analyze Matplotlib plot types (line, scatter, multi-line) and explain when to use each.
Answer:
1. Line Plot — Use for: continuous data, time series, trends over time.
import [Link] as plt # Line plot months = range(1, 13) sales =
[120,135,128,160,175,190,185,200,195,210,220,240] [Link](months, sales, 'b-o',
linewidth=2) [Link]('Monthly Sales — Line Plot') [Link]('Month'); [Link]('Sales
(units)') [Link](True); [Link]()

2. Scatter Plot — Use for: showing relationship/correlation between two variables.


# Scatter plot import numpy as np x = [Link](50) * 10 y = 3 * x +
[Link](50) * 5 [Link](x, y, c='red', alpha=0.6, edgecolors='k')
[Link]('Scatter Plot — Correlation') [Link]('X'); [Link]('Y'); [Link]()

3. Multi-line Plot — Use for: comparing multiple datasets on same axes.


# Multi-line x = [1, 2, 3, 4, 5] [Link](x, [10,20,15,25,30], 'b-o', label='Product A')
[Link](x, [5,15,10,20,18], 'r-s', label='Product B') [Link](x, [8,12,18,22,28], 'g-^',
label='Product C') [Link]('Multi-line — Product Comparison') [Link]();
[Link](True); [Link]()
Q25(U5). (13 Marks) ■ PYQ — Anna University
Question: Given DataFrame with missing values (NaN), clean data, display, and evaluate
importance of cleaning.
Answer:
import pandas as pd import numpy as np data = { 'Name' : ['A', 'B', 'C', 'D'], 'Age' : [20,
[Link], 22, 21], 'Marks': [85, 90, [Link], 75], } df = [Link](data) print("===
Before Cleaning ===") print(df) print("\nMissing values:\n", [Link]().sum()) # Cleaning
options: # 1. Drop rows with any NaN df_dropped = [Link]() # 2. Fill NaN with mean
(better approach) df_filled = [Link]() df_filled['Age'] =
df_filled['Age'].fillna(df_filled['Age'].mean()) df_filled['Marks'] =
df_filled['Marks'].fillna(df_filled['Marks'].mean()) print("\n=== After Cleaning (fillna
with mean) ===") print(df_filled.round(2)) print("\nMissing values after cleaning:\n",
df_filled.isnull().sum())

Importance of Data Cleaning: Raw data often has missing, inconsistent, or erroneous entries. Cleaning
ensures (1) accurate analysis, (2) reliable ML models, (3) correct statistical results. Missing values can skew
means, break algorithms, and produce incorrect visualizations.

Q26(U5). (13 Marks) ■ PYQ — Anna University


Question: Discuss NumPy's vectorized operations and performance vs. traditional loops.
Answer:
Vectorized Operations: NumPy applies operations element-wise on entire arrays at once without explicit
Python loops, using optimized C/Fortran code internally.
import numpy as np import time n = 1_000_000 a = list(range(n)) b = list(range(n)) #
Traditional Python loop start = [Link]() result_loop = [a[i] + b[i] for i in range(n)]
loop_time = [Link]() - start print(f"Loop time : {loop_time:.4f}s") # NumPy vectorized
a_np = [Link](a) b_np = [Link](b) start = [Link]() result_np = a_np + b_np np_time
= [Link]() - start print(f"NumPy time : {np_time:.4f}s") print(f"Speedup : {loop_time /
np_time:.1f}x faster") # More vectorized operations arr = [Link]([1, 4, 9, 16, 25])
print([Link](arr)) # [1. 2. 3. 4. 5.] print(arr ** 2) # element-wise square
print([Link](arr)) # element-wise sin print(arr[arr > 8]) # boolean indexing — [9 16 25]

Performance advantage: NumPy is typically 10–100× faster than pure Python loops because it avoids Python
interpreter overhead and uses SIMD CPU instructions.

Q27(U5). (13 Marks) ■ IMPORTANT


Question: Sales data in Pandas: create Series, sort, find top product, detect duplicates, average.
Answer:
import pandas as pd data = {'Product': ['A','B','C','D','E'], 'Sales' : [200, 450, 300,
450, 150]} df = [Link](data) sales_series = [Link](data['Sales'],
index=data['Product'], name='Sales') print("=== Sales Series ===") print(sales_series)
print("\n=== Sorted (Ascending) ===") print(sales_series.sort_values()) print("\n===
Top-Selling Product ===") max_val = sales_series.max() top = sales_series[sales_series ==
max_val] print(top) print("\n=== Duplicate Sales Values ===") dups =
sales_series[sales_series.duplicated(keep=False)] print(dups) print(f"\n=== Average Sales
===") print(f"Rs. {sales_series.mean():.2f}")

Output: Top-seller: B and D (both 450) | Average: 310.00 | Duplicates: B=450, D=450
Q28(U5). (13 Marks) ■ IMPORTANT
Question: Mini Data Manipulation System: NumPy array, slice (index 2-5), sort, display all.
Answer:
import numpy as np raw_data = list(map(int, input("Enter integers (space-separated):
").split())) # i) Create NumPy array arr = [Link](raw_data) print("Original Array :",
arr) # ii) Extract slice (index 2 to 5, exclusive) sliced = arr[2:5] print("Sliced Array
:", sliced) # iii) Sort sliced in ascending order sorted_arr = [Link](sliced)
print("Sorted Array :", sorted_arr) print("\n=== Summary ===") print(f" Min :
{[Link]()}") print(f" Max : {[Link]()}") print(f" Mean: {[Link]():.2f}") print(f" Sum
: {[Link]()}")

Sample (1 5 3 9 2 8 7): Original: [1 5 3 9 2 8 7] | Sliced [2:5]: [3 9 2] | Sorted: [2 3 9]

You might also like