Skip to content

Improve _most_used method implementation by using collections.Counter #12100

@Adeelp1

Description

@Adeelp1

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:

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs: ResponseIssues which require feedback from lead

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions