Home > Software engineering >  How to subtract values in a list
How to subtract values in a list

Time:11-30

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'

CodePudding user response:

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.

CodePudding user response:

The operations that you are doing inside Calculate() clearly assume that the input initial_opinion is a NumPy Array, and not a list. NumPy arrays support broadcast operations, lists do not.

So you should call your function with the right kind of input, e.g.:

Calculate(np.array([0.5, -0.5, 1]), 5)

Now, there are other errors with your code (parentheses are not balanced, and the calculation doesn't quite make sense yet), but if you pass the right kind of data type in, you'll be able to get further with your work.

With a NumPy Arrays, you can add an array to another array of the same size for a direct addition, or an array to a scalar to add that scalar's value to all the elements, and all sorts of other broadcast operations are supported for vectorized computations.

  • Related