Skip to content

Commit f6dae59

Browse files
committed
sorts: make tree_sort accept any Comparable items
1 parent a4c1df1 commit f6dae59

1 file changed

Lines changed: 20 additions & 7 deletions

File tree

sorts/tree_sort.py

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,20 @@
77

88
from collections.abc import Iterable, Iterator
99
from dataclasses import dataclass
10+
from typing import Any, Protocol
11+
12+
13+
class Comparable(Protocol):
14+
def __lt__(self, other: Any, /) -> bool: ...
1015

1116

1217
@dataclass
13-
class Node:
14-
val: int
15-
left: Node | None = None
16-
right: Node | None = None
18+
class Node[T: Comparable]:
19+
val: T
20+
left: Node[T] | None = None
21+
right: Node[T] | None = None
1722

18-
def __iter__(self) -> Iterator[int]:
23+
def __iter__(self) -> Iterator[T]:
1924
if self.left:
2025
yield from self.left
2126
yield self.val
@@ -25,7 +30,7 @@ def __iter__(self) -> Iterator[int]:
2530
def __len__(self) -> int:
2631
return sum(1 for _ in self)
2732

28-
def insert(self, val: int) -> None:
33+
def insert(self, val: T) -> None:
2934
if val < self.val:
3035
if self.left is None:
3136
self.left = Node(val)
@@ -38,7 +43,7 @@ def insert(self, val: int) -> None:
3843
self.right.insert(val)
3944

4045

41-
def tree_sort(arr: Iterable[int]) -> tuple[int, ...]:
46+
def tree_sort[T: Comparable](arr: Iterable[T]) -> tuple[T, ...]:
4247
"""
4348
>>> tree_sort([])
4449
()
@@ -54,6 +59,14 @@ def tree_sort(arr: Iterable[int]) -> tuple[int, ...]:
5459
(-1, 1, 2, 4, 5, 6, 7, 37)
5560
>>> tree_sort(range(10, -10, -1)) == tuple(sorted(range(10, -10, -1)))
5661
True
62+
>>> tree_sort(["c", "a", "b"])
63+
('a', 'b', 'c')
64+
>>> tree_sort([2.5, -1, 0.0])
65+
(-1, 0.0, 2.5)
66+
>>> tree_sort([1, "a"])
67+
Traceback (most recent call last):
68+
...
69+
TypeError: '<' not supported between instances of 'str' and 'int'
5770
"""
5871
iterator = iter(arr)
5972
try:

0 commit comments

Comments
 (0)