diff --git a/sorts/bogo_sort.py b/sorts/bogo_sort.py index 70785140e..16eed3bc3 100644 --- a/sorts/bogo_sort.py +++ b/sorts/bogo_sort.py @@ -14,9 +14,14 @@ python bogo_sort.py """ import random +from typing import Protocol -def bogo_sort(collection: list) -> list: +class Comparable(Protocol): + def __lt__(self, other: object, /) -> bool: ... + + +def bogo_sort[T: Comparable](collection: list[T]) -> list[T]: """Pure implementation of the bogosort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside @@ -28,11 +33,19 @@ def bogo_sort(collection: list) -> list: [] >>> bogo_sort([-2, -5, -45]) [-45, -5, -2] + >>> bogo_sort(["c", "a", "b"]) + ['a', 'b', 'c'] + >>> bogo_sort([2.5, -1.0, 0.0]) + [-1.0, 0.0, 2.5] + >>> bogo_sort([1, "a"]) + Traceback (most recent call last): + ... + TypeError: '<' not supported between instances of 'str' and 'int' """ - def is_sorted(collection: list) -> bool: + def is_sorted[T: Comparable](collection: list[T]) -> bool: for i in range(len(collection) - 1): - if collection[i] > collection[i + 1]: + if collection[i + 1] < collection[i]: return False return True diff --git a/tests/test_sorts.py b/tests/test_sorts.py index e3e91838a..8dd7fc37d 100644 --- a/tests/test_sorts.py +++ b/tests/test_sorts.py @@ -23,6 +23,7 @@ from typing import NamedTuple import pytest from sorts.binary_insertion_sort import binary_insertion_sort +from sorts.bogo_sort import bogo_sort from sorts.bubble_sort import bubble_sort_iterative, bubble_sort_recursive from sorts.circle_sort import circle_sort from sorts.cocktail_shaker_sort import cocktail_shaker_sort @@ -154,3 +155,11 @@ def test_sort_rejects_non_comparable_items(sort) -> None: def test_rec_insertion_sort_rejects_non_comparable_items() -> None: with pytest.raises(TypeError): rec_insertion_sort([1, "a"], 2) + + +def test_bogo_sort_comparable_items() -> None: + assert bogo_sort(["c", "a", "b"]) == ["a", "b", "c"] + assert bogo_sort([2.5, -1.0, 0.0]) == [-1.0, 0.0, 2.5] + + with pytest.raises(TypeError): + bogo_sort([1, "a"])