Inserts the index into the sorted array at the correct position. >>> NumberContainer().binary_search_insert([1,2,3], 2) [1, 2, 2, 3] >>> NumberContainer().binary_search_insert([0,1,3], 2) [0, 1, 2, 3] >>> NumberContainer().binary_search_inser
(self, array: list | str | range, index: int)
| 75 | ) |
| 76 | |
| 77 | def binary_search_insert(self, array: list | str | range, index: int) -> list[int]: |
| 78 | """ |
| 79 | Inserts the index into the sorted array |
| 80 | at the correct position. |
| 81 | |
| 82 | >>> NumberContainer().binary_search_insert([1,2,3], 2) |
| 83 | [1, 2, 2, 3] |
| 84 | >>> NumberContainer().binary_search_insert([0,1,3], 2) |
| 85 | [0, 1, 2, 3] |
| 86 | >>> NumberContainer().binary_search_insert([-5, -3, 0, 0, 11, 103], 51) |
| 87 | [-5, -3, 0, 0, 11, 51, 103] |
| 88 | >>> NumberContainer().binary_search_insert([-5, -3, 0, 0, 11, 100, 103], 101) |
| 89 | [-5, -3, 0, 0, 11, 100, 101, 103] |
| 90 | >>> NumberContainer().binary_search_insert(range(10), 4) |
| 91 | [0, 1, 2, 3, 4, 4, 5, 6, 7, 8, 9] |
| 92 | >>> NumberContainer().binary_search_insert("abd", "c") |
| 93 | ['a', 'b', 'c', 'd'] |
| 94 | >>> NumberContainer().binary_search_insert(131, 23) |
| 95 | Traceback (most recent call last): |
| 96 | ... |
| 97 | TypeError: binary_search_insert() only accepts either a list, range or str |
| 98 | """ |
| 99 | if isinstance(array, (range, str)): |
| 100 | array = list(array) |
| 101 | elif not isinstance(array, list): |
| 102 | raise TypeError( |
| 103 | "binary_search_insert() only accepts either a list, range or str" |
| 104 | ) |
| 105 | |
| 106 | low = 0 |
| 107 | high = len(array) - 1 |
| 108 | |
| 109 | while low <= high: |
| 110 | mid = (low + high) // 2 |
| 111 | if array[mid] == index: |
| 112 | # If the item already exists in the array, |
| 113 | # insert it after the existing item |
| 114 | array.insert(mid + 1, index) |
| 115 | return array |
| 116 | elif array[mid] < index: |
| 117 | low = mid + 1 |
| 118 | else: |
| 119 | high = mid - 1 |
| 120 | |
| 121 | # If the item doesn't exist in the array, insert it at the appropriate position |
| 122 | array.insert(low, index) |
| 123 | return array |
| 124 | |
| 125 | def change(self, index: int, number: int) -> None: |
| 126 | """ |