Skip to content

bpo-41972: Use the "Two-Way" algorithm when searching for long substrings #22679

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 21 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions Lib/test/string_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import unittest, string, sys, struct
from test import support
from collections import UserList
import random

class Sequence:
def __init__(self, seq='wxyz'): self.seq = seq
Expand Down Expand Up @@ -317,6 +318,45 @@ def test_rindex(self):
else:
self.checkraises(TypeError, 'hello', 'rindex', 42)

def test_find_periodic_pattern(self):
"""Cover the special path for periodic patterns."""
def reference_find(p, s):
m = len(p)
for i in range(len(s)):
if s[i:i+m] == p:
return i
return -1

rr = random.randrange
choices = random.choices
for _ in range(1000):
p0 = ''.join(choices('abcde', k=rr(10))) * rr(10, 20)
p = p0[:len(p0) - rr(10)] # pop off some characters
left = ''.join(choices('abcdef', k=rr(200)))
right = ''.join(choices('abcdef', k=rr(200)))
text = left + p + right
with self.subTest(p=p, text=text):
self.checkequal(reference_find(p, text),
text, 'find', p)

def test_find_shift_table_overflow(self):
"""When the table of 16-bit shifts overflows."""
N = 2**16 + 100 # Overflow the 16-bit shift table

# first check the periodic case
# here, the shift for 'b' is N.
pattern1 = 'a' * N + 'b' + 'a' * N
text1 = 'babbaa' * N + pattern1
self.checkequal(len(text1)-len(pattern1),
text1, 'find', pattern1)

# now check the non-periodic case
# here, the shift for 'd' is 3*(N+1)
pattern2 = 'ddd' + 'abc' * N + "eee"
text2 = pattern2[:-1] + "ddeede" * 2 * N + pattern2 + "de" * N
self.checkequal(len(text2) - N*len("de") - len(pattern2),
text2, 'find', pattern2)

def test_lower(self):
self.checkequal('hello', 'HeLLo', 'lower')
self.checkequal('hello', 'hello', 'lower')
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Substring search functions such as ``str1 in str2`` and ``str2.find(str1)`` now use the "Two-Way" string comparison algorithm whenever ``str1`` is long enough, to avoid quadratic behavior in the worst cases.
Loading