-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Closed
Labels
Needs: ResponseIssues which require feedback from leadIssues which require feedback from lead
Description
The current implementation of the _most_used method manually counts element occurrences using collections.defaultdict and then sorts the dictionary to find the most frequent element.
Current implementation:
openlibrary/openlibrary/core/lists/engine.py
Lines 92 to 97 in 606ba88
| def _most_used(self, seq): | |
| d = collections.defaultdict(lambda: 0) | |
| for x in seq: | |
| d[x] += 1 | |
| return sorted(d, key=lambda k: d[k], reverse=True)[0] |
While this works correctly, Python provides a built-in utility, collections.Counter, which is designed specifically for counting hashable objects. Using Counter would simplify the implementation and improve readability.
Proposed improvement:
from collections import Counter
def _most_used(self, seq):
return Counter(seq).most_common(1)[0][0]Benefits
- Simplifies the code
- Improves readability and maintainability
- Uses a standard library tool intended for counting
- Avoids manually maintaining a counting dictionary and sorting
Additionally, this avoids sorting the entire dictionary (O(k log k)) when only the most frequent element is needed.
If this change is acceptable, I would be happy to work on it and submit a pull request.
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
Needs: ResponseIssues which require feedback from leadIssues which require feedback from lead