Skip to content

Update two_num.py #2575

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 27 additions & 18 deletions two_num.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,35 @@
"""Author Anurag Kumar (mailto:anuragkumarak95@gmail.com)
"""
Author: Anurag Kumar (mailto:anuragkumarak95@gmail.com)

Given an array of integers, return indices of the two numbers
such that they add up to a specific target.
You may assume that each input would have exactly one solution,
and you may not use the same element twice.
This script defines a function that finds two indices in an array
such that their corresponding values add up to a given target.

Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
>>> two_sum([2, 7, 11, 15], 9)
[0, 1]

"""
Args:
nums (list): List of integers.
target (int): Target sum.

Returns:
list: Indices of the two numbers that add up to `target`.
False: If no such pair is found.
"""

def twoSum(nums, target):
def two_sum(nums, target):
"""Finds two numbers that add up to a given target."""
chk_map = {}
for index, val in enumerate(nums):
compl = target - val
if compl in chk_map:
indices = [chk_map[compl], index]
print(indices)
return [indices]
else:
chk_map[val] = index
return False
complement = target - val
if complement in chk_map:
return [chk_map[complement], index]
chk_map[val] = index
return False # Clearer than returning `None`

# Example usage
if __name__ == "__main__":
numbers = [2, 7, 11, 15]
target_value = 9
result = two_sum(numbers, target_value)
print(result) # Expected output: [0, 1]
Loading