Home > Blockchain >  Return tuple with biggest increase of second value in a list of tuples
Return tuple with biggest increase of second value in a list of tuples

Time:01-24

like the title says I have a list of tuples: [(3, 20), (9, 21), (18, 19)]. I need to find the tuple that has a positive y-increase wrt its predecessor. In this case 21-20 = 1. So tuple (9,21) should be returned. 19-21 = -1 so tuple (18,19) shouldn't be returned. The very first tuple in the list should never be returned. I've tried putting all the values in a list and then trying to figure it out but I'm clueless. It should work for lists of tuples of any length. I hope you guys can help me out, thanks in advance.

CodePudding user response:

I think something like that can solve your problem:

import numpy as np

data =  [(3, 20), (9, 21), (18, 19), (10, 22)]
diff_with_previous = []
for i in range(len(data)):
    if i == 0:
        diff_with_previous.append(-np.inf)
    else:
        diff_with_previous.append(data[i][1] - data[i-1][1])
indices = np.where(np.array(diff_with_previous) > 0)
print([data[i] for i in indices[0]])

CodePudding user response:

You could compare the second element of each tuple with the previous one, while iterating over the list:

data = [(3, 20), (9, 21), (18, 19), (1, 35), (4, 37), (1, 2)]

maxIncrease = [0, 0] # store max increase value and it's index
for i in range(1, len(data)):
    lst = data[i - 1]
    cur = data[i]

    diff = cur[1] - lst[1]
    if diff > maxIncrease[0]:
        maxIncrease = [diff, i]

print(
    f'Biggest increase of {maxIncrease[0]} found at index {maxIncrease[1]}: {data[maxIncrease[1]]}'
)

Out:

Biggest increase of 16 found at index 3: (1, 35)
  •  Tags:  
  • Related