Detect whether sequence is a multiple of a subsequence in Python

前端 未结 7 1599
轮回少年
轮回少年 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条回答
  •  梦毁少年i
    2021-02-07 15:08

    Simplifying Knoothe's solution. His algorithm is right, but his implementation is too complex. This implementation is also O(n).

    Since your array is only composed of ones and zeros, what I do is use existing str.find implementation (Bayer Moore) to implement Knoothe's idea. It's suprisingly simpler and amazingly faster at runtime.

    def f(s):
        s2 = ''.join(map(str, s))
        return s[:(s2+s2).index(s2, 1)]
    

提交回复
热议问题