Last active
June 20, 2016 22:16
-
-
Save svalleru/7b36521fbbf19c6fe80ea7703832fc64 to your computer and use it in GitHub Desktop.
find if the sum of any two numbers in a list equates to a given number
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class TwoSum(object): | |
| """ | |
| find if the sum of any two numbers in a list equates | |
| to a given number | |
| """ | |
| def __init__(self): | |
| self.nums = [] | |
| self.sum = 0 | |
| def add_num(self, num): | |
| self.nums.append(num) | |
| self.sum += num | |
| def find_sum(self, sum): | |
| if self.sum - sum in self.nums: | |
| return True | |
| else: | |
| return False | |
| ts = TwoSum() | |
| ts.add_num(1) | |
| ts.add_num(-1) | |
| ts.add_num(2) | |
| ts.add_num(-2) | |
| ts.add_num(3) | |
| print ts.find_sum(-1) | |
| print ts.find_sum(1) | |
| print ts.find_sum(6) | |
| print ts.find_sum(0) | |
| # False | |
| # True | |
| # False | |
| # True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment