From 502b64454be8c6b23f493c52e5952fb3f762e1f9 Mon Sep 17 00:00:00 2001 From: Nathan Bergey Date: Tue, 13 Sep 2022 22:08:32 -0400 Subject: [PATCH] Bm: Check edge conditions like empty strings for the search text --- src/bm.py | 4 +++- test/test_bm.py | 4 ++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/bm.py b/src/bm.py index 05e2265..d608e6b 100644 --- a/src/bm.py +++ b/src/bm.py @@ -58,12 +58,14 @@ class Bm(object): Return the index of the *first* occurrence of the pattern in the text, or '-1' if the pattern is not in the text. """ + PATTERN_LENGTH = len(self.pattern) + if not self.pattern or not self.text or len(self.text) < PATTERN_LENGTH: + return -1 # The search works on one character at a time in the text. The current # location is the "head" (like a read-head on a disk) # It starts at the last character in the pattern, and gets moved in the # loop until we reach the end of the text - PATTERN_LENGTH = len(self.pattern) head = PATTERN_LENGTH - 1 while head < len(self.text): # When the last character of the pattern matches the current head diff --git a/test/test_bm.py b/test/test_bm.py index 5e04992..29d1b3c 100644 --- a/test/test_bm.py +++ b/test/test_bm.py @@ -14,6 +14,10 @@ from src.bm import Bm # Other useful test cases: ("ユニコード", "コード", 2), + ("", "", -1), + ("a", "", -1), + ("", "a", -1), + ("t", "too long", -1), ]) def test_bm(text, pattern, expected): bm = Bm(text, pattern)