Skip to content

Commit 5f9be0a

Browse files
spamegg1cclauss
andauthored
Add Python type hints and doctests to other/two_sum.py (TheAlgorithms#2467)
* Add Python type hints and doctests to other/two_sum.py TheAlgorithms#2465 * Update other/two_sum.py Co-authored-by: Christian Clauss <[email protected]> * Update other/two_sum.py Co-authored-by: Christian Clauss <[email protected]> * Update two_sum.py Co-authored-by: Christian Clauss <[email protected]>
1 parent 9200a2e commit 5f9be0a

File tree

1 file changed

+26
-10
lines changed

1 file changed

+26
-10
lines changed

other/two_sum.py

+26-10
Original file line numberDiff line numberDiff line change
@@ -11,21 +11,37 @@
1111
Because nums[0] + nums[1] = 2 + 7 = 9,
1212
return [0, 1].
1313
"""
14+
from __future__ import annotations
1415

1516

16-
def twoSum(nums, target):
17+
def two_sum(nums: list[int], target: int) -> list[int]:
1718
"""
18-
:type nums: List[int]
19-
:type target: int
20-
:rtype: List[int]
19+
>>> two_sum([2, 7, 11, 15], 9)
20+
[0, 1]
21+
>>> two_sum([15, 2, 11, 7], 13)
22+
[1, 2]
23+
>>> two_sum([2, 7, 11, 15], 17)
24+
[0, 3]
25+
>>> two_sum([7, 15, 11, 2], 18)
26+
[0, 2]
27+
>>> two_sum([2, 7, 11, 15], 26)
28+
[2, 3]
29+
>>> two_sum([2, 7, 11, 15], 8)
30+
[]
31+
>>> two_sum([3 * i for i in range(10)], 19)
32+
[]
2133
"""
2234
chk_map = {}
2335
for index, val in enumerate(nums):
2436
compl = target - val
2537
if compl in chk_map:
26-
indices = [chk_map[compl], index]
27-
print(indices)
28-
return [indices]
29-
else:
30-
chk_map[val] = index
31-
return False
38+
return [chk_map[compl], index]
39+
chk_map[val] = index
40+
return []
41+
42+
43+
if __name__ == "__main__":
44+
import doctest
45+
46+
doctest.testmod()
47+
print(f"{two_sum([2, 7, 11, 15], 9) = }")

0 commit comments

Comments
 (0)