MCPcopy Create free account
hub / github.com/geekcomputers/Python / two_sum

Function two_sum

two_num.py:20–47  ·  view source on GitHub ↗

Finds indices of two numbers in 'nums' that add up to 'target'. Args: nums (List[int]): List of integers. target (int): Target sum. Returns: Optional[List[int]]: Indices of the two numbers that add up to the target, or None if no su

(nums: List[int], target: int)

Source from the content-addressed store, hash-verified

18
19
20def two_sum(nums: List[int], target: int) -> Optional[List[int]]:
21 """
22 Finds indices of two numbers in 'nums' that add up to 'target'.
23
24 Args:
25 nums (List[int]): List of integers.
26 target (int): Target sum.
27
28 Returns:
29 Optional[List[int]]: Indices of the two numbers that add up to the target,
30 or None if no such pair is found.
31 """
32 if len(nums) < 2:
33 raise ValueError("Input list must contain at least two numbers.")
34
35 if not all(isinstance(num, int) for num in nums):
36 raise TypeError("All elements in the list must be integers.")
37
38 # Dictionary to track seen values and their indices
39 seen_values = {}
40
41 for index, value in enumerate(nums):
42 complement = target - value
43 if complement in seen_values:
44 return [seen_values[complement], index]
45 seen_values[value] = index
46
47 return None
48
49
50# Example usage

Callers 1

two_num.pyFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected