Skip to content
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

Created TwoSum.py #7945

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
13 changes: 13 additions & 0 deletions TwoSum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
def two_sum(nums, target):
num_dict = {}
for i, num in enumerate(nums):
complement = target - num
if complement in num_dict:
return [num_dict[complement], i]
num_dict[num] = i
return None

nums = [2, 7, 11, 15]
target = 9
result = two_sum(nums, target)
print(result)
24 changes: 24 additions & 0 deletions twosum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
def two_sum(nums, target):
num_dict = {}
for i, num in enumerate(nums):
complement = target - num
if complement in num_dict:
return [num_dict[complement], i]
num_dict[num] = i
return None

if __name__ == "__main__":
nums = [2, 7, 11, 15]
target = 9
result = two_sum(nums, target)
print(result)

def test_two_sum():
assert two_sum([2, 7, 11, 15], 9) == [0, 1]
assert two_sum([1, 2, 3, 4, 5], 9) == [3, 4]
assert two_sum([3, 2, 4], 6) == [1, 2]
assert two_sum([3, 3], 6) == [0, 1]
assert two_sum([], 5) is None
print("All tests passed.")

test_two_sum()
Loading