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

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

    Non-regex solution:

    def repeat(string):
        for i in range(1, len(string)//2+1):
            if not len(string)%len(string[0:i]) and string[0:i]*(len(string)//len(string[0:i])) == string:
                return string[0:i]
    

    Faster non-regex solution, thanks to @ThatWeirdo (see comments):

    def repeat(string):
        l = len(string)
        for i in range(1, len(string)//2+1):
            if l%i: continue
            s = string[0:i]
            if s*(l//i) == string:
                return s
    

    The above solution is very rarely slower than the original by a few percent, but it's usually a good bit faster - sometimes a whole lot faster. It's still not faster than davidism's for longer strings, and zero's regex solution is superior for short strings. It comes out to the fastest (according to davidism's test on github - see his answer) with strings of about 1000-1500 characters. Regardless, it's reliably second-fastest (or better) in all cases I tested. Thanks, ThatWeirdo.

    Test:

    print(repeat('009009009'))
    print(repeat('254725472547'))
    print(repeat('abcdeabcdeabcdeabcde'))
    print(repeat('abcdefg'))
    print(repeat('09099099909999'))
    print(repeat('02589675192'))
    

    Results:

    009
    2547
    abcde
    None
    None
    None
    

提交回复
热议问题