Created
June 19, 2019 08:59
-
-
Save ogvalt/f6972b69d8b64e2c67ed1143be018e9b to your computer and use it in GitHub Desktop.
Brute force solution for dividing array into 3 parts of equal sum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def best_division(a): | |
""" | |
This function performs exhastive search over all possible divisions of array into 3 parts with equal sums | |
a - array on numbers (list<int|float>) | |
""" | |
results = [] | |
for i in range(1, len(a)-2+1): | |
for j in range(i+1, len(a)-1+1): | |
first, second, third = sum(a[:i]), sum(a[i:j]), sum(a[j:]) | |
opt_func = abs(first - second) + abs(second - third) + abs(first - third) | |
results.append([opt_func, [[i, j], [first, second, third]]]) | |
sorted_res = sorted(results, key=lambda x: x[0]) | |
return sorted_res[0] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment