Nicolas
Nicolas

Reputation: 13

How to sum the elements of a list if the difference of elements in another list is less than a certain value

Given that two lists have the same size. I want to first compute the difference between consecutive elements in one list, then sum the corresponding elements in the second list if the difference meets a criteria.

For example:

List_1 = [0.1, 0.2, 0.3, 0.5, 0.6, 0.9]
List_2 = [1, 1, 1, 1, 1, 1]

I want to sum the corresponding elements in List_2 if the difference between consecutive elements in List_1 is less than or equal to 0.1. If the difference is greater than 0.1, then do nothing. In this case, the difference in List_1 is [0.1, 0.1, 0.2, 0.1, 0.3] then my expected list of sum is [ 3, 2, 1].

Upvotes: 1

Views: 482

Answers (1)

finefoot
finefoot

Reputation: 11234

The following code essentially uses slicing and Python's built-in function zip to provide suitable iterables for the for loop. I tried to add some explanatory calls to print to show what's going on:

# Your list input
X = [0.1, 0.2, 0.3, 0.5, 0.6, 0.9]
Y = [1, 2, 4, 8, 16, 32]

# Calculate sums
Z = [Y[0]]
for x_1, x_2, y in zip(X, X[1:], Y[1:]):
    print(f"Z currently looks like this: {Z}")
    print(f"Is {x_1} to {x_2} leq 0.1? {x_2 - x_1 <= 0.1}", end=" ")
    if x_2 - x_1 <= 0.1:
        print(f"=> Add {y} to last sum in Z")
        Z[-1] += y
    else:
        print(f"=> Use {y} to start a new sum in Z")
        Z += [y]

print("Final result:", Z)

Will print:

Z currently looks like this: [1]
Is 0.1 to 0.2 leq 0.1? True => Add 2 to last sum in Z
Z currently looks like this: [3]
Is 0.2 to 0.3 leq 0.1? True => Add 4 to last sum in Z
Z currently looks like this: [7]
Is 0.3 to 0.5 leq 0.1? False => Use 8 to start a new sum in Z
Z currently looks like this: [7, 8]
Is 0.5 to 0.6 leq 0.1? True => Add 16 to last sum in Z
Z currently looks like this: [7, 24]
Is 0.6 to 0.9 leq 0.1? False => Use 32 to start a new sum in Z
Final result: [7, 24, 32]

Of course, you can just remove all calls to print and the code will still work.

Upvotes: 1

Related Questions