Skip to content

Commit 71afc3f

Browse files
authored
sorts: type reversort for any comparable items
1 parent 0dffbb2 commit 71afc3f

1 file changed

Lines changed: 11 additions & 3 deletions

File tree

‎sorts/reversort.py‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,14 @@
1717
python reversort.py
1818
"""
1919

20-
from typing import Any
20+
from typing import Protocol
2121

2222

23-
def reversort(collection: list[Any]) -> list[Any]:
23+
class Comparable(Protocol):
24+
def __lt__(self, other: object, /) -> bool: ...
25+
26+
27+
def reversort[T: Comparable](collection: list[T]) -> list[T]:
2428
"""
2529
Sort a list using the Reversort algorithm.
2630
@@ -70,6 +74,10 @@ def reversort(collection: list[Any]) -> list[Any]:
7074
[1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7]
7175
>>> reversort([1, 3.3, 5, 7.7, 2, 4.4, 6])
7276
[1, 2, 3.3, 4.4, 5, 6, 7.7]
77+
>>> reversort([1, "a"])
78+
Traceback (most recent call last):
79+
...
80+
TypeError: '<' not supported between instances of 'str' and 'int'
7381
>>> import random
7482
>>> collection_arg = random.sample(range(-50, 50), 100)
7583
>>> reversort(collection_arg) == sorted(collection_arg)
@@ -96,7 +104,7 @@ def reversort(collection: list[Any]) -> list[Any]:
96104
return arr
97105

98106

99-
def reversort_cost(collection: list[Any]) -> int:
107+
def reversort_cost[T: Comparable](collection: list[T]) -> int:
100108
"""
101109
Calculate the cost of sorting using Reversort.
102110

0 commit comments

Comments
 (0)