Skip to content

Commit c2318ab

Browse files
Add input validation to cyclic_sort to prevent invalid inputs (#15009)
* Add input validation to cyclic_sort * Add input validation to cyclic_sort * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * f string literal bug resolved * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * test cyclic sort input validation * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 5a6cc48 commit c2318ab

1 file changed

Lines changed: 29 additions & 5 deletions

File tree

sorts/cyclic_sort.py

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
python -m doctest -v cyclic_sort.py
66
or
77
python3 -m doctest -v cyclic_sort.py
8+
89
For manual testing run:
910
python cyclic_sort.py
1011
or
@@ -27,20 +28,42 @@ def cyclic_sort(nums: list[int]) -> list[int]:
2728
[]
2829
>>> cyclic_sort([3, 5, 2, 1, 4])
2930
[1, 2, 3, 4, 5]
31+
32+
>>> cyclic_sort([1, 2, 2])
33+
Traceback (most recent call last):
34+
...
35+
ValueError: All numbers must be unique, got 2
36+
37+
>>> cyclic_sort([1, 5])
38+
Traceback (most recent call last):
39+
...
40+
ValueError: All numbers must be in range 1 to 2, got 5
3041
"""
3142

43+
# Input validation
44+
seen = set()
45+
n = len(nums)
46+
47+
for num in nums:
48+
if num in seen:
49+
message = f"All numbers must be unique, got {num}"
50+
raise ValueError(message)
51+
52+
if num < 1 or num > n:
53+
message = f"All numbers must be in range 1 to {n}, got {num}"
54+
raise ValueError(message)
55+
56+
seen.add(num)
57+
3258
# Perform cyclic sort
3359
index = 0
3460
while index < len(nums):
35-
# Calculate the correct index for the current element
3661
correct_index = nums[index] - 1
37-
# If the current element is not at its correct position,
38-
# swap it with the element at its correct index
62+
3963
if index != correct_index:
4064
nums[index], nums[correct_index] = nums[correct_index], nums[index]
65+
4166
else:
42-
# If the current element is already in its correct position,
43-
# move to the next element
4467
index += 1
4568

4669
return nums
@@ -50,6 +73,7 @@ def cyclic_sort(nums: list[int]) -> list[int]:
5073
import doctest
5174

5275
doctest.testmod()
76+
5377
user_input = input("Enter numbers separated by a comma:\n").strip()
5478
unsorted = [int(item) for item in user_input.split(",")]
5579
print(*cyclic_sort(unsorted), sep=",")

0 commit comments

Comments
 (0)