diff --git a/searches/binary_search.py b/searches/binary_search.py index bec87b3c5aec..6907eda477b8 100644 --- a/searches/binary_search.py +++ b/searches/binary_search.py @@ -196,22 +196,28 @@ def binary_search(sorted_collection: list[int], item: int) -> int: 1 >>> binary_search([0, 5, 7, 10, 15], 6) -1 + >>> binary_search([1, 2, 2, 2, 3], 2) + 1 + >>> binary_search([1, 1, 1, 2, 3], 1) + 0 """ if any(a > b for a, b in pairwise(sorted_collection)): raise ValueError("sorted_collection must be sorted in ascending order") left = 0 right = len(sorted_collection) - 1 + result = -1 while left <= right: midpoint = left + (right - left) // 2 current_item = sorted_collection[midpoint] if current_item == item: - return midpoint + result = midpoint + right = midpoint - 1 elif item < current_item: right = midpoint - 1 else: left = midpoint + 1 - return -1 + return result def binary_search_std_lib(sorted_collection: list[int], item: int) -> int: diff --git a/strings/split.py b/strings/split.py index ed194ec69c2f..60b6a88ac700 100644 --- a/strings/split.py +++ b/strings/split.py @@ -17,17 +17,31 @@ def split(string: str, separator: str = " ") -> list: >>> split(";abbb;;c;", separator=';') ['', 'abbb', '', 'c', ''] + + >>> split("a--b--c", separator="--") + ['a', 'b', 'c'] + + >>> split("apple##banana##cherry", separator="##") + ['apple', 'banana', 'cherry'] """ split_words = [] + separator_length = len(separator) + + if separator_length == 0: + return [string] last_index = 0 - for index, char in enumerate(string): - if char == separator: + index = 0 + while index < len(string): + if string[index : index + separator_length] == separator: split_words.append(string[last_index:index]) - last_index = index + 1 - if index + 1 == len(string): - split_words.append(string[last_index : index + 1]) + last_index = index + separator_length + index += separator_length + else: + index += 1 + + split_words.append(string[last_index:]) return split_words