-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaddtozero.py
More file actions
43 lines (31 loc) · 917 Bytes
/
addtozero.py
File metadata and controls
43 lines (31 loc) · 917 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
"""Given list of ints, return True if any two nums in list sum to 0.
>>> add_to_zero([])
False
>>> add_to_zero([1])
False
>>> add_to_zero([1, 2, 3])
False
>>> add_to_zero([1, 2, 3, -2])
True
Given the wording of our problem, a zero in the list will always
make this true, since "any two numbers" could include that same
zero for both numbers, and they sum to zero:
>>> add_to_zero([0, 1, 2])
True
"""
def add_to_zero(nums):
"""Given list of ints, return True if any two nums sum to 0."""
opposites = set([])
for num in nums:
if num == 0:
return True
else:
opposites.add(-num)
for num in nums:
if num in opposites:
return True
return False
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print "\n*** ALL TESTS PASSED. NOTHING ESCAPES YOU!\n"