Created
August 23, 2023 15:35
-
-
Save aminrasouli/55f514abd102d4b9f12d6dd3f483e475 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def binary_search_all(li, target, left, right): | |
| result = [] | |
| while left <= right: | |
| mid = left + (right - left) // 2 | |
| if li[mid][0] == target: | |
| result.append(li[mid][1]) | |
| i = mid - 1 | |
| while i >= left and li[i][0] == target: | |
| result.append(li[i][1]) | |
| i -= 1 | |
| i = mid + 1 | |
| while i <= right and li[i][0] == target: | |
| result.append(li[i][1]) | |
| i += 1 | |
| return result | |
| elif li[mid][0] < target: | |
| left = mid + 1 | |
| else: | |
| right = mid - 1 | |
| return result | |
| def find_pairs(li, k): | |
| arr_enumerated = [(num, index) for index, num in enumerate(li)] | |
| arr_enumerated.sort() | |
| pairs = [] | |
| for num, index in arr_enumerated: | |
| diff = k - num | |
| diff_index_all = binary_search_all(arr_enumerated, diff, 0, len(li) - 1) | |
| for diff_index in diff_index_all: | |
| if index > diff_index: | |
| pairs.append((num, diff, index, diff_index)) | |
| return pairs | |
| def print_pairs(pairs): | |
| print("{") | |
| for num1, num2, index1, index2 in pairs: | |
| print(f"Numbers: {num1}, {num2} => Indexes: {index1}, {index2}") | |
| print("}") | |
| print_pairs(find_pairs([1, 1, 2, 2], 3)) | |
| print_pairs(find_pairs([3, 5, 2, -4, 8, 11], 7)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment