CS1010e notes and summary
CS1010e notes and summary
• 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].
python
Copy code
# Squaring numbers using map
numbers = [1, 2, 3]
squares = list(map(lambda x: x**2, numbers))
• 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).
python
Copy code
def rotate_clockwise(matrix):
return list(zip(*matrix[::-1]))
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
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().
• 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
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
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
• 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)
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]
• 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.
• 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.