Last Minute Notes Python Programming
Python is the primary programming language for GATE DA, and last-minute revision should focus on syntax pitfalls, built-in functions, and the one-liners th...
Python Syntax and Built-In Functions: Quick Revision
Python is the primary programming language for GATE DA, and last-minute revision should focus on syntax pitfalls, built-in functions, and the one-liners that compress common operations into exam-worthy code. This section consolidates the highest-yield Python facts for rapid review the night before the exam.
Indentation defines code blocks in Python; a missing or extra space causes an IndentationError. Variable names are case-sensitive. Python uses dynamic typing, so the type of a variable is determined at runtime. The type() function returns an object's type. The isinstance() function checks type with support for inheritance.
Built-in functions worth memorizing: len() returns the length of a sequence; range(start, stop, step) generates integer sequences; enumerate(iterable) yields (index, value) pairs; zip(a, b) pairs elements from two iterables; map(f, iterable) applies f to each element; filter(f, iterable) keeps elements where f returns True; sorted() returns a new sorted list; sum(), min(), and max() operate on iterables. List comprehensions condense loops: [x**2 for x in range(10) if x % 2 == 0] produces the squares of even numbers from 0 to 8.
String operations: strings are immutable sequences. s.split(sep) splits on separator; sep.join(list) concatenates with separator; s.strip() removes whitespace; s.lower() and s.upper() change case; s.replace(old, new) substitutes substrings; s[start:stop:step] slices. f-strings allow inline expressions: f"{value:.2f}" formats a float to two decimal places.
Exception handling: use try/except/finally blocks. Catching specific exceptions is better practice than catching a bare Exception. The with statement manages resources using context managers; open(filename) as f is the standard pattern for file I/O.
Lambda functions create anonymous functions: square = lambda x: x**2. They are useful as arguments to map, filter, and sorted but should not replace named functions for complex logic. Decorators wrap functions to modify their behavior and are commonly tested in Python-theory questions.
NumPy, Pandas, and Python Libraries for Data Science
NumPy and Pandas are the two most important Python libraries for data science, and GATE DA questions increasingly test practical knowledge of these tools alongside algorithmic understanding. A focused last-minute review of their core operations yields disproportionate exam benefit.
NumPy arrays are homogeneous, n-dimensional arrays stored in contiguous memory, enabling vectorized operations that are dramatically faster than Python loops. Key operations: np.array() creates an array; np.zeros(), np.ones(), np.eye() create special arrays; np.reshape() changes array shape without copying data; np.dot() or the @ operator performs matrix multiplication; np.linalg.inv() inverts a matrix; np.linalg.eig() computes eigenvalues and eigenvectors; np.linalg.svd() performs SVD. Array indexing supports boolean masks: a[a > 0] returns all positive elements.
Broadcasting is NumPy's mechanism for performing element-wise operations on arrays of different shapes by automatically expanding dimensions. A scalar added to an array adds to every element. A 1D array of shape (3,) added to a 2D array of shape (4,3) adds the 1D array to each row. Understanding broadcasting rules prevents a category of subtle bugs.
Pandas DataFrames are 2D labeled data structures built on NumPy arrays. Key operations: pd.read_csv() loads data; df.head() previews rows; df.describe() gives summary statistics; df.dropna() removes missing values; df.fillna(value) imputes them; df.groupby(column).agg(func) performs split-apply-combine; df.merge() joins DataFrames; df.pivot_table() creates cross-tabulations. Selecting by label uses df.loc[]; selecting by position uses df.iloc[].
Matplotlib provides basic plotting. plt.plot() creates line plots; plt.scatter() creates scatter plots; plt.hist() creates histograms. Seaborn builds on Matplotlib with statistical plots. For GATE DA, knowing which plot type suits which data type (histogram for distribution, scatter for correlation, bar for categorical comparison) is sufficient.
Quick revision fact: in pandas, df[col].value_counts() returns frequency counts sorted by frequency, equivalent to a defaultdict(int) counter pattern in pure Python. Recognizing these equivalent patterns connects library knowledge to algorithmic understanding.
Python for Algorithms: Complexity, Recursion, and OOP Patterns
Time and space complexity analysis is the bridge between Python code and theoretical computer science. GATE DA tests your ability to analyze the complexity of given code snippets, choose the optimal algorithm for a given task, and reason about trade-offs.
Big-O notation describes the asymptotic upper bound on resource usage. Common complexities from best to worst: O(1) constant, O(log n) logarithmic, O(n) linear, O(n log n) linearithmic, O(n^2) quadratic, O(2^n) exponential. Nested loops typically produce O(n^2) or higher complexity. Halving the problem at each step produces O(log n). Binary search on a sorted array is O(log n) per query.
Recursion implements algorithms by having a function call itself on smaller subproblems. Every recursive solution requires a base case that terminates the recursion and a recursive case that reduces the problem size. The recursion depth in Python is limited by default to 1000; sys.setrecursionlimit() increases it. The call stack uses O(d) space where d is the maximum recursion depth. Iterative solutions avoid this overhead.
Memoization caches the results of expensive function calls to avoid redundant computation. In Python, the functools.lru_cache decorator applies memoization automatically. Dynamic programming (DP) is the iterative equivalent: results are stored in a table and built bottom-up. The Fibonacci sequence can be computed in O(n) time and O(1) space using DP versus O(2^n) time with naive recursion.
Object-oriented programming in Python uses classes to bundle data and behavior. A class is defined with the class keyword; __init__ is the constructor; self refers to the instance. Inheritance allows a subclass to extend a parent class. Encapsulation hides implementation details; polymorphism allows different classes to be used interchangeably through a common interface.
Last-minute tip: for any Python code complexity question in GATE, count the number of nested loops, check whether each loop iterates over n elements or a fraction of n, and apply the multiplication rule. A triple nested loop over n elements at each level is O(n^3). Do not let library function calls mask hidden complexity; list.sort() is O(n log n), not O(1).