Reputation: 15
I have few numbers like a parts of score:
my_list = [10, 5, 20, 30, 25, 10]
sum of my points is 100 - it is maximum
I want to normalize it knowing that the sum should not exceed 100. How can I do this? so if i add another element with score 10, from the rest, a numbers will be subtracted so that the sum becomes 100...
like I'm moving the sliders in the game while having the maximum set of parameter points for my hero, IDK
Is there any library for this process? in numpy|sklearn maybe?
Upvotes: 1
Views: 56
Reputation: 261830
You can use:
my_list = [10, 5, 20, 30, 25, 10]
add = 10
sub = (100-sum(my_list)-add)/len(my_list)
new_list = [x+sub for x in my_list]+[add]
# [8.33, 3.33, 18.33, 28.33, 23.33, 8.33, 10]
sum(new_list)
# 100
Upvotes: 1
Reputation: 19252
You can write a custom function to do this -- no heavy dependencies required. Note that this returns a new list; one could further improve this by creating a class:
def generate_list_with_normalization(input_list, element_to_add, cap=100):
total = sum(input_list) + element_to_add
if total <= cap:
return input_list + [element_to_add]
return [elem * cap / total for elem in input_list + [element_to_add]]
my_list = [10, 5, 20, 30, 25, 10]
result = generate_list_with_normalization(my_list, 10, 100)
print(result)
print(sum(result))
This outputs:
[9.090909090909092, 4.545454545454546, 18.181818181818183,
27.272727272727273, 22.727272727272727, 9.090909090909092, 9.090909090909092]
100.0
Upvotes: 1