Detect whether sequence is a multiple of a subsequence in Python

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

    Just a different approach to the problem

    I first determine all the factors of the length and then split the list and check if all the parts are same

    >>> def f(s):
        def factors(n):
            #http://stackoverflow.com/a/6800214/977038
            return set(reduce(list.__add__,
                    ([i, n//i] for i in range(2, int(n**0.5) + 1) if n % i == 0)))
        _len = len(s)
        for fact in reversed(list(factors(_len))):
            compare_set = set(izip(*[iter(s)]*fact))
            if len(compare_set) == 1:
                return compare_set
    
    
    >>> f(t)
    set([(1, 0, 1, 1)])
    

提交回复
热议问题