Python Tools for DSA
This is the Python toolkit that shows up again and again in DSA solutions.
Lists
nums = [10, 20, 30]
nums.append(40)
last = nums.pop()
print(nums)
print(last)
print(nums[0], nums[-1])
Dictionaries
counts = {}
for ch in "banana":
counts[ch] = counts.get(ch, 0) + 1
print(counts)
Sets
seen = set()
for x in [3, 1, 4, 1, 5]:
if x in seen:
print("duplicate:", x)
break
seen.add(x)
Tuples
Tuples are useful when you want an immutable pair like (row, col) or (distance, node).
point = (2, 5)
row, col = point
print(row, col)
Useful built-ins
nums = [7, 2, 9, 4]
print("sorted:", sorted(nums))
print("min:", min(nums))
print("max:", max(nums))
print("sum:", sum(nums))
Interview habit
Before writing a custom data structure in Python, ask:
- Can
listsolve this? - Do I need a
setfor membership? - Do I need a
dictfor lookup? - Is a tuple the cleanest key or state representation?