Skip to content

Instantly share code, notes, and snippets.

@sarahbkim
Created November 10, 2018 08:23
Show Gist options
  • Save sarahbkim/c4ee94b560351f985331fd2f81dea60e to your computer and use it in GitHub Desktop.
Save sarahbkim/c4ee94b560351f985331fd2f81dea60e to your computer and use it in GitHub Desktop.
scratch paper
import unittest
def has_pair_with_sum(a_list, target):
if len(a_list) < 2:
return False
i, j = 0, len(a_list) - 1
while i < j:
min_value = a_list[i]
max_value = a_list[j]
tmp_sum = min_value + max_value
if tmp_sum == target:
return True
elif tmp_sum < target:
i += 1
else: # tmp_sum > target:
j -= 1
return False
class FindTargetSum(unittest.TestCase):
def test(self):
l1 = [1, 3, 5, 8, 12, 13, 22]
self.assertEqual(has_pair_with_sum(l1, 16), True)
self.assertEqual(has_pair_with_sum(l1, 19), False)
def test_another(self):
l2 = [1, 3, 5]
self.assertEqual(has_pair_with_sum(l2, 6), True)
self.assertEqual(has_pair_with_sum(l2, 2), False)
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment