0% found this document useful (0 votes)
5 views4 pages

Python 6-Week Course Assignment Guide

Uploaded by

ss7944844
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)
5 views4 pages

Python 6-Week Course Assignment Guide

Uploaded by

ss7944844
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 6-Week Assignment Pack (CSE 20 + CSE

30)
■ Week 1 — Python Basics & Data Types
Topics: Variables, expressions, statements, basic I/O, data types

MCQs:
1. What will type(3.0) return?
a) int b) float c) double d) str
2. print("5" * 3) → ?
a) 15 b) 555 c) error d) None
3. Invalid variable name?
a) _count b) count1 c) 1count d) count_

Debugging:
num = input("Enter number: ")
square = num * num
print("Square is: " + square)

Practice:
1. Area of circle
2. Celsius to Fahrenheit
3. Print name and age

■ Week 2 — Control Structures


Topics: if-elif-else, while, for

MCQs:
1. Output of if/elif chain example?
a) A b) B c) A then B d) C
2. Loop for unknown iterations?
a) for b) while c) do-while d) None

Debugging:
count = 5
while count > 0:
print(count)
count -= 1

Practice:
1. FizzBuzz
2. Guessing game

■ Week 3 — Functions, Strings, Data Structures


MCQs:
1. Correct function definition?
a) def myfunc {} b) function myfunc(): c) def myfunc(): d) myfunc def():
2. s[::-1] for "hello"?
a) hello b) olleh c) error d) h

Debugging:
def add(a, b):
return a + b
print(add(2))
Practice:
1. Count vowels
2. Student topper dictionary
3. Remove duplicates

■ Week 4 — File I/O, Error Handling, Intro to OOP


MCQs:
1. Mode to overwrite file?
a) r b) w c) a d) rw
2. Purpose of __init__?
a) destroy b) init attrs c) copy obj d) none

Debugging:
file = open("[Link]", "r")
data = [Link]()
print(data)
[Link]

Practice:
1. BankAccount class
2. Division by zero handling
3. Count words in file

■ Week 5 — Advanced Python: OOP, Iterators, Generators, Recursion


MCQs:
1. Generator yield example output?
a) 1 2 b) 2 1 c) error d) None
2. Recursion truth?
a) call twice b) base case c) faster than loops d) no args

Debugging:
class Animal: ... class Dog(Animal): def speak(): ...

Practice:
1. Even number generator
2. Factorial recursion
3. Employee with private attrs

■ Week 6 — Algorithms, Functional Programming, Mini-Projects


MCQs:
1. Graph shortest path module?
a) graph b) networkx c) math d) numpy
2. reduce(lambda x,y: x+y, [1,2,3])?
a) 6 b) [6] c) (6,) d) error

Debugging:
from functools import map
nums = [1,2,3] squares = map(lambda x: x*x nums)

Practice:
1. BFS
2. Coin change DP
3. To-Do CLI app
■ Additional DSA Practice Questions
Strings:
Reverse string, palindrome check, char freq, longest non-repeat substring, anagram check
Arrays/Lists:
Max/min without built-in, rotate list, second largest, remove value, sum pairs
Bit Manipulation:
Count set bits, power of 2 check, swap without var, unique number, reverse bits
Sets:
Manual union/intersection, find duplicates, disjoint check, diff, symmetric diff
Dictionaries:
Word freq, invert dict, merge sum values, max value key, group by first letter
Tuples:
Sort by second elem, unpack, most common, tuple->dict, merge tuples
Recursion:
Factorial, Fibonacci, Tower of Hanoi, reverse string, prime check
Matrix:
Spiral print, transpose, multiply, sum, search in sorted matrix
Functions:
Varargs sum, Armstrong, min & max, flatten list, memoization
OOP:
Student class, multiple inheritance, + overload, instance counter, abstract Shape class

■ Additional DSA Practice Questions with Code & Explanations

1■■ Strings
1. Reverse a string without slicing:
def reverse_string(s): result = "" for ch in s: result = ch + result return result
print(reverse_string("hello")) Explanation: Prepending each character reverses the string.

2. Check palindrome:
def is_palindrome(s): s = [Link](" ", "").lower() return s == s[::-1] Explanation: Remove spaces,
lowercase, compare to reversed.

2■■ Arrays / Lists


1. Find max without max():
def find_max(lst): m = lst[0] for num in lst: if num > m: m = num return m Explanation: Track the
largest element manually.

2. Rotate list right by k:


def rotate_list(lst, k): k %= len(lst) return lst[-k:] + lst[:-k] Explanation: Use slicing to split and
rearrange.

3■■ Bit Manipulation


1. Count set bits:
def count_bits(n): count = 0 while n: count += n & 1 n >>= 1 return count Explanation: Check last
bit with &1, shift right until 0.

4■■ Sets
1. Find duplicates:
def find_duplicates(lst): seen = set() dup = set() for x in lst: if x in seen: [Link](x) else: [Link](x)
return dup Explanation: Track seen elements, collect repeats.

5■■ Dictionaries
1. Word frequency:
def word_freq(text): freq = {} for word in [Link](): freq[word] = [Link](word, 0) + 1 return freq
Explanation: Use dict with get() to count occurrences.
6■■ Tuples
1. Sort list of tuples by second element:
data = [(1, 3), (2, 1), (4, 2)] print(sorted(data, key=lambda x: x[1])) Explanation: key=lambda sorts
by second tuple element.

7■■ Recursion
1. Factorial:
def factorial(n): if n <= 1: return 1 return n * factorial(n - 1) Explanation: Base case at 1, multiply
recursively.

8■■ Matrix
1. Transpose matrix:
def transpose(mat): return [[mat[j][i] for j in range(len(mat))] for i in range(len(mat[0]))] Explanation:
Swap rows and columns using list comprehension.

9■■ Functions
1. Variable arguments sum:
def sum_all(*args): return sum(args) Explanation: *args collects arguments into tuple, sum them.

■ OOP
1. Student class:
class Student: def __init__(self, name, age, marks): [Link] = name [Link] = age [Link] =
marks def grade(self): if [Link] >= 90: return "A" elif [Link] >= 75: return "B" return "C" s =
Student("John", 20, 88) print([Link]()) Explanation: Simple class with method to calculate grade
based on marks.

Common questions

Powered by AI

Functional programming enhances code modularity and readability in Python by promoting the use of pure functions—functions that produce consistent outputs solely based on their input parameters without side effects. This increases clarity and predictability in code execution. Key features associated with functional programming include first-class functions that can be assigned to variables and passed as arguments, higher-order functions that operate on other functions such as `map` and `filter`, and immutability, which prevents changes to data structures, thus improving stability and thread safety. Techniques like lambda expressions, partial application, and function composition further encourage concise and expressive code .

Data structures are fundamental to optimizing algorithmic efficiency as they organize data in a way that enables effective data manipulation and retrieval. Their appropriate selection directly impacts performance by minimizing time complexity for operations such as access, insertion, deletion, and search. Selecting the right data structure can lead to significant improvements in algorithm performance, enhancing scalability and speed. For instance, hash tables allow constant time complexity for search and insertion, making them preferable for applications requiring frequent lookups. Conversely, using the wrong data structure can result in inefficiencies, increased computational overhead, and suboptimal performance .

When implementing a recursive function, key considerations include ensuring a clear and reachable base case to prevent infinite recursion and stack overflow errors. Additionally, the recursive step must simplify the problem while moving towards the base case with each function call. Recursion is a powerful tool as it provides a natural and intuitive approach for problems that can be subdivided into similar smaller problems, such as the Tower of Hanoi or factorial calculations. However, recursion can be limiting due to potential high memory usage and slower execution compared to iterative solutions, especially in languages or scenarios where tail-call optimization is not supported .

The potential pitfalls of using global variables in a Python program include an increased risk of unintended side effects, as changes to the global variable can impact all parts of the program that access it, leading to difficult-to-trace bugs. They also reduce modularity and reusability of code, as functions that rely on global variables may not work independently. Additionally, global variables can increase complexity by intertwining data and logic across different parts of the program. To mitigate these issues, one can limit the use of global variables by passing them as parameters to functions, employing encapsulation within classes, or using local variables within the appropriate scope .

Error handling in programming aims to manage and respond to errors during program execution, ensuring that the application can gracefully recover or provide meaningful feedback rather than crashing unexpectedly. Best practices for robust error management include using try-except blocks to catch anticipated exceptions, employing finally to execute cleanup actions, and avoiding bare except clauses which can hide unexpected errors. Moreover, it's crucial to log errors for diagnostics and to catch and handle specific exception types to provide precise error responses. Using custom exceptions tailored for the application can also enhance error clarity .

File operations in Python are handled using built-in functions such as `open()`, `read()`, `write()`, and `close()`. Developers commonly use context managers with the `with` statement to ensure files are correctly closed after operations, even if exceptions occur. Common pitfalls include failing to manage file exceptions such as attempting to read or write without the necessary permissions, or forgetting to close the file, which can lead to resource leaks. To avoid these issues, developers should validate file paths and permissions before operations and utilize context managers for automatic and safe file handling .

The 'yield' statement in Python is used within a generator function to produce a value and pause the function's state, which can be resumed to continue from where it left off in subsequent calls. Traditional iteration methods, such as loops, generate all values immediately and store them in memory, which can be inefficient for large data sets. In contrast, 'yield' offers a memory-efficient solution by generating values on-the-fly, one at a time, and preserving the function's state in between yields. This lazy evaluation approach minimizes memory usage and allows generators to handle potentially infinite sequences or large datasets effectively .

In Python, using variables or expressions incorrectly can lead to type-related errors, such as trying to multiply a string with an integer directly after an input operation that captures data as a string. For instance, multiplying a string instead of converting it to an integer could result in concatenated strings rather than a mathematical product. Debugging can help resolve such issues by allowing the programmer to trace the flow of execution and identify the exact point and nature of the error, such as the need for type conversion before execution. For example, in the provided debugging snippet, the code `square = num * num` raises an error since `num` is captured as a string; it needs conversion using `int(num)` before performing the multiplication .

Iterators in Python are objects that implement the iterator protocol, which consists of the methods `__iter__()` and `__next__()`. They allow traversing through all the elements of a collection. Generators, a subset of iterators, are functions that use `yield` statements to produce a sequence of results lazily, each resumed state maintaining its context over successive calls. Practical scenarios favor iterators when full control and customization of iteration mechanisms are needed, such as creating complex, customized iteration logic. Generators are favored when handling large datasets, lazy sequences, or infinite series as they provide memory-efficient solutions by generating items on-the-fly .

The `__init__` method in Python serves as the constructor for a class. It is called automatically when an instance (or object) of the class is created. Its primary role is to initialize the instance's attributes with values passed as arguments when the object is instantiated. This method is distinct from other methods because it is specifically designed to prepare a new object's initial state, while other methods typically perform operations on existing instances without modifying their foundational initialization. The uniqueness of `__init__` lies in its compulsory execution during object creation, setting it apart from regular methods that are called explicitly .

You might also like