Skip to content

Commit 05a14d1

Browse files
fix: reject negative values in radix sort
1 parent 6c04620 commit 05a14d1

3 files changed

Lines changed: 61 additions & 1 deletion

File tree

.vscode/settings.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
{
22
"githubPullRequests.ignoredPullRequestBranches": [
33
"master"
4-
]
4+
],
5+
"python-envs.defaultEnvManager": "ms-python.python:system"
56
}

sorts/radix_sort.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,10 @@ def radix_sort(list_of_ints: list[int]) -> list[int]:
2222
>>> radix_sort([1,100,10,1000]) == sorted([1,100,10,1000])
2323
True
2424
"""
25+
26+
if any(i < 0 for i in list_of_ints):
27+
raise ValueError("radix_sort only supports non-negative integers")
28+
2529
placement = 1
2630
max_digit = max(list_of_ints)
2731
while placement <= max_digit:

sorts/test_radix_sort.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import pytest
2+
3+
from sorts.radix_sort import radix_sort
4+
5+
6+
def test_radix_sort_basic():
7+
assert radix_sort([0, 5, 3, 2, 2]) == [0, 2, 2, 3, 5]
8+
9+
10+
def test_radix_sort_already_sorted():
11+
values = [1, 2, 3, 4, 5]
12+
assert radix_sort(values) == [1, 2, 3, 4, 5]
13+
14+
15+
def test_radix_sort_reverse_sorted():
16+
values = [5, 4, 3, 2, 1]
17+
assert radix_sort(values) == [1, 2, 3, 4, 5]
18+
19+
20+
def test_radix_sort_duplicates():
21+
values = [4, 2, 4, 1, 2, 4]
22+
assert radix_sort(values) == [1, 2, 2, 4, 4, 4]
23+
24+
25+
def test_radix_sort_zero():
26+
assert radix_sort([0]) == [0]
27+
28+
29+
def test_radix_sort_multiple_zeros():
30+
assert radix_sort([0, 5, 0, 2, 3]) == [0, 0, 2, 3, 5]
31+
32+
33+
def test_radix_sort_different_digit_lengths():
34+
values = [1, 1000, 10, 100, 10000]
35+
assert radix_sort(values) == [1, 10, 100, 1000, 10000]
36+
37+
38+
def test_radix_sort_large_numbers():
39+
values = [999999, 123456, 1000000, 42]
40+
assert radix_sort(values) == [42, 123456, 999999, 1000000]
41+
42+
43+
def test_radix_sort_negative_number():
44+
with pytest.raises(ValueError):
45+
radix_sort([-1, 5, 3])
46+
47+
48+
def test_radix_sort_multiple_negative_numbers():
49+
with pytest.raises(ValueError):
50+
radix_sort([-10, -5, 0, 5])
51+
52+
53+
def test_radix_sort_matches_sorted():
54+
values = [170, 45, 75, 90, 802, 24, 2, 66]
55+
assert radix_sort(values) == sorted(values)

0 commit comments

Comments
 (0)