Skip to content

Instantly share code, notes, and snippets.

@winstxnhdw
Last active September 1, 2023 03:41
Show Gist options
  • Save winstxnhdw/e2f9df3a6956000b44782e6a0c52d997 to your computer and use it in GitHub Desktop.
Save winstxnhdw/e2f9df3a6956000b44782e6a0c52d997 to your computer and use it in GitHub Desktop.
A generic typesafe in-place implementation of a sort3 algorithm in Python
from typing import Annotated, Callable, NamedTuple, Protocol, TypeVar
class MaxLength(NamedTuple):
"""
Summary
-------
a data structure for annotating the maximum length of a list
Attributes
----------
value (int) : the maximum length of a list
"""
value: int
class Comparable(Protocol):
"""
Summary
-------
a protocol for comparable types
"""
__lt__: Callable[..., bool]
__gt__: Callable[..., bool]
__le__: Callable[..., bool]
__ge__: Callable[..., bool]
__eq__: Callable[..., bool]
__ne__: Callable[..., bool]
T = TypeVar('T', bound=Comparable)
def sort3(array: Annotated[list[T], MaxLength(3)]) -> list[T]:
"""
Summary
-------
sorts an array of length 3 in-place
Parameters
----------
array (list[T]) : the array to be sorted
Returns
-------
array (list[T]) : the sorted array
"""
if array[1] < array[0]:
array[0], array[1] =\
array[1], array[0]
if array[2] < array[1]:
array[1], array[2] =\
array[2], array[1]
if array[1] < array[0]:
array[0], array[1] =\
array[1], array[0]
return array
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment