Search code examples
pythonpython-3.xfor-loopenumerate

How to check all the integers in the list are continuous?


I am trying to write a program which will print "YES" if all the numbers in the list are continuous and should return "NO" if the numbers are not continuous. By continuous I mean every number in the list should be greater than one from the previous element.

For example:

  • It should print "YES" for inputs: [3, 4, 5], [7, 8, 9], [1, 2, 3], [0, 1, 2, 3, 4, 5].. etc

  • It should print "NO" for inputs: [9, 1, 0], [3, 2, 4], [5, 5], [9, 8, 2, 3, 7].. etc

I used enumerate for this purpose.

Here's my code:

    inp=[1,2,3,4,5]
    flag=0
    for index,e in enumerate(inp): 
        if index!=len(inp)-1:    
            if inp[index+1]==inp[index]+1:
                flag=1
    if flag==1:
        print ("YES")
    else:
        print ("NO")

The code works fine but i find it redundant.
Is there a better way to do it using enumerate or without using enumerate?


Solution

  • You don't need enumerate in order to check the elements of your lists are continuous. You can simply achieve it via creating a function using zip and all as:

    def check_continuity(my_list):
        return all(a+1==b for a, b in zip(my_list, my_list[1:]))
    

    Same result can be achieved by any with zip as (similar to all but with not and != for comparision):

    def check_continuity(my_list):
        return not any(a+1!=b for a, b in zip(my_list, my_list[1:]))
    

    Above functions will return True/False depending upon whether your list is continuous or not.

    Sample run:

    # Continuous Lists
    >>> check_continuity([3, 4, 5])
    True
    >>> check_continuity([7, 8, 9])
    True
    >>> check_continuity([1, 2, 3])
    True
    
    # Non Continuous Lists
    >>> check_continuity([9, 1, 0])
    False
    >>> check_continuity([3, 2, 4])
    False
    >>> check_continuity([5, 5])
    False
    

    In order to print "YES"/"NO", you may make a simple if..elsecheck outside the function call as:

    >>> "YES" if check_continuity([1, 2, 3]) else "NO"
    'YES'
    
    # OR update the return statement in your function to
    #    return "NO" if any(a+1!=b for a, b in zip(my_list, my_list[1:])) else "YES"