Skip to content

Instantly share code, notes, and snippets.

@rupalbarman
Created March 26, 2017 15:05
Show Gist options
  • Save rupalbarman/eac73e3431ca518967d3f2719478dac9 to your computer and use it in GitHub Desktop.
Save rupalbarman/eac73e3431ca518967d3f2719478dac9 to your computer and use it in GitHub Desktop.
get subsets of two elements from a list/ array whose sum is given
def get_pair_with_sum(a, need):
s= set()
for i in a:
if (need- i) in s:
print(need-i, i)
else:
s.add(i)
a=[4,2,4,2]
b=[3,6,2,5]
need= 8
# find subset with sum = 8
get_pair_with_sum(a, need) #prints [4,4]
print()
get_pair_with_sum(b, need) #prints [6,2], [3,5]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment