0

if my list is in the following format:

a=[1,3,4,5,8,10]

How can I show that the elements are not increasing by 1? In other words, if my list is

a=[1,2,3,4,5,6]

the function should say that it is sequential i.e. each element is greater than the previous element by one. Thanks in advance.

2
  • 3
    Stack Overflow is not here to do your work for you, though we're happy to help if you've tried some things and run into problems. Show us your code and let us know what's going wrong and you'll probably get a helpful answer right away. Commented Apr 7, 2014 at 5:38
  • These reasonable comments, followed by 5 answers below... Why does this happen? Commented Apr 7, 2014 at 6:02

5 Answers 5

1

One simple way to do the testing is

if all(x[i] == x[0]+i for i in range(1, len(x))):
    ...
Sign up to request clarification or add additional context in comments.

Comments

1
>>> a=[1,2,3,4,5,6]
>>> all(i==j for i,j in enumerate(a, a[0]))
True

>>> a=[1,3,4,5,8,10]
>>> 
>>> all(i==j for i,j in enumerate(a, a[0]))
False

2 Comments

@6502, it was rubbish. I've got an improved version
+1: compact and avoids re-evaluating a [0]. It would complain with floats but the OP is consifering integers..
0

You can use zip and set:

def check_sequential(a):
    return set([p - q for p, q in zip(a[1:], a)]) == {1}

print check_sequential([1,3,4,5,8,10])
print check_sequential([1,2,3,4,5])

Output:

False
True

Comments

0

Use numpy.

Differentiate it

Use Max.

1 Comment

Better check min too in case the sequence isn't increasing
0

For short lists, you can just create a sequential range yourself and compare them

>>> a = [1,2,3,4,5,6]
>>> a == range(a[0], a[-1] + 1) # in Python3, you need list(range(...))
True
>>> a = [1,3,4,5,8,10]
>>> a == range(a[0], a[-1] + 1)
False

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.