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

Function two_sum

maths/two_sum.py:18–41  ·  view source on GitHub ↗

>>> two_sum([2, 7, 11, 15], 9) [0, 1] >>> two_sum([15, 2, 11, 7], 13) [1, 2] >>> two_sum([2, 7, 11, 15], 17) [0, 3] >>> two_sum([7, 15, 11, 2], 18) [0, 2] >>> two_sum([2, 7, 11, 15], 26) [2, 3] >>> two_sum([2, 7, 11, 15], 8) [] >>> two_sum([3 * i

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

Source from the content-addressed store, hash-verified

16
17
18def two_sum(nums: list[int], target: int) -> list[int]:
19 """
20 >>> two_sum([2, 7, 11, 15], 9)
21 [0, 1]
22 >>> two_sum([15, 2, 11, 7], 13)
23 [1, 2]
24 >>> two_sum([2, 7, 11, 15], 17)
25 [0, 3]
26 >>> two_sum([7, 15, 11, 2], 18)
27 [0, 2]
28 >>> two_sum([2, 7, 11, 15], 26)
29 [2, 3]
30 >>> two_sum([2, 7, 11, 15], 8)
31 []
32 >>> two_sum([3 * i for i in range(10)], 19)
33 []
34 """
35 chk_map: dict[int, int] = {}
36 for index, val in enumerate(nums):
37 compl = target - val
38 if compl in chk_map:
39 return [chk_map[compl], index]
40 chk_map[val] = index
41 return []
42
43
44if __name__ == "__main__":

Callers 1

two_sum.pyFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected