MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / array_equalization

Function array_equalization

matrix/matrix_equalization.py:4–49  ·  view source on GitHub ↗

This algorithm equalizes all elements of the input vector to a common value, by making the minimal number of "updates" under the constraint of a step size (step_size). >>> array_equalization([1, 1, 6, 2, 4, 6, 5, 1, 7, 2, 2, 1, 7, 2, 2], 4) 4 >>> array_equalization([22, 81,

(vector: list[int], step_size: int)

Source from the content-addressed store, hash-verified

2
3
4def array_equalization(vector: list[int], step_size: int) -> int:
5 """
6 This algorithm equalizes all elements of the input vector
7 to a common value, by making the minimal number of
8 "updates" under the constraint of a step size (step_size).
9
10 >>> array_equalization([1, 1, 6, 2, 4, 6, 5, 1, 7, 2, 2, 1, 7, 2, 2], 4)
11 4
12 >>> array_equalization([22, 81, 88, 71, 22, 81, 632, 81, 81, 22, 92], 2)
13 5
14 >>> array_equalization([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 5)
15 0
16 >>> array_equalization([22, 22, 22, 33, 33, 33], 2)
17 2
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
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
35 unique_elements = set(vector)
36 min_updates = maxsize
37
38 for element in unique_elements:
39 elem_index = 0
40 updates = 0
41 while elem_index < len(vector):
42 if vector[elem_index] != element:
43 updates += 1
44 elem_index += step_size
45 else:
46 elem_index += 1
47 min_updates = min(min_updates, updates)
48
49 return min_updates
50
51
52if __name__ == "__main__":

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected