
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
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
- Related Articles
- Python - Check if a given string is binary string or not
- Program to check whether every one has at least a friend or not in Python
- Check if a binary string has a 0 between 1s or not in C++
- Program to check whether one string swap can make strings equal or not using Python
- Python program to check if a string is palindrome or not
- Python program to check if the string is empty or not
- How to check if a string has at least one letter and one number in Python?
- Python program to check if a given string is Keyword or not
- Program to check if the given list has Pythagorean Triplets or not in Python
- C# program to check if string is panagram or not
- Swift program to check if string is pangram or not
- Check if a binary string has two consecutive occurrences of one everywhere in C++
- Check if all the 1s in a binary string are equidistant or not in Python
- Check if a binary string contains consecutive same or not in C++
- Program to check string contains consecutively descending string or not in Python

Advertisements