openlibrary icon indicating copy to clipboard operation
openlibrary copied to clipboard

Improve _most_used method implementation by using collections.Counter

Open Adeelp1 opened this issue 8 months ago • 3 comments

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:

https://github.com/internetarchive/openlibrary/blob/606ba88a13f96de264d250de16b9b616f5908493/openlibrary/core/lists/engine.py#L92-L97

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.

Adeelp1 avatar Mar 15 '26 06:03 Adeelp1

Hey @Adeelp1 , I've implemented the collections.Counter refactor as suggested to improve performance and readability. I've also added a safety check for empty sequences.

Harshul23 avatar Mar 17 '26 15:03 Harshul23

Thanks for implementing this!

The use of Counter and the added check for empty sequences both make the function more robust and readable. Appreciate the update 👍

Adeelp1 avatar Mar 17 '26 16:03 Adeelp1

Hi @Harshul23, thanks for working on this and for the clean refactor 👍

While looking deeper into this, I noticed that _most_used is only used by reduce_seeds(), and reduce_seeds() itself appears to be unused (dead code). I’ve opened a separate issue to track that: Unused reduce_seeds in internetarchive/openlibrary #12112.

Given that this code path is not currently used anywhere, it might be better to remove the dead code instead of refactoring it.

Because of this, I’m planning to close this issue in favor of addressing the unused code. Feel free to share thoughts if you see any active usage I might have missed.

Thanks again for the contribution!

Adeelp1 avatar Mar 19 '26 16:03 Adeelp1