Created
April 30, 2017 02:52
-
-
Save rupalbarman/e9e48700b0d8c93d719c0ef2b07cc3ba to your computer and use it in GitHub Desktop.
Three sum problem in python. Find three numbers from an array whose sum is x
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
| ''' | |
| three sum, to find a+b+c== x in an array | |
| ''' | |
| a= [-1,0,1,2,-1,-4] #the array/ list | |
| x= 0 #the sum we need | |
| s= set() | |
| res= [] #holds groups of 3 numbers satisfying the condition | |
| for i in range(len(a)-1): | |
| ax= a[i] | |
| l, r= i+1, len(a)-1 | |
| while l < r: | |
| if x -(ax+ a[l]) in s: | |
| res.append([ax, a[l], x -(ax+ a[l])]) | |
| else: | |
| s.add(ax+ a[l]) | |
| l+=1 | |
| s.clear() | |
| print(res) #[[-1, 2, -1], [0, -1, 1]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment