We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 654d01d commit 599e1b2Copy full SHA for 599e1b2
1 file changed
optimize-python-code/examples.py
@@ -42,4 +42,13 @@ def find_common_elements_list(list1, list2):
42
list_time = time.time() - start_time
43
print(f"List approach time: {list_time:.4f} seconds")
44
45
-
+# after
46
+def find_common_elements_set(list1, list2):
47
+ set2 = set(list2) # Convert list to a set (one-time cost)
48
+ return [item for item in list1 if item in set2] # Check membership in set
49
+
50
+start_time = time.time()
51
+common_set = find_common_elements_set(large_list1, large_list2)
52
+set_time = time.time() - start_time
53
+print(f"Set approach time: {set_time:.4f} seconds")
54
+print(f"Improvement: {list_time / set_time:.2f}x faster")
0 commit comments