Home > Software engineering >  find indices of matching characters in list of string python
find indices of matching characters in list of string python

Time:03-02

I have a list of bitstrings and for every bitstring there are 2 entangled bits that are always either 00 or 11. How do I find the indices of the bits assuming all of the strings are the same length?

For example lets say there are 3 bits and this is the list:

list = ['000', '110', '001', '111']
# indices 0 and 1 are entangled because they are 
# always either 00 or 11 and index 2 is independent of them

I tried mapping to find which are always 00 but this doesn't work because they can also be 11 for larger strings. thanks

CodePudding user response:

for x in range(len(list[0])-1):
    if all(bits[x] == bits[x 1] for bits in list):
        print('index', x, 'and index', x 1, 'are entangled')

CodePudding user response:

Considering that in a string 3 chars long, the most common value must be the 'entangled' one. So we can just map each list to whether or not the individual bits equal the most common bit, then look for the columns where the results are all the same.

import numpy as np
l =  ['000', '010', '101', '111']
l = np.array(l)


def true_false(e):
    return list(map(lambda x: x==str(np.bincount(list(e)).argmax()),list(e)))

b = np.array(list(map(true_false,l)))

np.all(b == b[0,:], axis = 0).nonzero()

Output

(array([0, 2], dtype=int64),)
  • Related