Skip to content

Commit c2e8346

Browse files
authored
sorts: type double_sort for any comparable items (#15345)
1 parent a381578 commit c2e8346

1 file changed

Lines changed: 15 additions & 3 deletions

File tree

‎sorts/double_sort.py‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,15 @@
1-
from typing import Any
1+
from typing import Protocol
22

33

4-
def double_sort(collection: list[Any]) -> list[Any]:
4+
class Comparable(Protocol):
5+
def __lt__(self, other: object, /) -> bool: ...
6+
7+
8+
def double_sort[T: Comparable](collection: list[T]) -> list[T]:
59
"""This sorting algorithm sorts an array using the principle of bubble sort,
610
but does it both from left to right and right to left.
711
Hence, it's called "Double sort"
8-
:param collection: mutable ordered sequence of elements
12+
:param collection: mutable ordered sequence of comparable elements
913
:return: the same collection in ascending order
1014
Examples:
1115
>>> double_sort([-1 ,-2 ,-3 ,-4 ,-5 ,-6 ,-7])
@@ -16,6 +20,14 @@ def double_sort(collection: list[Any]) -> list[Any]:
1620
[-6, -5, -4, -3, -2, -1]
1721
>>> double_sort([-3, 10, 16, -42, 29]) == sorted([-3, 10, 16, -42, 29])
1822
True
23+
>>> double_sort(["c", "a", "b"])
24+
['a', 'b', 'c']
25+
>>> double_sort([2.5, -1, 0.0])
26+
[-1, 0.0, 2.5]
27+
>>> double_sort([1, "a"])
28+
Traceback (most recent call last):
29+
...
30+
TypeError: '<' not supported between instances of 'str' and 'int'
1931
"""
2032
no_of_elements = len(collection)
2133
for _ in range(

0 commit comments

Comments
 (0)