Detect whether sequence is a multiple of a subsequence in Python

前端 未结 7 1597
轮回少年
轮回少年 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:11

    Here's another solution (competing with my earlier iterators-based solution), leveraging numpy.

    It does make a (single) copy of your data, but taking advantage of the fact your values are 0s and 1s, it is super-fast, thanks to numpy's magics.

    import numpy as np
    
    def is_reps(arr, slice_size):
        if len(arr) % slice_size != 0:
            return False
        arr = arr.reshape((-1, slice_size))
        return (arr.all(axis=0) | (~arr).all(axis=0)).all()
    
    s = (1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1) * 1000
    a = np.array(s, dtype=bool)
    for i in range(1,len(s)):
        if is_reps(a, i):
            print i, s[:i]
            break
    
    0 讨论(0)
提交回复
热议问题