Python Tutorial
DSA Algorithms
An algorithm is a finite list of steps that transforms input into output. Searching and sorting are the two families in the next chapters.
Properties
Input, output, definiteness (each step is clear), finiteness (it stops), and effectiveness (steps are doable).
def find_max(nums):
best = nums[0]
for n in nums[1:]:
if n > best:
best = n
return best
print(find_max([3, 9, 2, 7]))What Comes Next
Linear and binary search, then bubble, selection, insertion, quick, counting, radix, and merge sort — each with its typical Big O.
# Search: linear O(n), binary O(log n) on sorted data
# Sort: insertion ~ O(n²), merge/quick typical O(n log n)📘 Real-World Deep Dive
Knowing <strong>DSA Algorithms (algorithms & data structures)</strong> well is what turns algorithms & data structures from a curiosity into a daily tool — you'll reach for it in nearly every real project.
Real-Life Scenario
An end-to-end usage of DSA Algorithms that you'd actually see in a data pipeline or analytics notebook.
Real-Life Example
import math, bisect, heapq
def two_sum(nums, target):
seen = {}
for i, n in enumerate(nums):
if target - n in seen:
return seen[target-n], i
seen[n] = i
return None
print(two_sum([2, 7, 11, 15], 9))
print("sqrt:", math.isqrt(17))
print("bisect:", bisect.bisect_left([1,3,5,7], 5))
print("heappop:", heapq.heappop([3,1,2]))Expected Output
(see source)Common mistakes
- Off-by-one errors in binary-search: the standard idiom is
while lo <= hiwithmid = (lo + hi) // 2. - Recursive algorithms blow the stack for n > ~10⁴; convert to iterative with an explicit stack.
- Comparison algorithms (
sorted(iterable)) are stable by default in Python — surprising for Java/C++ users. - Treating DSA Algorithms as a black box without reading the docs — the API has subtle defaults that bite when you scale.
🚀 Performance & Best Practices
- Use
bisect.bisect_left/bisect_rightinstead of writing your own binary search. - Convert a sorted search into a tuple-access pattern with
numpy.searchsortedfor huge arrays. - Use
heapqfor priority queues instead of maintaining a sorted list manually. - When working with algorithms & data structures, prefer vectorised / batched operations over Python loops.
🧪 Try It Yourself
- Reproduce the snippet on a representative slice of your own data.
- Profile the snippet with
cProfileortimeitand find the single biggest improvement. - Generalise the snippet into a small, reusable function you can drop into future projects.