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

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

    I started with more than eight solutions to this problem. Some were bases on regex (match, findall, split), some of string slicing and testing, and some with string methods (find, count, split). Each had benefits in code clarity, code size, speed and memory consumption. I was going to post my answer here when I noticed that execution speed was ranked as important, so I did more testing and improvement to arrive at this:

    def repeating(s):
        size = len(s)
        incr = size % 2 + 1
        for n in xrange(1, size//2+1, incr):
            if size % n == 0:
                if s[:n] * (size//n) == s:
                    return s[:n]
    

    This answer seems similar to a few other answers here, but it has a few speed optimisations others have not used:

    • xrange is a little faster in this application,
    • if an input string is an odd length, do not check any even length substrings,
    • by using s[:n] directly, we avoid creating a variable in each loop.

    I would be interested to see how this performs in the standard tests with common hardware. I believe it will be well short of David Zhang's excellent algorithm in most tests, but should be quite fast otherwise.

    I found this problem to be very counter-intuitive. The solutions I thought would be fast were slow. The solutions that looked slow were fast! It seems that Python's string creation with the multiply operator and string comparisons are highly optimised.

    0 讨论(0)
提交回复
热议问题