0% found this document useful (0 votes)
3 views16 pages

Python 2

The IITM BS Python OPPE 2 Exam Preparation Guide outlines essential topics and strategies for success in the exam, which includes functions, lambda functions, list comprehensions, matrix operations, recursion, and file handling. It emphasizes time management during the exam and provides practice questions for each topic to reinforce understanding. The guide also details file handling techniques, particularly with CSV files, which are crucial for the exam.
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)
3 views16 pages

Python 2

The IITM BS Python OPPE 2 Exam Preparation Guide outlines essential topics and strategies for success in the exam, which includes functions, lambda functions, list comprehensions, matrix operations, recursion, and file handling. It emphasizes time management during the exam and provides practice questions for each topic to reinforce understanding. The guide also details file handling techniques, particularly with CSV files, which are crucial for the exam.
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

i have my python oppe 2 exam and i want best tips

and tricks inn which we will be fadu prep i want all


topics explain and question
Now I have comprehensive information about IITM BS Python OPPE 2. Let me compile a
detailed, well-structured guide with all topics, tips, tricks, and questions.

🚀 Complete IITM BS Python OPPE 2 Exam


Preparation Guide
Your OPPE 2 exam is a critical test of your Python programming skills, covering topics from
Weeks 1-8 up to File Handling. This comprehensive guide will help you prepare "fadu" style
with all topics explained, practice questions, tips, and tricks based on your previous OPPE
preparation experience and current exam patterns. [1] [2] [3] [4]

📋 OPPE 2 Exam Structure & Strategy

Exam Format:
Duration: 2 hours (120 minutes)
Total Questions: 5 questions, solve any 4
Marks Distribution: 100 marks total
Time per Question: ~20-25 minutes each [5] [6] [4]
Section Breakdown:

Section Questions Marks Each Topics

Section 1 3 questions 10 marks Functions, Data Types (no loops)

Section 2 2 questions 20 marks Data Processing, Analysis

Section 3 2 questions 15 marks Data Analysis + File Handling

🎯 Golden Time Management Strategy


The most important trick for OPPE 2 success is smart time allocation: [6] [5]
1. First 3 minutes: Read and understand the question thoroughly
2. Next 5 minutes: If you get the logic, start coding; if not, skip immediately and move to next
question
3. 5 minutes: Write pseudocode on pen and paper, break problem into smaller parts
4. Remaining 12 minutes: Code the solution—you already know the logic, just type it
Pro Tip: Always keep pen and paper ready. Break complex problems into smaller parts and
write pseudocode before coding. [5]

📚 TOPIC 1: Functions & Lambda Functions

Core Concepts
Regular Functions:

def function_name(parameters):
# function body
return result

Lambda Functions (Anonymous Functions):


Lambda functions are single-expression functions defined without a name: [7] [8] [9]

# Syntax
lambda arguments: expression

# Examples
# 1. Simple addition
add = lambda x, y: x + y
print(add(5, 3)) # Output: 8

# 2. Check even/odd
check = lambda x: "Even" if x % 2 == 0 else "Odd"
print(check(4)) # Output: Even
print(check(7)) # Output: Odd

# 3. Multiple return values (tuple)


calc = lambda x, y: (x + y, x * y)
print(calc(3, 4)) # Output: (7, 12)

Lambda with Built-in Functions


Using map() - applies function to each element: [8] [7]

numbers = [1, 2, 3, 4]
doubled = list(map(lambda x: x * 2, numbers))
print(doubled) # Output: [2, 4, 6, 8]

Using filter() - filters elements based on condition: [7] [8]


numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # Output: [2, 4, 6]

Using sorted() with key parameter:

students = [("Ram", 80), ("Sita", 90), ("Gita", 75)]


# Sort by marks (second element)
sorted_students = sorted(students, key=lambda x: x[^1], reverse=True)
print(sorted_students) # [('Sita', 90), ('Ram', 80), ('Gita', 75)]

Practice Questions - Functions & Lambda


Q1: Write a function that takes a list and returns the sum of squares of even numbers:

def sum_even_squares(lst):
return sum(map(lambda x: x**2, filter(lambda x: x % 2 == 0, lst)))

# Test
print(sum_even_squares([1, 2, 3, 4, 5, 6])) # Output: 56 (4+16+36)

Q2: Write a lambda function to find maximum of three numbers:

max_three = lambda a, b, c: a if (a >= b and a >= c) else (b if b >= c else c)


print(max_three(10, 25, 15)) # Output: 25

📚 TOPIC 2: List Comprehensions & Dictionary Operations

List Comprehension Syntax

# Basic syntax
[expression for item in iterable if condition]

# Examples
# 1. Squares of numbers
squares = [x**2 for x in range(1, 6)]
# Output: [1, 4, 9, 16, 25]

# 2. Even numbers
evens = [x for x in range(1, 11) if x % 2 == 0]
# Output: [2, 4, 6, 8, 10]

# 3. Nested list comprehension (flatten 2D list)


matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
# Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Dictionary Operations & Comprehension

# Dictionary comprehension
squares_dict = {x: x**2 for x in range(1, 6)}
# Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# Filter dictionary
marks = {"Ram": 80, "Sita": 45, "Gita": 90, "Rita": 35}
passed = {k: v for k, v in [Link]() if v >= 50}
# Output: {'Ram': 80, 'Gita': 90}

# Important dictionary methods


d = {"a": 1, "b": 2, "c": 3}
print([Link]()) # dict_keys(['a', 'b', 'c'])
print([Link]()) # dict_values([1, 2, 3])
print([Link]()) # dict_items([('a', 1), ('b', 2), ('c', 3)])
print([Link]("x", 0)) # 0 (default if key not found)

Practice Questions
Q1: Create a dictionary from two lists:

names = ["Ram", "Sita", "Gita"]


marks = [80, 90, 75]
result = {name: mark for name, mark in zip(names, marks)}
# Output: {'Ram': 80, 'Sita': 90, 'Gita': 75}

Q2: Count character frequency in a string:

def char_frequency(s):
return {char: [Link](char) for char in set(s)}

print(char_frequency("hello"))
# Output: {'h': 1, 'e': 1, 'l': 2, 'o': 1}

📚 TOPIC 3: Matrix Operations (2D Lists)


Critical Tip: In matrix questions, always start with finding dimensions: [5]

m = len(matrix) # Number of rows


n = len(matrix[^0]) # Number of columns
Matrix Addition

def mat_sum(A, B, C):


# Check if dimensions match
if len(A) != len(B) or len(A) != len(C):
return -1
if len(A[^0]) != len(B[^0]) or len(A[^0]) != len(C[^0]):
return -1

rows = len(A)
cols = len(A[^0])
result = [[A[i][j] + B[i][j] + C[i][j] for j in range(cols)] for i in range(rows)]
return result

Matrix Multiplication

def matrix_multiply(A, B):


rows_A = len(A)
cols_A = len(A[^0])
cols_B = len(B[^0])

# Initialize result matrix with zeros


result = [[0 for _ in range(cols_B)] for _ in range(rows_A)]

for i in range(rows_A):
for j in range(cols_B):
for k in range(cols_A):
result[i][j] += A[i][k] * B[k][j]
return result

PYQ: Matrix Product of 5 Matrices [6]


Question: Write a function mat_product that accepts five square matrices A, B, C, D, E and
returns A×B×C×D×E.

def mat_product(A, B, C, D, E):


def multiply(X, Y):
n = len(X)
result = [[^0]*n for _ in range(n)]
for i in range(n):
for j in range(n):
for k in range(n):
result[i][j] += X[i][k] * Y[k][j]
return result

# Multiply in order: ((((A*B)*C)*D)*E)


temp = multiply(A, B)
temp = multiply(temp, C)
temp = multiply(temp, D)
result = multiply(temp, E)
return result
Add Column of 1s to Matrix

def add_ones(matrix):
result = []
for row in matrix:
new_row = [^1] + row # Add 1 at the beginning
[Link](new_row)
return result

# Test
m = [[1, 2], [3, 4], [5, 6]]
print(add_ones(m))
# Output: [[1, 1, 2], [1, 3, 4], [1, 5, 6]]

📚 TOPIC 4: Recursion

Key Rule for Recursion: Every recursive function must have: [5]
1. Base case - condition to stop recursion
2. Return statement
3. Recursive call - function calling itself
Pro Tip: If stuck on recursion, try solving with a for loop first within 10 minutes, then convert to
recursive approach—the logic is the same, just with recursive calls. [5]

Essential Recursion Examples


1. Factorial:

def factorial(n):
if n == 0 or n == 1: # Base case
return 1
return n * factorial(n - 1) # Recursive case

print(factorial(5)) # Output: 120

2. Fibonacci:

def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
return fibonacci(n-1) + fibonacci(n-2)

print(fibonacci(10)) # Output: 55

3. Sum of Digits:
def sum_digits(n):
if n == 0: # Base case
return 0
return (n % 10) + sum_digits(n // 10)

print(sum_digits(123)) # Output: 6
print(sum_digits(9876)) # Output: 30

4. GCD (Euclidean Algorithm):

def gcd(a, b):


if b == 0: # Base case
return a
return gcd(b, a % b)

print(gcd(12, 18)) # Output: 6


print(gcd(17, 31)) # Output: 1

5. Power Function:

def power(base, exp):


if exp == 0:
return 1
return base * power(base, exp - 1)

print(power(2, 5)) # Output: 32

6. Check if Prime (Recursive):

def is_prime(n, divisor=2):


if n <= 1:
return False
if divisor * divisor > n:
return True
if n % divisor == 0:
return False
return is_prime(n, divisor + 1)

print(is_prime(17)) # True
print(is_prime(18)) # False

7. Count Occurrences in String:

def count_char(s, char):


if len(s) == 0:
return 0
count = 1 if s[^0] == char else 0
return count + count_char(s[1:], char)
print(count_char("hello world", "l")) # Output: 3

PYQ: Generate All Combinations [6]

def combinations(lst):
if len(lst) == 0:
return [[]]

first = lst[^0]
rest = lst[1:]
rest_combos = combinations(rest)

with_first = []
for combo in rest_combos:
with_first.append([first] + combo)

return rest_combos + with_first

print(combinations([1, 2, 3]))
# Output: [[], [^3], [^2], [2, 3], [^1], [1, 3], [1, 2], [1, 2, 3]]

PYQ: Generate All Permutations of String [6]

def permutations(s):
if len(s) <= 1:
return [s]

result = []
for i, char in enumerate(s):
remaining = s[:i] + s[i+1:]
for perm in permutations(remaining):
[Link](char + perm)
return result

print(permutations("abc"))
# Output: ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']

📚 TOPIC 5: File Handling (Most Important for OPPE 2!)


File handling is the most critical topic for OPPE 2 as Section 3 specifically tests this. [4] [10] [11]

File Opening Modes


Mode Description

'r' Read only (default)

'w' Write (overwrites file)


Mode Description

'a' Append (adds to end)

'r+' Read and write

Basic File Operations


Reading a Text File:

# Method 1: Read entire file


with open('[Link]', 'r') as f:
content = [Link]()
print(content)

# Method 2: Read line by line


with open('[Link]', 'r') as f:
for line in f:
print([Link]()) # strip() removes newline

# Method 3: Read all lines into list


with open('[Link]', 'r') as f:
lines = [Link]()

Writing to a File:

# Write mode (creates new or overwrites)


with open('[Link]', 'w') as f:
[Link]("Hello World\n")
[Link]("Second line")

# Append mode (adds to existing)


with open('[Link]', 'a') as f:
[Link]("\nAppended line")

# Write multiple lines


lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open('[Link]', 'w') as f:
[Link](lines)

CSV File Handling (Super Important!)


Reading CSV File:

import csv

# Method 1: [Link] (returns list)


with open('[Link]', 'r') as f:
reader = [Link](f)
header = next(reader) # Skip header
for row in reader:
print(row) # Each row is a list
# Method 2: [Link] (returns dictionary)
with open('[Link]', 'r') as f:
reader = [Link](f)
for row in reader:
print(row['Name'], row['Marks']) # Access by column name

Writing CSV File:

import csv

# Write using [Link]


with open('[Link]', 'w', newline='') as f:
writer = [Link](f)
[Link](['Name', 'Age', 'City']) # Header
[Link](['Ram', 25, 'Delhi'])
[Link](['Sita', 22, 'Mumbai'])

# Write using [Link]


with open('[Link]', 'w', newline='') as f:
fieldnames = ['Name', 'Age', 'City']
writer = [Link](f, fieldnames=fieldnames)
[Link]()
[Link]({'Name': 'Ram', 'Age': 25, 'City': 'Delhi'})

Major PYQ: CSV to List of Dictionaries [12] [6]


Question: Read a CSV file and store as list of dictionaries where each dictionary represents a
row.

def file_to_list(filename):
result = []
with open(filename, 'r') as f:
lines = [Link]()

# First line is header


header = lines[^0].strip().split(',')

# Process each data row


for line in lines[1:]:
values = [Link]().split(',')
row_dict = {}
for i, col in enumerate(header):
# First column is Name (string), others are marks (int)
if i == 0:
row_dict[col] = values[i]
else:
row_dict[col] = int(values[i])
[Link](row_dict)

return result

# Alternative using csv module


import csv
def file_to_list_v2(filename):
result = []
with open(filename, 'r') as f:
reader = [Link](f)
for row in reader:
for key in row:
if key != 'Name':
row[key] = int(row[key])
[Link](dict(row))
return result

More CSV Practice Questions [6]


Q1: Calculate Average GPA by Branch:

def avg_gpa_by_branch(filename, branch):


total_gpa = 0
count = 0
with open(filename, 'r') as f:
reader = [Link](f)
for row in reader:
if row['Branch'] == branch:
total_gpa += float(row['GPA'])
count += 1
return total_gpa / count if count > 0 else 0

Q2: Find Student with Highest GPA in Branch:

def highest_gpa_in_branch(filename, branch):


max_gpa = -1
student_name = ""
with open(filename, 'r') as f:
reader = [Link](f)
for row in reader:
if row['Branch'] == branch:
if float(row['GPA']) > max_gpa:
max_gpa = float(row['GPA'])
student_name = row['Name']
return student_name

Q3: Sort Data by Multiple Criteria:

def sort_data(filename):
with open(filename, 'r') as f:
reader = [Link](f)
data = list(reader)

# Sort by branch (ascending), then GPA (descending)


sorted_data = sorted(data, key=lambda x: (x['Branch'], -float(x['GPA'])))
return sorted_data
Q4: Find Longest Word in Text File:

def find_longest_word(filename):
longest = ""
with open(filename, 'r') as f:
for line in f:
words = [Link]().split()
for word in words:
# Remove punctuation
clean_word = ''.join(c for c in word if [Link]())
if len(clean_word) > len(longest):
longest = clean_word
return longest

📚 TOPIC 6: Prime Numbers & Number Theory

Check if Number is Prime

def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True

PYQ: Primes at Prime Indices [6]


Question: Count primes located at prime indices in a list (0-indexed).

def primes_galore(L):
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True

count = 0
for i in range(len(L)):
if is_prime(i) and is_prime(L[i]):
count += 1
return count

# Test
print(primes_galore([0, 1, 2, 3, 4, 5, 6, 7]))
# Prime indices: 2, 3, 5, 7
# Values at those: 2, 3, 5, 7 (all prime)
# Output: 4

Generate Primes Up to N (Sieve)

def sieve_of_eratosthenes(n):
is_prime = [True] * (n + 1)
is_prime[^0] = is_prime[^1] = False

for i in range(2, int(n**0.5) + 1):


if is_prime[i]:
for j in range(i*i, n + 1, i):
is_prime[j] = False

return [i for i in range(n + 1) if is_prime[i]]

🎯 Quick Reference: Common Errors & Fixes

Error Cause Fix

IndexError Accessing index out of range Check list length before accessing

TypeError Wrong data type in operation Use int(), str(), float() conversions

KeyError Dictionary key doesn't exist Use .get() method or check with in

FileNotFoundError File doesn't exist Check filename/path

RecursionError Missing base case Always define base case first

Debugging Tip: If you forget how a built-in function works, use: [5]

help(function_name)

📝 Last-Minute Revision Checklist

✅ Functions & Lambda: map(), filter(), sorted() with lambda


✅ List Comprehension: Basic and nested
✅ Dictionary: Operations, comprehension, methods
✅ Matrix: Addition, multiplication, dimension finding
✅ Recursion: Base case, factorial, fibonacci, GCD, sum of digits
✅ File Handling: read(), readline(), readlines(), write(), CSV operations
✅ Prime Numbers: is_prime(), primes at prime indices
✅ String Methods: split(), join(), strip(), isalnum()
🏆 Exam Day Strategy

1. Read all 5 questions first (5 minutes)


2. Identify 4 easiest questions to attempt
3. Start with most confident question to build momentum
4. Use pen and paper for pseudocode and logic
5. Test with sample inputs before submitting
6. Don't spend more than 25 mins on any question
7. If stuck, skip and return later
You've got this! Focus on understanding concepts, practice the PYQs, and manage your time
wisely during the exam. All the best for your OPPE 2! 💪🔥

1. preferences.explanation_style
2. [Link]
3. [Link]
4. [Link]
5. [Link]
6. [Link]
7. [Link]
8. [Link]
9. [Link]
10. [Link]
11. [Link]
12. [Link]
13. [Link]
14. [Link]
15. [Link]
16. [Link]
17. [Link]
18. [Link]
19. [Link]
20. [Link]
21. [Link]
22. [Link]
23. [Link]
24. [Link]
25. [Link]
26. [Link]
27. [Link]
28. [Link]
29. [Link]
30. [Link]
31. [Link]
32. [Link] IP QB [Link]
33. [Link]
34. [Link]
35. [Link]
36. [Link]
37. [Link]
38. [Link]
ence/5161564
39. [Link]
40. [Link]
41. [Link]
621
42. [Link]
43. [Link] SOLVING AND PYTHON
PROGRAMMING-2086059864-GE8151 PSPP all units [Link]
44. [Link]
45. [Link]
46. [Link]
47. [Link]
48. [Link]
49. [Link]
50. [Link]
51. [Link]
52. [Link]
53. [Link]
54. [Link]
55. [Link]
56. [Link]
thon-using-recursion
57. [Link]
58. [Link]
59. [Link]
60. [Link]
61. [Link]
62. [Link]
63. [Link]
rices
64. [Link]
65. [Link]
66. [Link]
67. [Link]
68. [Link]
69. [Link]
70. [Link]
71. [Link]
72. [Link]
73. [Link]
74. [Link]

You might also like