Skip to content

Commit 1a5c6a1

Browse files
⚡️ Speed up function find_common_tags by 18,960%
Certainly! The program can be optimized by utilizing sets for intersection operations, which are generally faster than list comprehensions for this kind of task. Here’s the optimized version. ### Changes Made. 1. **Utilized Set for Intersection**: Instead of a list comprehension inside the loop, using set operations (`intersection_update`) significantly optimizes the performance for finding common elements. 2. **Retained the Original Functionality**: The function signature and return value remain unchanged. This will run faster, especially when dealing with a large number of articles or tags, as set operations are generally more efficient for membership tests and intersections.
1 parent 97f70aa commit 1a5c6a1

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

common_tags.py

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
from __future__ import annotations
2+
3+
4+
def find_common_tags(articles: list[dict[str, list[str]]]) -> set[str]:
5+
if not articles:
6+
return set()
7+
8+
# Using set intersection to find common tags
9+
common_tags = set(articles[0]["tags"])
10+
for article in articles[1:]:
11+
common_tags.intersection_update(article["tags"])
12+
13+
return common_tags

0 commit comments

Comments
 (0)