Compare lists with multiple elements

Question:

I have a tuple as follows s=[(1,300),(250,800),(900,1000),(1200,1300),(1500,2100)]
I need to compare the upper limit of the list with the lower limit of the next list. If the lower limit of the next list is less than the upper limit of the previous list than it should throw error else it should pass.
Example:

s=[(1,300),(250,800),(900,1000),(1200,1300),(1500,2100)] – This should throw error as 250<300.If it fails for any one, it should throw error immediately.

s=[(1,300),(350,800),(900,1000)] – This should not throw error as 350>300.

I have tried something like this:

s=[(1,300),(250,800),(900,1000)]
s= (sorted(s))
print(s)
def f(mytuple, currentelement):
    return mytuple[mytuple.index(currentelement) + 1]
for i in s:
    j = f(s,i)
    if i[0]<j[1]:
        print("fail")
    else:
        print("pass")
Asked By: anurag kumar anu

||

Answers:

Two problems I see:

1) You’re running into an out of bounds error, as the last element (900,1000) is trying to check the follow element which does not exist.

You can skip the last element by adding [:-1] to your loop.

2) In addition, your “if” condition seems to be backwards. You seem to be wanting to compare i[1] with j[0] instead of i[0] with j[1].

s=[(1,300),(250,800),(900,1000)]
s= (sorted(s))
print(s)
def f(mytuple, currentelement):
    return mytuple[mytuple.index(currentelement) + 1]
for i in s[:-1]:
    j = f(s,i)
    if i[1]>j[0]:
        print("fail")
    else:
        print("pass")

See How to loop through all but the last item of a list? for more details.

Answered By: Seth McNaughton

zip() combines lists (or any iterables) to a new iterable. It stops when the shortest list is exhausted. Imagine:

a = [1, 2, 3, 4]
b = ['a', 'b', 'c']
zipped = zip(a, b) # Gives: [(1, 'a'), (2, 'b'), (3, 'c')] 
# 4 is skipped, because there is no element remaining in b

We can used this to get all pairs in s in an elegant, easy to read form:

s=[(1,300),(250,800),(900,1000)]
s= (sorted(s))
pairs = zip(s, s[1:]) # zip s from index 0 with s from index 1

Now that we have pairs in the form of ((a0, a1), (b0, b1)) you can easily compare if a1 > b0 in a loop:

for a,b in pairs:
    if a[1] > b[0]:
        print("fail")
    else:
        print("pass")
Answered By: tcdejong