Skip to content

Commit 3c89b8a

Browse files
author
Harsh Raj Singhania
committed
sorts: type shell_sort for comparable items and add tests
1 parent dbf22d3 commit 3c89b8a

2 files changed

Lines changed: 18 additions & 1 deletion

File tree

sorts/shell_sort.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,15 @@
22
https://en.wikipedia.org/wiki/Shellsort#Pseudocode
33
"""
44

5+
from collections.abc import MutableSequence
6+
from typing import Any, Protocol
57

6-
def shell_sort(collection: list[int]) -> list[int]:
8+
9+
class Comparable(Protocol):
10+
def __lt__(self, other: Any, /) -> bool: ...
11+
12+
13+
def shell_sort[T: Comparable](collection: MutableSequence[T]) -> MutableSequence[T]:
714
"""Pure implementation of shell sort algorithm in Python
815
:param collection: Some mutable ordered collection with heterogeneous
916
comparable items inside
@@ -15,6 +22,15 @@ def shell_sort(collection: list[int]) -> list[int]:
1522
[]
1623
>>> shell_sort([-2, -5, -45])
1724
[-45, -5, -2]
25+
>>> shell_sort(["c", "a", "b"])
26+
['a', 'b', 'c']
27+
>>> shell_sort([2.5, -1, 0.0])
28+
[-1, 0.0, 2.5]
29+
>>> shell_sort(["c", "a", "b"]) == sorted(["c", "a", "b"])
30+
True
31+
>>> import pytest
32+
>>> with pytest.raises(TypeError):
33+
... shell_sort([1, "a"])
1834
"""
1935
# Marcin Ciura's gap sequence
2036

tests/test_sorts.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,7 @@ def test_sort_matches_builtin(sort, case):
121121
insertion_sort,
122122
merge_sort,
123123
selection_sort,
124+
shell_sort,
124125
],
125126
ids=lambda f: f.__name__,
126127
)

0 commit comments

Comments
 (0)