1- from typing import Any
1+ from typing import Any , Protocol , TypeVar
22
33
4- def bubble_sort_iterative (collection : list [Any ]) -> list [Any ]:
4+ class Comparable (Protocol ):
5+ def __lt__ (self , other : Any , / ) -> bool : ...
6+
7+
8+ T = TypeVar ("T" , bound = Comparable )
9+
10+
11+ def bubble_sort_iterative [T : Comparable ](collection : list [T ]) -> list [T ]:
512 """Pure implementation of the bubble sort algorithm in Python (iterative).
613
714 Bubble sort works by repeatedly stepping through the collection,
@@ -58,6 +65,10 @@ def bubble_sort_iterative(collection: list[Any]) -> list[Any]:
5865 >>> collection_arg = random.choices(string.ascii_letters + string.digits, k=100)
5966 >>> bubble_sort_iterative(collection_arg) == sorted(collection_arg)
6067 True
68+ >>> bubble_sort_iterative([1, "a"]) # doctest: +IGNORE_EXCEPTION_DETAIL
69+ Traceback (most recent call last):
70+ ...
71+ TypeError: '<' not supported between instances of 'str' and 'int'
6172 """
6273 length = len (collection )
6374 for i in reversed (range (length )):
@@ -71,7 +82,7 @@ def bubble_sort_iterative(collection: list[Any]) -> list[Any]:
7182 return collection
7283
7384
74- def bubble_sort_recursive (collection : list [Any ]) -> list [Any ]:
85+ def bubble_sort_recursive [ T : Comparable ] (collection : list [T ]) -> list [T ]:
7586 """Pure implementation of the bubble sort algorithm in Python (recursive).
7687
7788 Functionally identical to the iterative version: each call makes a
@@ -124,6 +135,10 @@ def bubble_sort_recursive(collection: list[Any]) -> list[Any]:
124135 >>> collection_arg = random.choices(string.ascii_letters + string.digits, k=100)
125136 >>> bubble_sort_recursive(collection_arg) == sorted(collection_arg)
126137 True
138+ >>> bubble_sort_recursive([1, "a"]) # doctest: +IGNORE_EXCEPTION_DETAIL
139+ Traceback (most recent call last):
140+ ...
141+ TypeError: '<' not supported between instances of 'str' and 'int'
127142 """
128143 length = len (collection )
129144 swapped = False
0 commit comments