1- from typing import Any
1+ from collections .abc import Sequence
2+ from typing import Any , Protocol
23
34
4- def binary_search (lst : list [Any ], item : Any , start : int , end : int ) -> int :
5+ class Comparable (Protocol ):
6+ def __lt__ (self , other : Any , / ) -> bool : ...
7+
8+
9+ def binary_search [T : Comparable ](lst : list [T ], item : T , start : int , end : int ) -> int :
510 """>>> binary_search([1, 3, 5], 4, 0, 2)
611 2
712 >>> binary_search([1, 3, 5], 0, 0, 2)
@@ -30,20 +35,20 @@ def binary_search(lst: list[Any], item: Any, start: int, end: int) -> int:
3035 Space: ``O(log n)`` due to recursion depth.
3136 """
3237 if start == end :
33- return start if lst [start ] > item else start + 1
38+ return start if item < lst [start ] else start + 1
3439 if start > end :
3540 return start
3641
3742 mid = (start + end ) // 2
3843 if lst [mid ] < item :
3944 return binary_search (lst , item , mid + 1 , end )
40- elif lst [mid ] > item :
45+ elif item < lst [mid ]:
4146 return binary_search (lst , item , start , mid - 1 )
4247 else :
4348 return mid
4449
4550
46- def insertion_sort (lst : list [Any ]) -> list [Any ]:
51+ def insertion_sort [ T : Comparable ] (lst : list [T ]) -> list [T ]:
4752 """>>> insertion_sort([3, 2, 1])
4853 [1, 2, 3]
4954
@@ -74,7 +79,7 @@ def insertion_sort(lst: list[Any]) -> list[Any]:
7479 return lst
7580
7681
77- def merge (left : list [Any ], right : list [Any ]) -> list [Any ]:
82+ def merge [ T : Comparable ] (left : list [T ], right : list [T ]) -> list [T ]:
7883 """>>> merge([1, 4], [2, 3])
7984 [1, 2, 3, 4]
8085
@@ -104,7 +109,7 @@ def merge(left: list[Any], right: list[Any]) -> list[Any]:
104109 return [right [0 ], * merge (left , right [1 :])]
105110
106111
107- def tim_sort (lst : list [ Any ] | tuple [ Any , ...] | str ) -> list [Any ]:
112+ def tim_sort [ T : Comparable ] (lst : Sequence [ T ] ) -> list [T ]:
108113 """
109114 Sort and return the input using a TimSort-like approach: detect
110115 runs, sort each run with insertion sort, then merge the runs.
@@ -125,14 +130,18 @@ def tim_sort(lst: list[Any] | tuple[Any, ...] | str) -> list[Any]:
125130 True
126131 >>> tim_sort([3, 2, 1]) == sorted([3, 2, 1])
127132 True
133+ >>> tim_sort([1, "a"])
134+ Traceback (most recent call last):
135+ ...
136+ TypeError: '<' not supported between instances of 'str' and 'int'
128137
129138 """
130139 if not lst :
131140 return []
132141 length = len (lst )
133142 runs , sorted_runs = [], []
134143 new_run = [lst [0 ]]
135- sorted_array : list [Any ] = []
144+ sorted_array : list [T ] = []
136145 i = 1
137146 while i < length :
138147 if lst [i ] < lst [i - 1 ]:
0 commit comments