|
1 |
| -import sys |
| 1 | +from sys import maxsize |
2 | 2 |
|
3 | 3 |
|
4 |
| -def array_equalization(vector: list[int], k: int) -> int: |
| 4 | +def array_equalization(vector: list[int], step_size: int) -> int: |
5 | 5 | """
|
6 |
| -
|
7 | 6 | This algorithm equalizes all elements of the input vector
|
8 | 7 | to a common value, by making the minimal number of
|
9 |
| - "updates" under the constraint of a step size (k) |
10 |
| -
|
11 |
| - details: https://www.geeksforgeeks.org/equalize-array-using-array-elements/ |
| 8 | + "updates" under the constraint of a step size (step_size). |
12 | 9 |
|
13 | 10 | >>> array_equalization([1, 1, 6, 2, 4, 6, 5, 1, 7, 2, 2, 1, 7, 2, 2], 4)
|
14 | 11 | 4
|
15 | 12 | >>> array_equalization([22, 81, 88, 71, 22, 81, 632, 81, 81, 22, 92], 2)
|
16 | 13 | 5
|
17 |
| - >>> array_equalization([-22, 81, -88, 71, 22, 81, 632, 81, -81, -22, 92], 2) |
18 |
| - 5 |
19 | 14 | >>> array_equalization([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 5)
|
20 | 15 | 0
|
21 |
| - >>> array_equalization([sys.maxsize for c in range(10)], 3) |
22 |
| - 0 |
23 | 16 | >>> array_equalization([22, 22, 22, 33, 33, 33], 2)
|
24 | 17 | 2
|
25 |
| -
|
| 18 | + >>> array_equalization([1, 2, 3], 0) |
| 19 | + Traceback (most recent call last): |
| 20 | + ValueError: Step size must be positive and non-zero. |
| 21 | + >>> array_equalization([1, 2, 3], -1) |
| 22 | + Traceback (most recent call last): |
| 23 | + ValueError: Step size must be positive and non-zero. |
| 24 | + >>> array_equalization([1, 2, 3], 0.5) |
| 25 | + Traceback (most recent call last): |
| 26 | + ValueError: Step size must be an integer. |
| 27 | + >>> array_equalization([1, 2, 3], maxsize) |
| 28 | + 1 |
26 | 29 | """
|
| 30 | + if step_size <= 0: |
| 31 | + raise ValueError("Step size must be positive and non-zero.") |
| 32 | + if not isinstance(step_size, int): |
| 33 | + raise ValueError("Step size must be an integer.") |
| 34 | + |
27 | 35 | unique_elements = set(vector)
|
28 |
| - min_updates = sys.maxsize |
| 36 | + min_updates = maxsize |
29 | 37 |
|
30 | 38 | for element in unique_elements:
|
31 | 39 | elem_index = 0
|
32 | 40 | updates = 0
|
33 | 41 | while elem_index < len(vector):
|
34 | 42 | if vector[elem_index] != element:
|
35 | 43 | updates += 1
|
36 |
| - elem_index += k |
| 44 | + elem_index += step_size |
37 | 45 | else:
|
38 | 46 | elem_index += 1
|
39 | 47 | min_updates = min(min_updates, updates)
|
|
0 commit comments