Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions sorts/reversort.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,14 @@
python reversort.py
"""

from typing import Any
from typing import Any, Protocol


def reversort(collection: list[Any]) -> list[Any]:
class Comparable(Protocol):
def __lt__(self, other: Any, /) -> bool: ...


def reversort[T: Comparable](collection: list[T]) -> list[T]:
"""
Sort a list using the Reversort algorithm.

Expand Down Expand Up @@ -78,6 +82,10 @@ def reversort(collection: list[Any]) -> list[Any]:
>>> collection_arg = random.choices(string.ascii_letters + string.digits, k=100)
>>> reversort(collection_arg) == sorted(collection_arg)
True
>>> reversort([1, "a"]) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
TypeError: '<' not supported between instances of 'str' and 'int'
"""
arr = collection[:] # Create a copy to avoid modifying the original
n = len(arr)
Expand All @@ -96,7 +104,7 @@ def reversort(collection: list[Any]) -> list[Any]:
return arr


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

Expand All @@ -119,6 +127,10 @@ def reversort_cost(collection: list[Any]) -> int:
0
>>> reversort_cost([])
0
>>> reversort_cost([1, "a"]) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
TypeError: '<' not supported between instances of 'str' and 'int'
"""
arr = collection[:] # Create a copy to avoid modifying the original
n = len(arr)
Expand Down
3 changes: 3 additions & 0 deletions tests/test_sorts.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
from sorts.patience_sort import patience_sort
from sorts.quick_sort import quick_sort
from sorts.recursive_insertion_sort import rec_insertion_sort
from sorts.reversort import reversort
from sorts.selection_sort import selection_sort
from sorts.shell_sort import shell_sort
from sorts.shrink_shell_sort import shell_sort as shrink_shell_sort
Expand Down Expand Up @@ -73,6 +74,7 @@ def test_heap_sort() -> None:
pancake_sort,
patience_sort,
quick_sort,
reversort,
selection_sort,
shell_sort,
shrink_shell_sort,
Expand Down Expand Up @@ -140,6 +142,7 @@ def test_rec_insertion_sort(case) -> None:
merge_sort,
odd_even_sort,
pancake_sort,
reversort,
selection_sort,
shrink_shell_sort,
strand_sort,
Expand Down
Loading