Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert a list with a sum of 1 and keep the relations between the values

Assume there is a list[int] like this:

[0, 2, 3, 3, 0, 9]

I want to convert it to list[float] with a sum of 1 and keep the relations between the values:

[a, b, c, d, e, f]

# a = e = 0
# c = d
# f = 4.5b = 3c = 3d
# a + b + c + d + e + f = 1

[0.0, x, 1.5x, 1.5x, 0.0, 4.5x]

I guess there is a built-in function that does that in some modules like math or statistics, not sure what it is called.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Not sure if an inbuilt function exists, but perhaps you can just use a list comprehension:

>>> input_list = [0, 2, 3, 3, 0, 9]
>>> total = sum(input_list)
>>> [x / total for x in input_list]
[0.0, 0.11764705882352941, 0.17647058823529413, 0.17647058823529413, 0.0, 0.5294117647058824]

I thought you could use the walrus operator (:=) to do this in one line [x / (total := sum(input_list)) for x in input_list] and only calculate sum(input_list) once, but apparently, that is not the case.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading