Search code examples
pythonpython-3.xsubsequence

Simple method to find 0,0,1 in that order, within a given List


I am trying to write a simple function to find if 0,0,1 occurs in a list, in that order.
It should return True or False.

The list can contain any number of numbers.
For the function ZeroZeroOne examples would be as follows:

>> ZeroZeroOne( [0,0,1] )
>> True

>> ZeroZeroOne( [1,0,0] )
>> False

# there are 2s in between but the following does have 0,0,1 occurring and in correct order 
>> ZeroZeroOne( [0,2,2,2,2,0,1] )
>> True

I have this function:

def ZeroZeroOne(nums):
      
    FoundIt = False

    #quick return if defo not possible
    if (nums.count(0) < 2) and (nums.count(1) == 0):
        return FoundIt

    n = len(nums)
    for x in range(n-2):
        if nums[x] == 0:
            for i,z in enumerate(nums[(x+1):]):
                if z==0 and z!=1:
                    for j,q in enumerate(nums[(i+1):]):
                        if q==1 and q!=0:
                            FoundIt=True

    return FoundIt

Why does the function return True for this list [0, 1, 0, 2, 1]?

Moreover....
This function seems overly-complex for a seemingly simple problem.

  • Is there a correct approach to this problem in Python - a canonical or Pythonic approach?
  • Or is ones approach simply opinion-based?

Solution

  • You can achieve this with a single loop - O(n) time complexity. Since it is for this specific case. Try the code below.

    def ZeroZeroOne(nums):
        found_pattern = []
        for num in nums:
            if num == 1:
                found_pattern.append(1)
                if len(found_pattern) == 3:
                    return True
                else:
                    found_pattern = []
            elif num == 0 and len(found_pattern) < 2:
                found_pattern.append(0)
        return False
    
    
    print(ZeroZeroOne([0, 0, 1]))
    print(ZeroZeroOne([0, 1, 0, 2, 1]))
    print(ZeroZeroOne([0, 2, 0, 1]))
    print(ZeroZeroOne([0, 0, 0, 1]))
    print(ZeroZeroOne([0, 2, 2, 2, 2, 0, 1]))
    

    But I think you can generalize this as well if required. Probably you need to look in to how grep works and modify it for your use case if you want a generic approach.