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

How to subtract values in a list

I am writing a function that works as follows it receives list of numbers e.g [0.5,-0.5,1]
then it returns a list with this in each index[(-0.5-0.5) + (1-0.5)]. In other words, it adds the difference between the current value and the other values. So the output should be [-0.5,2.5,-2]

def  Calculate(initial_values,b):
   x = np.array([initial_values]).T
   results=[0]
   for i in range(len(initial_values)):
     results.append( (initial_values[:i] - initial_values[i])+(initial_values[i+1:]-initial_values[i])

Error

TypeError: unsupported operand type(s) for -: 'list' and 'float'

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 :

This seems to do the trick:

def Calculate(arr):
    res = []
    for i, val in enumerate(arr):
        total = -val * (len(arr) - 1) + sum(arr[0:i]) + sum(arr[i+1:])
        res.append(total)
    return res

We iterate through each element and calculate the sum of differences like you described. Since the current element gets subtracted from each term we can factor it out.

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