Detect whether sequence is a multiple of a subsequence in Python

前端 未结 7 1598
轮回少年
轮回少年 2021-02-07 14:44

I have a tuple of zeros and ones, for instance:

(1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1)

It turns out:

(1, 0, 1, 1, 1, 0, 1, 1, 1,          


        
7条回答
  •  甜味超标
    2021-02-07 15:01

    You can archive it in sublinear time by XOR'ing the rotated binary form for the input array:

    1. get the binary representation of the array, input_binary
    2. loop from i = 1 to len(input_array)/2, and for each loop, rotate the input_binary to the right by i bits, save it as rotated_bin, then compare the XOR of rotated_bin and input_binary.
    3. The first i that yields 0, is the index to which is the desired substring.

    Complete code:

    def get_substring(arr):
        binary = ''.join(map(str, arr)) # join the elements to get the binary form
    
        for i in xrange(1, len(arr) / 2):
            # do a i bit rotation shift, get bit string sub_bin
            rotated_bin = binary[-i:] + binary[:-i]
            if int(rotated_bin) ^ int(binary) == 0:
                return arr[0:i]
    
        return None
    
    
    if __name__ == "__main__":
        test = [1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1]
        print get_substring(test) # [1,0,1,1]
    

提交回复
热议问题