Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Search for sum of pairs in given array
""" Given an array A[] of n numbers and another number x, determines whether or not there exist two elements in S whose sum is exactly x. Time Complexity: O(n) time if range of numbers is known. Author: Jayesh Chandrapal """ import unittest def search(nums, x): map = [0] * ( max(nums) + 1 ) for i in range(len(nums)): temp = x - nums[i] if temp > 0 and map[temp] == 1: # print("Pair with given sum is: " + str(temp) + " and " + str(nums[i])) return 1 map[nums[i]] = 1 return 0 class Tests(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test1(self): self.assertEqual(1, search([1, 4, 45, 6, 10, -8], 16)) def test2(self): self.assertEqual(0, search([1, 4, 45, 6, 10, -8], 18)) if __name__ == "__main__": unittest.main()
run
|
edit
|
history
|
help
0
Venture
P
Ugly number
replace
denemeler
Lesso#6 updated
string length
lesson3 part3
Python virables
PyAbs