Skip to content

Commit ba91194

Browse files
sorts: make odd_even_transposition sort any comparable items
Add Comparable Protocol and TypeVar for generic type hints. Part of #15234
1 parent 35ccb2c commit ba91194

1 file changed

Lines changed: 21 additions & 9 deletions

File tree

‎sorts/odd_even_transposition_parallel.py‎

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,20 @@
1111
synchronization could be used.
1212
"""
1313

14+
from __future__ import annotations
15+
1416
import multiprocessing as mp
17+
from typing import Protocol
1518

1619
# lock used to ensure that two processes do not access a pipe at the same time
1720
# NOTE This breaks testing on build runner. May work better locally
1821
# process_lock = mp.Lock()
1922

23+
24+
class Comparable(Protocol):
25+
def __lt__(self, other: object, /) -> bool: ...
26+
27+
2028
"""
2129
The function run by the processes that sorts the list
2230
@@ -30,14 +38,14 @@
3038

3139

3240
def oe_process(
33-
position,
34-
value,
35-
l_send,
36-
r_send,
37-
lr_cv,
38-
rr_cv,
39-
result_pipe,
40-
multiprocessing_context,
41+
position: int,
42+
value: Comparable,
43+
l_send: tuple | None,
44+
r_send: tuple | None,
45+
lr_cv: tuple | None,
46+
rr_cv: tuple | None,
47+
result_pipe: tuple,
48+
multiprocessing_context: mp.context.BaseContext,
4149
) -> None:
4250
process_lock = multiprocessing_context.Lock()
4351

@@ -78,7 +86,7 @@ def oe_process(
7886
"""
7987

8088

81-
def odd_even_transposition(arr):
89+
def odd_even_transposition[T: Comparable](arr: list[T]) -> list[T]:
8290
"""
8391
>>> odd_even_transposition(list(range(10)[::-1])) == sorted(list(range(10)[::-1]))
8492
True
@@ -98,6 +106,10 @@ def odd_even_transposition(arr):
98106
>>> unsorted_list = [-442, -98, -554, 266, -491, 985, -53, -529, 82, -429]
99107
>>> odd_even_transposition(unsorted_list) == sorted(unsorted_list + [1])
100108
False
109+
>>> odd_even_transposition([1, "a"]) # doctest: +IGNORE_EXCEPTION_DETAIL
110+
Traceback (most recent call last):
111+
...
112+
TypeError: '<' not supported between instances of 'str' and 'int'
101113
"""
102114
# spawn method is considered safer than fork
103115
multiprocessing_context = mp.get_context("spawn")

0 commit comments

Comments
 (0)