Python
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax and Data Types
-
Section 3: Collections
-
39: Set Operations: Union, Intersection, Difference
-
Section 4: Control Flow
-
Section 5: Functions
-
Section 6: Turtle Graphics and Early Practice Projects
-
Section 7: Working with Files and I/O
-
Section 8: Regular Expressions
-
Section 9: Object-Oriented Python
-
Section 10: Error Handling
-
Section 11: Modules and Packages
-
Section 12: Iterators, Generators, and Functional Tools
-
Section 13: Decorators and Metaprogramming
-
Section 14: Concurrency and Parallelism
-
Section 15: Working with Dates, Times, and Numbers
-
Section 16: Standard Library Deep Dive I: Data Structures
-
Section 17: Standard Library Deep Dive II: System and Introspection
-
Section 18: Standard Library Deep Dive III: Security and Encoding
-
Section 19: Standard Library Deep Dive IV: Text and Data Utilities
-
Section 20: Networking and Web Basics
-
Section 21: Working with Databases
-
Section 22: Testing and Quality
-
Section 23: Advanced Typing
-
Section 24: Context Managers and Resource Handling
-
Section 25: Text, Unicode, and Binary Data
-
Section 26: More Functional and Iteration Tools
-
Section 27: Data Validation and Configuration
-
Section 28: Working with Images and Media
-
Section 29: Property-Based and Documentation Testing
-
Section 30: Packaging and Deployment
-
Section 31: Performance and Internals
-
Section 32: Design Patterns in Python
-
Section 33: GUI Programming
-
Section 34: Security Basics
-
Section 35: Data Structures and Algorithms
-
Section 36: Practical Projects
-
Section 37: Capstone Projects
-
Section 38: Interview and Algorithm Practice
-
Section 39: Writing Idiomatic Python
446: Implementing Search Algorithms in Python
I've got a dataset of about 10,000 employee IDs—just integers—and I need to find if a specific ID exists in the system. When I first started coding this, I did what most of us do: I wrote the most obvious solution that came to mind. I didn't think about "algorithms"; I just thought about the goal.
Just looping through the pile
I started with a simple loop. I'll call it a "linear search," though at the time, I just called it "checking every item." Here is how that looked in my editor:
def find_employee(employee_list, target_id):
for emp_id in employee_list:
if emp_id == target_id:
return True
return False
# Let's test it with a small sample
ids = [102, 455, 321, 890, 112]
print(find_employee(ids, 890)) # True
It works. Perfectly. But as I scaled this up to the full 10,000-record list and started running it inside a loop for a batch report, I noticed a lag. It wasn't a crash, but it felt sluggish. If the ID I'm looking for is at the very end of the list—or not there at all—Python has to check every single element. In the worst case, that's 10,000 checks. Not a dealbreaker for 10k, but if this grows to 10 million? We're in trouble.
Cutting the deck in half
I remembered that if my data is sorted, I don't have to look at every item. I can treat the list like a physical dictionary. I don't start at page one to find "Python"; I open the book in the middle and decide if I need to go left or right.
Let's try to implement a binary search. I'll sort the IDs first, then keep splitting the search area in half. Here was my first attempt at the logic:
def binary_search_attempt(sorted_list, target):
low = 0
high = len(sorted_list) - 1
while low < high: # I'll come back to this condition
mid = (low + high) // 2
if sorted_list[mid] == target:
return mid
elif sorted_list[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
I ran a test case: `binary_search_attempt([10, 20, 30, 40], 40)`. I expected it to return index 3, but it actually returned -1. I stared at the code for a minute and realized my mistake: the while low < high condition. If the target is the very last element, low eventually becomes equal to high, and the loop exits before checking that final element. It's a classic off-by-one error.
Fixing the logic gap
I adjusted the condition to while low <= high. That tiny change ensures that even when the search window narrows down to a single element, we actually check that element before giving up.
def binary_search_fixed(sorted_list, target):
low = 0
high = len(sorted_list) - 1
while low <= high:
mid = (low + high) // 2
print(f"Checking index {mid}, value {sorted_list[mid]}") # Debugging trace
if sorted_list[mid] == target:
return mid
elif sorted_list[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
ids_sorted = [112, 102, 321, 455, 890] # Wait, this isn't sorted!
ids_sorted.sort()
print(f"Found at index: {binary_search_fixed(ids_sorted, 890)}")
Now, watch the debug trace. Instead of 5 iterations (linear), it finds the target in about 3. On a list of 10,000 items, linear search might take 10,000 steps; binary search will take, at most, about 14. That is a massive difference in efficiency.
When to use which
You might be wondering why we don't use binary search for everything. Well, look at that ids_sorted.sort() line. Sorting a list takes time—specifically, O(n log n) time. If you only need to search a list once, it's faster to just do a linear search. But if you sort the list once and then perform thousands of searches? Binary search is the only way to go. I usually weigh the "cost of sorting" against the "frequency of searching" before deciding which one to implement.
📋 Practical Task
Build a Product SKU Finder for E-commerce Inventory
You are managing a warehouse inventory system. You have a list of product SKUs (Stock Keeping Units) which are strings of alphanumeric characters. Because the inventory is huge, you need to implement an efficient lookup system.
Your Task:
- Create a list of at least 10 unsorted SKU strings (e.g.,
"SKU105", "SKU002", "SKU999", etc.). - Implement a function
find_sku_index(sku_list, target_sku)that uses a binary search algorithm to find the index of a target SKU. - Inside your main code block, you must first sort the list before passing it to your function.
- Test the function with one SKU that exists in the list and one that does not, printing the resulting index or a "Not Found" message.
There are no comments for now.