Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 22 additions & 4 deletions sorts/patience_sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
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
Expand All @@ -19,16 +20,22 @@
"""


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
Expand All @@ -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
Expand Down
1 change: 1 addition & 0 deletions tests/test_sorts.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@ def test_rec_insertion_sort(case) -> None:
odd_even_sort,
odd_even_transposition,
pancake_sort,
patience_sort,
reversort,
selection_sort,
shrink_shell_sort,
Expand Down
Loading