diff --git a/two_num.py b/two_num.py index 5780845217f..02c431788ac 100644 --- a/two_num.py +++ b/two_num.py @@ -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]