Skip to content

Commit e56bff4

Browse files
sorts: type gnome sort for comparable items
1 parent 927c7d3 commit e56bff4

2 files changed

Lines changed: 14 additions & 2 deletions

File tree

sorts/gnome_sort.py

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,14 @@
1212
python3 gnome_sort.py
1313
"""
1414

15+
from typing import Protocol
1516

16-
def gnome_sort(lst: list) -> list:
17+
18+
class Comparable(Protocol):
19+
def __lt__(self, other: object, /) -> bool: ...
20+
21+
22+
def gnome_sort[T: Comparable](lst: list[T]) -> list[T]:
1723
"""
1824
Pure implementation of the gnome sort algorithm in Python
1925
@@ -32,7 +38,12 @@ def gnome_sort(lst: list) -> list:
3238
3339
>>> "".join(gnome_sort(list(set("Gnomes are stupid!"))))
3440
' !Gadeimnoprstu'
35-
"""
41+
42+
>>> gnome_sort(["d", "a", "c", "b"])
43+
['a', 'b', 'c', 'd']
44+
>>> gnome_sort([2.5, -1.0, 0.0])
45+
[-1.0, 0.0, 2.5]
46+
"""
3647
if len(lst) <= 1:
3748
return lst
3849

tests/test_sorts.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,7 @@ def test_sort_matches_builtin(sort, case):
9696
bubble_sort_iterative,
9797
bubble_sort_recursive,
9898
insertion_sort,
99+
gnome_sort,
99100
],
100101
ids=lambda f: f.__name__,
101102
)

0 commit comments

Comments
 (0)