How can I tell if a string repeats itself in Python?

后端 未结 13 1413
栀梦
栀梦 2020-11-27 09:07

I\'m looking for a way to test whether or not a given string repeats itself for the entire string or not.

Examples:

[
    \'0045662100456621004566210         


        
13条回答
  •  时光取名叫无心
    2020-11-27 09:15

    This function runs very quickly (tested and it's over 3 times faster than fastest solution here on strings with over 100k characters and the difference gets bigger the longer the repeating pattern is). It tries to minimise the number of comparisons needed to get the answer:

    def repeats(string):
        n = len(string)
        tried = set([])
        best = None
        nums = [i for i in  xrange(2, int(n**0.5) + 1) if n % i == 0]
        nums = [n/i for i in nums if n/i!=i] + list(reversed(nums)) + [1]
        for s in nums:
            if all(t%s for t in tried):
                print 'Trying repeating string of length:', s
                if string[:s]*(n/s)==string:
                    best = s
                else:
                    tried.add(s)
        if best:
            return string[:best]
    

    Note that for example for string of length 8 it checks only fragment of size 4 and it does not have to test further because pattern of length 1 or 2 would result in repeating pattern of length 4:

    >>> repeats('12345678')
    Trying repeating string of length: 4
    None
    
    # for this one we need only 2 checks 
    >>> repeats('1234567812345678')
    Trying repeating string of length: 8
    Trying repeating string of length: 4
    '12345678'
    

提交回复
热议问题