Program to check all 1s are present one after another or not in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of numbers called nums that contains at least one element whose value is 1. We have to check whether all the 1s appear consecutively or not.

So, if the input is like nums = [8, 2, 1, 1, 1, 3, 5], then the output will be True.

To solve this, we will follow these steps −

  • visited := 0

  • for each x in nums, do

    • if x is same as 1, then

      • if visited is same as 2, then

        • return False

      • visited := 1

    • otherwise when visited is non-zero, then

      • visited := 2

  • return True

Example

Let us see the following implementation to get better understanding

def solve(nums):
   visited = 0
   for x in nums:
      if x == 1:
         if visited == 2:
            return False
         visited = 1
      elif visited:
         visited = 2
   return True

nums = [8, 2, 1, 1, 1, 3, 5]
print(solve(nums))

Input

[8, 2, 1, 1, 1, 3, 5]

Output

True
raja
Published on 11-Oct-2021 06:55:36
Advertisements