|
1 |
| -"""Author Anurag Kumar (mailto:[email protected]) |
| 1 | +""" |
| 2 | +Author: Anurag Kumar (mailto:[email protected]) |
2 | 3 |
|
3 |
| -Given an array of integers, return indices of the two numbers |
4 |
| -such that they add up to a specific target. |
5 |
| -You may assume that each input would have exactly one solution, |
6 |
| -and you may not use the same element twice. |
| 4 | +This script defines a function that finds two indices in an array |
| 5 | +such that their corresponding values add up to a given target. |
7 | 6 |
|
8 | 7 | Example:
|
9 |
| -Given nums = [2, 7, 11, 15], target = 9, |
10 |
| -Because nums[0] + nums[1] = 2 + 7 = 9, |
11 |
| -return [0, 1]. |
| 8 | + >>> two_sum([2, 7, 11, 15], 9) |
| 9 | + [0, 1] |
12 | 10 |
|
13 |
| -""" |
| 11 | +Args: |
| 12 | + nums (list): List of integers. |
| 13 | + target (int): Target sum. |
14 | 14 |
|
| 15 | +Returns: |
| 16 | + list: Indices of the two numbers that add up to `target`. |
| 17 | + False: If no such pair is found. |
| 18 | +""" |
15 | 19 |
|
16 |
| -def twoSum(nums, target): |
| 20 | +def two_sum(nums, target): |
| 21 | + """Finds two numbers that add up to a given target.""" |
17 | 22 | chk_map = {}
|
18 | 23 | for index, val in enumerate(nums):
|
19 |
| - compl = target - val |
20 |
| - if compl in chk_map: |
21 |
| - indices = [chk_map[compl], index] |
22 |
| - print(indices) |
23 |
| - return [indices] |
24 |
| - else: |
25 |
| - chk_map[val] = index |
26 |
| - return False |
| 24 | + complement = target - val |
| 25 | + if complement in chk_map: |
| 26 | + return [chk_map[complement], index] |
| 27 | + chk_map[val] = index |
| 28 | + return False # Clearer than returning `None` |
| 29 | + |
| 30 | +# Example usage |
| 31 | +if __name__ == "__main__": |
| 32 | + numbers = [2, 7, 11, 15] |
| 33 | + target_value = 9 |
| 34 | + result = two_sum(numbers, target_value) |
| 35 | + print(result) # Expected output: [0, 1] |
0 commit comments