
- Python 3 Basic Tutorial
- Python 3 - Home
- What is New in Python 3
- Python 3 - Overview
- Python 3 - Environment Setup
- Python 3 - Basic Syntax
- Python 3 - Variable Types
- Python 3 - Basic Operators
- Python 3 - Decision Making
- Python 3 - Loops
- Python 3 - Numbers
- Python 3 - Strings
- Python 3 - Lists
- Python 3 - Tuples
- Python 3 - Dictionary
- Python 3 - Date & Time
- Python 3 - Functions
- Python 3 - Modules
- Python 3 - Files I/O
- Python 3 - Exceptions
Check if all the 1s in a binary string are equidistant or not in Python
Suppose we have a binary string str, we have to check whether all of the 1s in the string are equidistant or not. In other words, the distance between every two 1s is same. And the string contains at least two 1s.
So, if the input is like s = "100001000010000", then the output will be True as the 1s are at distance 4 from each other.
To solve this, we will follow these steps −
- index := a new list
- for i in range 0 to size of s, do
- if s[i] is same as 1, then
- insert i at the end of index
- if s[i] is same as 1, then
- t := size of index
- for i in range 1 to t - 1, do
- if (index[i] - index[i - 1]) is not same as (index[1] - index[0]), then
- return False
- if (index[i] - index[i - 1]) is not same as (index[1] - index[0]), then
- return True
Let us see the following implementation to get better understanding −
Example
def solve(s): index = [] for i in range(len(s)): if s[i] == '1': index.append(i) t = len(index) for i in range(1, t): if (index[i] - index[i - 1]) != (index[1] - index[0]): return False return True s = "100001000010000" print(solve(s))
Input
"100001000010000"
Output
True
- Related Articles
- Check if a binary string has a 0 between 1s or not in C++
- Python - Check if a given string is binary string or not
- Program to check all 1s are present one after another or not in Python
- Check if a string has m consecutive 1s or 0s in Python
- Check if a binary string contains consecutive same or not in C++
- Check if all elements of the array are palindrome or not in Python
- Check if a string is Isogram or not in Python
- Check whether the frequencies of all the characters in a string are prime or not in Python
- Program to count substrings with all 1s in binary string in Python
- Check if it is possible to rearrange a binary string with alternate 0s and 1s in Python
- Python - Check If All the Characters in a String Are Alphanumeric?
- Check if all levels of two trees are anagrams or not in Python
- Check if any anagram of a string is palindrome or not in Python
- Check whether the vowels in a string are in alphabetical order or not in Python
- Python program to check if a string is palindrome or not

Advertisements