Here are some ways to make this code faster:
- Use a dictionary instead of a list for orders. This allows O(1) lookup time instead of O(n) with a list.
orders = {
(1, "red"): {"name": "apple", "id": 1, "color": "red"},
(3, "orange"): {"name": "orange", "id": 3, "color": "orange"}
}
Then you can lookup orders by (id, color) key:
order = orders[(1, "red")]
-
Use a set for matched_products instead of checking membership with in. This is O(1) instead of O(n) with a list.
-
Add products to the matched_products set directly instead of first checking matches. This avoids the nested loop.
Revised code:
products = [
{"name": "apple", "id": 1, "color": "red"},
{"name": "banana", "id": 2, "color": "yellow"}
]
orders = {
(1, "red"): {"name": "apple", "id": 1, "color": "red"},
(3, "orange"): {"name": "orange", "id": 3, "color": "orange"}
}
matched_products = set()
for product in products:
order = orders.get((product["id"], product["color"]))
if order:
matched_products.add(product)
for product in products:
if product not in matched_products:
print("MISSING?", product)
This avoids the nested loop and O(n) lookups, making the code much faster. Let me know if you have any other questions!