如何找到最大在Python中一个字符序列连续重复多少次? [英] How to find the max. number of times a sequence of characters repeats consecutively in Python?
问题描述
我正在研究cs50/pset6/dna项目.我正在努力寻找一种方法来分析一系列字符串,并收集某个特定字符序列连续重复的最大次数.这是一个示例:
I'm working on a cs50/pset6/dna project. I'm struggling with finding a way to analize a sequence of strings, and gather the maximum number of times a certain sequence of characters repeats consecutively. Here is an example:
字符串: JOKHCNHBVDBVDBVDJHGSBVDBVD
我应该寻找的字符序列: BVD
Sequence of characters I should look for: BVD
结果:我的函数应该能够返回 3
,因为在某个点上,字符 BVD
连续重复了三遍,即使我又重复了两次,应该寻找重复次数最多的时间.如果您仍然需要更好的解释,请查看此视频的第一个 1:16
:
Result: My function should be able to return 3
, because in one point the characters BVD
repeat three times consecutively, and even though it repeats again two times, I should look for the time that it repeats the most number of times.
If you still need a better explanation, please look at the first 1:16
of this video: https://www.youtube.com/watch?time_continue=221&v=j84b_EgntcQ&feature=emb_title
如果您能帮助我,我会很乐意,谢谢!
I would LOVE if you could help, thanks!
推荐答案
这有点la脚,但是一种蛮力"的方式是仅检查是否存在最长的子字符串.一旦找到子字符串,请跳出循环:
It's a bit lame, but one "brute-force"ish way would be to just check for the presence of the longest substring possible. As soon as a substring is found, break out of the loop:
编辑-使用函数可能更直接:
EDIT - Using a function might be more straight forward:
def get_longest_repeating_pattern(string, pattern):
if not pattern:
return ""
for i in range(len(string)//len(pattern), 0, -1):
current_pattern = pattern * i
if current_pattern in string:
return current_pattern
return ""
string = "JOKHCNHBVDBVDBVDJHGSBVDBVD"
pattern = "BVD"
longest_repeating_pattern = get_longest_repeating_pattern(string, pattern)
print(len(longest_repeating_pattern))
编辑-说明:
首先,只是一个简单的for循环,该循环从较大的数字开始,然后下降到较小的数字.例如,我们从5开始,然后下降到0(但不包括0),步长为-1:
First, just a simple for-loop that starts at a larger number and goes down to a smaller number. For example, we start at 5 and go down to 0 (but not including 0), with a step size of -1:
>>> for i in range(5, 0, -1):
print(i)
5
4
3
2
1
>>>
如果 string ="JOKHCNHBVDBVDBVDJHGSBVDBVD"
,则 len(string)
为 26
,如果 pattern ="BVD";
,则 len(pattern)
是 3
.
if string = "JOKHCNHBVDBVDBVDJHGSBVDBVD"
, then len(string)
would be 26
, if pattern = "BVD"
, then len(pattern)
is 3
.
返回我的原始代码:
for i in range(len(string)//len(pattern), 0, -1):
输入数字:
for i in range(26//3, 0, -1):
26//3
是一个整数除法,其结果为 8
,因此变为:
26//3
is an integer division which yields 8
, so this becomes:
for i in range(8, 0, -1):
因此,这是一个从 8
到 1
的for循环(请记住,它不会下降到 0
). i
采用每次迭代的新值,首先是 8
,然后是 7
,等等.
So, it's a for-loop that goes from 8
to 1
(remember, it doesn't go down to 0
). i
takes on the new value for each iteration, first 8
, then 7
, etc.
在Python中,您可以乘以"字符串,就像这样:
In Python, you can "multiply" strings, like so:
>>> pattern = "BVD"
>>> pattern * 1
'BVD'
>>> pattern * 2
'BVDBVD'
>>> pattern * 3
'BVDBVDBVD'
>>>
这篇关于如何找到最大在Python中一个字符序列连续重复多少次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!