From d961217d5ff106244ca424495d927412d7c96080 Mon Sep 17 00:00:00 2001 From: Fayupable <90789180+Fayupable@users.noreply.github.com> Date: Thu, 24 Sep 2026 17:08:14 +0300 Subject: [PATCH] sorts: type patience_sort's Stack for any comparable item (#15427) Part of #15234. --- sorts/patience_sort.py | 26 ++++++++++++++++++++++---- tests/test_sorts.py | 1 + 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/sorts/patience_sort.py b/sorts/patience_sort.py index 63c2c8ffe..56ee1b06d 100644 --- a/sorts/patience_sort.py +++ b/sorts/patience_sort.py @@ -3,6 +3,7 @@ from __future__ import annotations from bisect import bisect_left from functools import total_ordering from heapq import merge +from typing import Protocol """ A pure Python implementation of the patience sort algorithm @@ -19,16 +20,22 @@ python3 patience_sort.py """ +class Comparable(Protocol): + def __lt__(self, other: object, /) -> bool: ... + + @total_ordering -class Stack(list): - def __lt__(self, other): +class Stack[T: Comparable](list[T]): + def __lt__(self, other: Stack[T]) -> bool: return self[-1] < other[-1] - def __eq__(self, other): + def __eq__(self, other: object) -> bool: + if not isinstance(other, Stack): + return NotImplemented return self[-1] == other[-1] -def patience_sort(collection: list) -> list: +def patience_sort[T: Comparable](collection: list[T]) -> list[T]: """A pure implementation of patience sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous @@ -44,6 +51,17 @@ def patience_sort(collection: list) -> list: >>> patience_sort([-3, -17, -48]) [-48, -17, -3] + + >>> patience_sort(['d', 'a', 'b', 'e']) == sorted(['d', 'a', 'b', 'e']) + True + + >>> patience_sort([3.3, 1.1, 2.2]) + [1.1, 2.2, 3.3] + + >>> patience_sort([1, "a"]) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + TypeError: '<' not supported between instances of 'str' and 'int' """ stacks: list[Stack] = [] # sort into stacks diff --git a/tests/test_sorts.py b/tests/test_sorts.py index e0b77ac79..a4a8ed741 100644 --- a/tests/test_sorts.py +++ b/tests/test_sorts.py @@ -158,6 +158,7 @@ def test_rec_insertion_sort(case) -> None: odd_even_sort, odd_even_transposition, pancake_sort, + patience_sort, reversort, selection_sort, shrink_shell_sort,