- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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 Questions & Answers
- 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 all elements of the array are palindrome or not in Python
- Check if a binary string contains consecutive same or not in C++
- Check if a string is Isogram or not in Python
- Check if all levels of two trees are anagrams or not in Python
- Check whether the frequencies of all the characters in a string are prime or not in Python
- Python program to check if the string is empty or not
- Python program to check if a string is palindrome or not
- Python Pandas - Check if the dataframe objects are equal or not
- Check if it is possible to rearrange a binary string with alternate 0s and 1s in Python
- How to check if all values in a vector are integer or not in R?
- Check if a binary tree is sorted levelwise or not in C++

Advertisements