[英]finding the most amount of times a substring appears successively in a string
我有一長串字符,我不僅試圖找出這些字符的 substring 是否存在於較大的字符串中,我還試圖找到最長的連續實例。
例如......在下面的代碼片段中,我發現我可以使用“count”來查看 ZE83AED3DDF4667DEC0DAAAACB2BB3BE0BZ b 在 a 中出現的次數。 結果是 5。但是,我要確定的是最長的連續運行,即 3(其中“abc”在中間背靠背出現)。 我很難理解這個邏輯。 任何意見,將不勝感激。
a = "abcxyzabcabcabcxyzabcxyz"
b = "abc"
total = a.count(b)
print(total)
使用 while 循環應該相當簡單:
def func(a, b):
n = 1
while b*n in a:
n += 1
return n - 1
一種可能且幼稚的解決方案是使用 python index
function 來識別 substring 的最接近索引。 從那里您可以簡單地繼續向前搜索 substring 直到找到不再出現的點,然后再次調用index
向前跳過。
例子:
a = "abcxyzabcabcabcxyzabcxyz"
b = "abc"
curr_index = a.index(b)
longest_count = 0
current_count = 0
while curr_index < len(a):
if a[curr_index : curr_index + len(b)] == b:
curr_index += len(b)
current_count += 1
else:
if longest_count < current_count:
longest_count = current_count
try:
curr_index = a.index(b, curr_index)
except ValueError:
# Substring no longer found in string slice
break
current_count = 0
if longest_count < current_count:
longest_count = current_count
print(longest_count)
這只會返回最長的重復計數,但不會返回它開始的位置。 但是,添加該功能是微不足道的。
使用適當的索引繼續調用b
上的a.index
。 如果索引是您的子集的開始,那么您在同一次運行中。 否則,開始新的運行:
def longest_run(string, pattern):
longest = 0
current = 0
start = 0
while True:
try:
ind = string.index(pattern, start)
if ind == start:
current += 1
else:
if current > longest:
longest = current
current = 1
start += len(pattern)
except ValueError:
return longest
您可以將re.findall
與匹配一次或多次b
的模式一起使用(使用re.escape
以防止b
被解釋為正則表達式),然后 map 將返回的字符串傳遞給len
並將它們傳遞給max
以獲得最長匹配,然后將該長度除以b
的長度,得到b
重復的次數:
import re
max(map(len, re.findall('(?:%s)+' % re.escape(b), a))) // len(b)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.