Syntax error Program to check if binary string has at most one segment of ones or not using Python

Program to check if binary string has at most one segment of ones or not using Python



Suppose we have a binary string s (without leading zeros), We have to check whether s contains at most one contiguous segment of ones or not.

So, if the input is like s = "11100", then the output will be True as there is one segment of ones "111".

To solve this, we will follow these steps −

  • count := -1

  • if size of s is same as 1, then

    • return True

  • for each i in s, do

    • if i is same as "1" and count > -1, then

      • return False

    • otherwise when i is same as "0", then

      • count := count + 1

  • return True

Let us see the following implementation to get better understanding −

Example

 Live Demo

def solve(s):
   count = -1
   if len(s)==1:
      return True
   for i in s:
         if i=="1" and count>-1:
            return False
         elif i=="0":
            count+=1
   return True
s = "11100"
print(solve(s))

Input

11100

Output

True
Updated on: 2021-05-29T14:31:34+05:30

492 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements