Given a list of numbers, write a Python program to check if the list contains consecutive integers.
Input : [2, 3, 1, 4, 5] Output : True Input : [1, 2, 3, 5, 6] Output : False
Let’s discuss the few ways we can do this task.
Approach #1 : using
This approach uses
sorted() function of Python. We compare the sorted list with list of range of minimum and maximum integer of the list and return it.
Approach #2 : Using
Numpy module provides a function
diff() that calculate the n-th discrete difference along the given axis. We find the iterative difference of the sorted list and check if it is equal to 1.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course