简体   繁体   English

一个字符串会重复多少次 - python?

[英]how many times does a string repeat itself - python?

I have strings in python like 'abcabcabc', 'abcdbabcdb'.我在 python 中有字符串,例如“abcabcabc”、“abcdbabcdb”。 How do I return the number of times a substring repeats itself within a string?如何返回 substring 在字符串中重复的次数?

You want to find the longest substring in a string and return the occurrences.您想在字符串中找到最长的 substring 并返回出现次数。 The first one would return 3, and the second one would return 2.第一个将返回 3,第二个将返回 2。

Assuming that the repetition of a substring can be partial at the end of the original string (ie the length of the substring is not necessarily an integer divisor of the length of the string), you could do it like this:假设 substring 的重复可以在原始字符串的末尾部分重复(即 substring 的长度不一定是字符串长度的 integer 除数),您可以这样做:

def maxRep(s):
 return len(s)/next(i for i in range(1,len(s)+1) if (s[:i]*len(s)).startswith(s))

output: output:

s = 'abcabcabc'
r = maxRep(s)
print(s,r) # 3.0

s = 'abcdbabcdb'
r = maxRep(s)
print(s,r) # 2.0

s = 'abcdbabcdbab'
r = maxRep(s)
print(s,r) # 2.4

The function uses a brute force approach where every possible length of repeating substring is attempted to see if the result matches the string. function 使用蛮力方法,尝试重复 ZE83AED3DDF4667DEC0DAAAACB2BB3BE0BZ 的每个可能长度,以查看结果是否与字符串匹配。 The smallest substring length is used (ie the first length that matches) because this will give the greatest number of repetitions.使用最小的 substring 长度(即匹配的第一个长度),因为这将提供最大数量的重复。

if you need the substring to be completely repeated (ie no partial substring at the end, you can adjust the function like this:如果您需要 substring 完全重复(即最后没有部分 substring,您可以像这样调整 function:

def maxRep(s):
    return len(s)//next(i for i in range(1,len(s)+1) if not any(s.split(s[:i])))

The condition is based on the fact that splitting the string using the a perfectly repeated substring will only produce empty values in the resulting list该条件基于这样一个事实,即使用完美重复的 substring 拆分字符串只会在结果列表中产生空值

Use regex to find the greatest string that repeat itself:使用正则表达式查找重复的最大字符串:

import re

a = 'abcabcabc'
regex = r'(\w+)(?:.*\1)+'
# greatest must contains: 'abc'
greatest = re.findall(regex, a)[0]

Now you can count the number of occurence:现在您可以计算出现次数:

a.count(greatest)

Do you mean something like this:你的意思是这样的:

def repeat_finder(string):
    for i in range(len(string)//2,0,-1):
        if len(string)%i==0:
            n = len(string)//i
            if string == string[:i]*n:
                return (string[:i],n)
    return 'Not a repeat string.'

repeat_finder('abababab')
repeat_finder('sdlkfkfkfkffdd')
repeat_finder('ababababab')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM