Skip to content

Commit 612f518

Browse files
nikhil-mewarnikhil.mewar@valiancesolutions.comcclauss
authored
sorts: make strand sort work with comparable types (#15350)
* sorts: make strand sort work with comparable types * Add type parameter to strand_sort function * Add strand_sort to sorting tests --------- Co-authored-by: nikhil.mewar@valiancesolutions.com <nikhil.mewar@valiancesolutions.com> Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent 302dd93 commit 612f518

2 files changed

Lines changed: 18 additions & 1 deletion

File tree

‎sorts/strand_sort.py‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,19 @@
11
import operator
2+
from typing import Protocol, TypeVar
23

34

4-
def strand_sort(arr: list, reverse: bool = False, solution: list | None = None) -> list:
5+
class Comparable(Protocol):
6+
def __lt__(self, other: object, /) -> bool: ...
7+
8+
def __gt__(self, other: object, /) -> bool: ...
9+
10+
11+
T = TypeVar("T", bound=Comparable)
12+
13+
14+
def strand_sort[T](
15+
arr: list[T], reverse: bool = False, solution: list[T] | None = None
16+
) -> list[T]:
517
"""
618
Strand sort implementation
719
source: https://en.wikipedia.org/wiki/Strand_sort
@@ -16,6 +28,10 @@ def strand_sort(arr: list, reverse: bool = False, solution: list | None = None)
1628
1729
>>> strand_sort([4, 2, 5, 3, 0, 1], reverse=True)
1830
[5, 4, 3, 2, 1, 0]
31+
32+
>>> strand_sort(["banana", "apple", "cherry"])
33+
['apple', 'banana', 'cherry']
34+
1935
"""
2036
_operator = operator.lt if reverse else operator.gt
2137
solution = solution or []

‎tests/test_sorts.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,7 @@ def test_rec_insertion_sort(case) -> None:
142142
pancake_sort,
143143
selection_sort,
144144
shrink_shell_sort,
145+
strand_sort,
145146
],
146147
ids=lambda f: f.__name__,
147148
)

0 commit comments

Comments
 (0)