55python -m doctest -v cyclic_sort.py
66or
77python3 -m doctest -v cyclic_sort.py
8+
89For manual testing run:
910python cyclic_sort.py
1011or
@@ -27,42 +28,34 @@ def cyclic_sort(nums: list[int]) -> list[int]:
2728 []
2829 >>> cyclic_sort([3, 5, 2, 1, 4])
2930 [1, 2, 3, 4, 5]
30- >>> cyclic_sort([1, 2, 5])
31-
32- Traceback (most recent call last):
33- ...
34- ValueError: All numbers must be in range 1 to 3, got 5
35-
36- >>> cyclic_sort([1, 2, 2])
37- Traceback (most recent call last):
38- ...
39- ValueError: All numbers must be unique, got [1, 2, 2]
4031 """
32+
4133 # Input validation
4234 seen = set ()
4335 n = len (nums )
4436
4537 for num in nums :
4638 if num in seen :
47- raise ValueError (f"All numbers must be unique, got { nums } " )
39+ message = f"All numbers must be unique, got { nums } "
40+ raise ValueError (message )
4841
4942 if num < 1 or num > n :
50- raise ValueError (f"All numbers must be in range 1 to { n } , got { num } " )
43+ message = f"All numbers must be in range 1 to { n } , got { num } "
44+ raise ValueError (message )
5145
5246 seen .add (num )
5347
5448 # Perform cyclic sort
5549 index = 0
5650 while index < len (nums ):
57- # Calculate the correct index for the current element
5851 correct_index = nums [index ] - 1
59- # If the current element is not at its correct position,
60- # swap it with the element at its correct index
52+
6153 if index != correct_index :
62- nums [index ], nums [correct_index ] = nums [correct_index ], nums [index ]
54+ nums [index ], nums [correct_index ] = (
55+ nums [correct_index ],
56+ nums [index ],
57+ )
6358 else :
64- # If the current element is already in its correct position,
65- # move to the next element
6659 index += 1
6760
6861 return nums
@@ -72,6 +65,7 @@ def cyclic_sort(nums: list[int]) -> list[int]:
7265 import doctest
7366
7467 doctest .testmod ()
68+
7569 user_input = input ("Enter numbers separated by a comma:\n " ).strip ()
7670 unsorted = [int (item ) for item in user_input .split ("," )]
77- print (* cyclic_sort (unsorted ), sep = "," )
71+ print (* cyclic_sort (unsorted ), sep = "," )
0 commit comments