feat(sorts): make reversort generic over comparable items - #15402
Conversation
Part of TheAlgorithms#15234 - Replace list[Any] with a Comparable-bounded TypeVar so reversort and reversort_cost sort any mutually comparable items, not just ints - Add TypeError doctests confirming mixed non-comparable input raises - Register reversort in the shared test battery covering str/float/ dataclass/NamedTuple cases and the non-comparable rejection path
ruff UP047 requires the sanctioned [T: Comparable] signature form used by the reference insertion_sort.py. Keep the module-level TypeVar as in the reference.
|
ON HOLD: Our focus is on merging or closing old pull requests before October 1st. |
|
@priya-sundaram-dev, please review. Are the type hints correct? |
priya-sundaram-dev
left a comment
There was a problem hiding this comment.
The type hints are correct, and the Comparable protocol with just __lt__ is exactly the right minimal bound for a sort — nicely done. Two small things:
-
Redundant
TypeVar. You've written the bound twice: once as the module-levelT = TypeVar("T", bound=Comparable)and once inline via PEP 695 (def reversort[T: Comparable](...)). The inline form shadows the module-level one, so theT = TypeVar(...)line is dead. Since this repo targets the latest CPython, I'd keep the PEP 695 syntax and drop both theTypeVarimport and the assignment — leavingfrom typing import Any, Protocol. -
Doctests look right.
+IGNORE_EXCEPTION_DETAILis the correct call here, since theTypeErrormessage can read'str' and 'int'or'int' and 'str'depending on which comparison trips first — ignoring the detail keeps it deterministic across runs.
With the redundant TypeVar removed this is good to go. mypy and ruff should both be happy after that.
|
The type hints look correct to me, and they match the reference
One tiny, optional nit — not blocking: with the PEP 695 |
Co-authored-by: Christian Clauss <cclauss@me.com>
Describe your change
Part of #15234
Make reversort (and its
reversort_costhelper) sort any mutually comparable items instead of onlylist[int]:list[Any]to the sharedComparableProtocolwith aTypeVarbound, as in the referenceinsertion_sort.pyTypeErrordoctest to both functions confirming mixed non-comparable input raises instead of silently mis-sortingreversortintests/test_sorts.pyso it is exercised against the shared battery (ints, floats, strings,Person/Dogdataclasses) and the non-comparable rejection pathChecklist