Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Distance of Bit pairs

I am given a string, and I have to calculate the sum of of each distance of bit pairs where both bits are 1.

For example the given string of 100101 would have the distance of 10
100101 (3)
100101 (5)
100101 (2)

Therefore the sum of distances is 3+5+2=10.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My current code is the following, I can’t really solve what’s wrong, and how should I approach the problem.

def pairs(s):
    count = 0
    for i in range(len(s)):
        if s[i] == '1':
            for j in range(i+1, len(s)):
                if s[j] == '1':
                    count += 1
    return count

if __name__ == "__main__":
    print(pairs("100101")) #10

I have also tried to store the 1’s in a list, but can’t manage to calculate the distance.

>Solution :

The following should do it:

def pairs(s):
    count = 0
    for i in range(len(s)):
        if s[i] == '1':
            dist = 0
            for j in range(i+1, len(s)):
                dist += 1
                if s[j] == '1':
                    count += dist
    return count

if __name__ == "__main__":
    print(pairs("100101")) #10
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading