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

CS1010e notes and summary

The document covers essential Python programming concepts, including immutability of tuples, list manipulations, functional programming techniques, and common errors. It also discusses matrix operations, vector calculus, string manipulations, data structures, searching and sorting algorithms, graph algorithms, dynamic programming, efficient coding practices, and performance tips. Each section includes code examples and best practices for effective Python programming.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

CS1010e notes and summary

The document covers essential Python programming concepts, including immutability of tuples, list manipulations, functional programming techniques, and common errors. It also discusses matrix operations, vector calculus, string manipulations, data structures, searching and sorting algorithms, graph algorithms, dynamic programming, efficient coding practices, and performance tips. Each section includes code examples and best practices for effective Python programming.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

1.

Python Programming Basics

• Immutability of Tuples
o Tuples cannot be modified after they are created. Use a list or reconstruct a new tuple if
changes are needed.
• List Manipulations
o Use .append() to add items to a list.
o Use .insert(index, item) to insert an item at a specific index.
o List comprehensions offer a concise way to create lists: [expression for item in
iterable].

2. Functional Programming in Python

• map, filter, and reduce


o map(function, iterable) applies a function to every item of the iterable.
o filter(function, iterable) creates a list of elements for which a function returns true.
o reduce(function, iterable, initializer) reduces the iterable to a single value by
cumulatively applying the function.
• Examples:

python
Copy code
# Squaring numbers using map
numbers = [1, 2, 3]
squares = list(map(lambda x: x**2, numbers))

# Filtering even numbers using filter


evens = list(filter(lambda x: x % 2 == 0, numbers))

# Using reduce to sum elements


from functools import reduce
total = reduce(lambda x, y: x + y, numbers)

3. Common Errors and Misunderstandings

• List vs Tuple: Remember that lists are mutable (can be changed), while tuples are immutable.
• Indentation: Python uses indentation to define code blocks. Always align your code blocks properly
to avoid IndentationError.
• Boundary Conditions in Loops: Always check boundary conditions in loops to avoid IndexError.
• Type Errors in Operations: Be aware of the types when performing operations (e.g., cannot add a
list and an integer).

4. Matrix and Grid Operations

• Accessing Elements: Access elements using matrix[row][col].


• Modifying Elements: Directly modify elements if using lists, but for tuples within lists, replace the
tuple if modifications are needed.
• Rotating Matrices and Grid Traversal:
o Clockwise rotation involves moving the last row element to the first column, and so forth.

python
Copy code
def rotate_clockwise(matrix):
return list(zip(*matrix[::-1]))

5. Vector Calculus and Mathematical Operations


• Integration and Differentiation: These operations are fundamental in physics and engineering
contexts.
• Common Formulas: Remember key formulas like the dot product for vectors.

6. Cheats for Specific Problems

• Local Maximum in 2D List:

python
Copy code
def local_maximum(grid):
count = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
is_max = True
for di, dj in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
ni, nj = i + di, j + dj
if 0 <= ni < len(grid) and 0 <= nj < len(grid[0]):
if grid[ni][nj] > grid[i][j]:
is_max = False
break
if is_max:
count += 1
return count

8. String Manipulations

• Concatenation:
o Avoid using + repeatedly in loops; use .join() for efficiency when concatenating multiple
strings.
• Reversal:
o Use slicing: reversed_string = string[::-1].
• Substring Check:
o Use in: 'substr' in string.
• Formatting:
o Use f-strings for clearer syntax: f"Result: {result}".

9. Data Structures

• Dictionaries for Counting:

python
Copy code
from collections import Counter
counts = Counter(items) # Automatically counts the elements in the list 'items'

• Set Operations:
o Use sets for fast membership testing, union, intersection, and unique elements.
• Stacks and Queues:
o Use lists for stacks with append() and pop().
o Use collections.deque for queues which supports append() and popleft().

10. Searching and Sorting

• Binary Search:
o Use bisect module for maintaining sorted lists and binary searching.
• Sorting Complex Structures:
o Use sorted() with key: sorted(list, key=lambda x: x[1]).
11. Graph Algorithms

• Depth-First Search (DFS):

python
Copy code
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
for neighbor in graph[start]:
if neighbor not in visited:
dfs(graph, neighbor, visited)
return visited

• Breadth-First Search (BFS):

python
Copy code
from collections import deque
def bfs(graph, start):
visited, queue = set(), deque([start])
while queue:
vertex = queue.popleft()
for neighbor in graph[vertex]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
return visited

12. Dynamic Programming

• Memoization:

python
Copy code
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)

• Tabulation (Bottom-Up Approach):

python
Copy code
def fib_tab(n):
if n == 0:
return 0
elif n == 1:
return 1
fib_table = [0] * (n+1)
fib_table[1] = 1
for i in range(2, n+1):
fib_table[i] = fib_table[i-1] + fib_table[i-2]
return fib_table[n]

13. Efficient Code Practices

• Avoid Global Variables: Use function parameters and return values to manage state.
• Use Generators: For large data sets, use generators (yield) instead of returning lists to save
memory.
• Exception Handling: Use specific exceptions instead of general exceptions to make error handling
more accurate.

14. Performance Tips

• Use List Comprehensions: Often faster and more direct than equivalent operations using map and
filter.
• Use Native Functions and Libraries: Built-in Python functions and libraries are usually more
optimized than custom implementations.
• Profile Before Optimizing: Use profiling tools like cProfile to understand where the bottlenecks
are before optimizing.

You might also like