Posts: 11
Threads: 4
Joined: Mar 2020
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 ?
Posts: 6,196
Threads: 16
Joined: Feb 2020
Posts: 456
Threads: 16
Joined: Jun 2022
Aug-12-2022, 04:52 PM
(This post was last modified: Aug-13-2022, 11:45 AM by rob101.
Edit Reason: added comments
)
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.
Sig:
>>> import this
The UNIX philosophy: "Do one thing, and do it well."
"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse
"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Posts: 1,566
Threads: 3
Joined: Mar 2020
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.
Posts: 6,196
Threads: 16
Joined: Feb 2020
Aug-12-2022, 07:20 PM
(This post was last modified: Aug-12-2022, 07:20 PM by deanhystad.)
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)
|