Home > database >  Select two elements of tuple given interval
Select two elements of tuple given interval

Time:10-27

I have the following tuple:

my_list = (1000, 3000, 7000, 15000 ,790000)

For any given number I give to a selected variable, I want to return both the the value in the tuple minus the interval and the selected value. By interval I eman the delta/difference between the selected value and the prior one I want to output.

Let's say, for example:

selected = 79000
interval = 2

Expected output: (7000, 79000)

or

selected = 7000
interval = 1

Expected output: (3000, 7000)

Note that the order of the values in tehe expected output follows that of the values in the tuple. So never would a larger number be output before a smaller one.

The ouptput I expect both values to be in is either a tuple e.g. (3000, 15000) or a list [3000, 15000].

CodePudding user response:

There might be better ways, but please see my approach below:

def getInterval(myList: list, selected, interval) -> tuple:
    idxSelected = myList.index(selected)
    return (myList[idxSelected - interval], myList[idxSelected])

my_list = [*range(1, 15)]
selected = 4
interval = 3

print(getInterval(my_list, selected, interval))

CodePudding user response:

my_list = (1, 2, 3, 4, 5)

selected = 5
interval = 2
difference = selected-interval

if my_list.index(difference) < my_list.index(selected): #To check if the Difference Value comes before the Selected Value
    print(difference, selected)
else:
    print(selected, difference)

CodePudding user response:

my_list = (1, 2, 3, 4 ,5)

selected = 5
interval = 2
selected_location = my_list.index(selected) #Here, 4

try:
    print([my_list[selected_location-interval], my_list[selected_location]]) #(3, 5)
except:
    print([my_list[selected_location], my_list[selected_location interval]]) #Incase the selected variable is on index 1, then 1-2 would give -1, which is not the desired index
  • Related