Skip to content

Commit def174d

Browse files
committed
feat: optimizing the prune function at the apriori_algorithm.py archive
1 parent 8d1fb26 commit def174d

File tree

1 file changed

+5
-3
lines changed

1 file changed

+5
-3
lines changed

machine_learning/apriori_algorithm.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
"""
1313

1414
from itertools import combinations
15-
15+
from collections import Counter
1616

1717
def load_data() -> list[list[str]]:
1818
"""
@@ -32,7 +32,7 @@ def prune(itemset: list, candidates: list, length: int) -> list:
3232
the frequent itemsets of the previous iteration (valid subsequences of the frequent
3333
itemsets from the previous iteration).
3434
35-
Prunes candidate itemsets that are not frequent.
35+
Prunes candidate itemsets that are not frequent using Counter for optimization.
3636
3737
>>> itemset = ['X', 'Y', 'Z']
3838
>>> candidates = [['X', 'Y'], ['X', 'Z'], ['Y', 'Z']]
@@ -44,11 +44,13 @@ def prune(itemset: list, candidates: list, length: int) -> list:
4444
>>> prune(itemset, candidates, 3)
4545
[]
4646
"""
47+
itemset_counter = Counter(itemset)
4748
pruned = []
49+
4850
for candidate in candidates:
4951
is_subsequence = True
5052
for item in candidate:
51-
if item not in itemset or itemset.count(item) < length - 1:
53+
if item not in itemset_counter or itemset_counter[item] < length - 1:
5254
is_subsequence = False
5355
break
5456
if is_subsequence:

0 commit comments

Comments
 (0)