From 576c09013225a21a68950aa8931448ee1b432ca1 Mon Sep 17 00:00:00 2001 From: deerred643-star <229418842+deerred643-star@users.noreply.github.com> Date: Sun, 13 Sep 2026 03:48:11 +0800 Subject: [PATCH 1/2] sorts: make exchange_sort generic for comparable items --- sorts/exchange_sort.py | 17 ++++++++++++++++- tests/test_sorts.py | 1 + 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/sorts/exchange_sort.py b/sorts/exchange_sort.py index 1ce78a9dc0cb..14fecdb6abcb 100644 --- a/sorts/exchange_sort.py +++ b/sorts/exchange_sort.py @@ -1,4 +1,11 @@ -def exchange_sort(numbers: list[int]) -> list[int]: +from typing import Any, Protocol + + +class Comparable(Protocol): + def __lt__(self, other: Any, /) -> bool: ... + + +def exchange_sort[T: Comparable](numbers: list[T]) -> list[T]: """ Uses exchange sort to sort a list of numbers. Source: https://en.wikipedia.org/wiki/Sorting_algorithm#Exchange_sort @@ -12,6 +19,14 @@ def exchange_sort(numbers: list[int]) -> list[int]: [-2, 0, 3, 5, 10] >>> exchange_sort([]) [] + >>> exchange_sort(["c", "a", "b"]) + ['a', 'b', 'c'] + >>> exchange_sort([2.5, -1.0, 0.0]) + [-1.0, 0.0, 2.5] + >>> exchange_sort([1, "a"]) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + TypeError: '<' not supported between instances of 'str' and 'int' """ numbers_length = len(numbers) for i in range(numbers_length): diff --git a/tests/test_sorts.py b/tests/test_sorts.py index adabc2c7d43a..a7bcd6e59003 100644 --- a/tests/test_sorts.py +++ b/tests/test_sorts.py @@ -117,6 +117,7 @@ def test_sort_matches_builtin(sort, case): circle_sort, cocktail_shaker_sort, comb_sort, + exchange_sort, gnome_sort, insertion_sort, merge_sort, From 97be4127b7884b76ae091ad9db47a37c9e0d30d1 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Sat, 12 Sep 2026 22:32:38 +0200 Subject: [PATCH 2/2] Ints and floats are comparable --- sorts/exchange_sort.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/sorts/exchange_sort.py b/sorts/exchange_sort.py index 14fecdb6abcb..49a84ca4dfce 100644 --- a/sorts/exchange_sort.py +++ b/sorts/exchange_sort.py @@ -21,9 +21,9 @@ def exchange_sort[T: Comparable](numbers: list[T]) -> list[T]: [] >>> exchange_sort(["c", "a", "b"]) ['a', 'b', 'c'] - >>> exchange_sort([2.5, -1.0, 0.0]) - [-1.0, 0.0, 2.5] - >>> exchange_sort([1, "a"]) # doctest: +IGNORE_EXCEPTION_DETAIL + >>> exchange_sort([2.5, -1, 0.0]) + [-1, 0.0, 2.5] + >>> exchange_sort([1, "a"]) Traceback (most recent call last): ... TypeError: '<' not supported between instances of 'str' and 'int'