Python Forum

Full Version: Calculate the sum of the differences inside tuple
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello everyone,

I would like to calculate the sum of the differences between each value for each tuple. For instance :

(4,7,9) would give 3 (7-4 = 3) and 2 (9-2). And the sum of these differences would be 5.

And after that, I would like to print only the tuples whith a sum superior to a value.

So, for instance, if I put that list of tuples :

[(4,8,10,13);
(8,11,14,15),
(9;16;18;19)]
And then, I put a condition to print only the tuples with a sum of differences inferior to 10, then it will return this result :

[(4,8,10,13);
(8,11,14,15)]
About the code, I am a little bit lost.

I have no idea how I can calculate the difference between each value of each tuple. Anyone could help me please ?
itertools pairwise might be useful for this.

https://docs.python.org/3/library/itertools.html
How about this:

list_1 = [
    (4,8,10,13),
    (8,11,14,15),
    (9,16,18,19)
    ]

for item in list_1:
    n1,n2,n3,n4 = item
    r1 = n2-n1
    r2 = n3-n2
    r3 = n4-n3
    r_sum = r1+r2+r3
    if r_sum < 10:
        print(item)
Output:
(4, 8, 10, 13) (8, 11, 14, 15)

Adding...

Your syntax is all over the place, which is leading to confusion.

As an example:

[(4,8,10,13);
(8,11,14,15),
(9;16;18;19)]
... this is not a valid List object

And:

(9;16;18;19)
... this is not a valid Tuple object.

Also in your post...

"(4,7,9) would give 3 (7-4 = 3) and 2 (9-2). And the sum of these differences would be 5."

... is not correct. I think you mean...

(4,7,9) would give 3 (7-4 = 3) and 2 (9-7 = 2). And the sum of these differences would be 5.
Can the list ever decrease? Would [2, 7, 5] ever be valid? If so, is the difference in the second pair to be seen as 2 or -2?

If the list always increases or if you take the forward difference (which can be negative), then the sum of all your differences is just the difference between the last and the first value:

(4,8,10,13) => 13 - 4 = 5
(8,11,14,15) => 15 - 8 = 7
(9;16;18;19) => 19 - 9 = 10

Otherwise you're looking for the sum of the absolute differences.
Great insight! Associative property for the win.
(4, 8, 10, 13)
8-4 + 10-8 + 13-10 == 13 + (10 - 10) + (8 - 8) - 4 == 13 - 4

(8, 4, 10, 13)
4-8 + 10-4 + 13-10 == 13 + (10 - 10) + (4 - 4) - 8 == 13 - 8

(10, 2, 15, 9)
2-10 + 15-2 + 9-15 == 9 + (15 - 15) + (2 - 2) - 10 == 9 - 10

However
(10, 2, 15, 9)
abs(2-10) + abs(15-2) + abs(9-15) != 9 - 10 or abs(9-10)