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

后端 未结 13 1410
栀梦
栀梦 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:12

    Here's a straight forward solution, without regexes.

    For substrings of s starting from zeroth index, of lengths 1 through len(s), check if that substring, substr is the repeated pattern. This check can be performed by concatenating substr with itself ratio times, such that the length of the string thus formed is equal to the length of s. Hence ratio=len(s)/len(substr).

    Return when first such substring is found. This would provide the smallest possible substring, if one exists.

    def check_repeat(s):
        for i in range(1, len(s)):
            substr = s[:i]
            ratio = len(s)/len(substr)
            if substr * ratio == s:
                print 'Repeating on "%s"' % substr
                return
        print 'Non repeating'
    
    >>> check_repeat('254725472547')
    Repeating on "2547"
    >>> check_repeat('abcdeabcdeabcdeabcde')
    Repeating on "abcde"
    

提交回复
热议问题