Skip to content

Instantly share code, notes, and snippets.

@flaviocdc
Created February 23, 2014 01:48
Show Gist options
  • Save flaviocdc/9165487 to your computer and use it in GitHub Desktop.
Save flaviocdc/9165487 to your computer and use it in GitHub Desktop.
TalentBuddy.co Tuple Sum using DFS
def tuple_sum(a, s):
ret = backtrack(a, s, 0, 1, 2, 3)
print ' '.join(str(i) for i in ret)
def backtrack(a, s, x, y, w, z):
result = a[x] + a[y] + a[w] + a[z]
conj = set([x, y, w, z])
if result == s and len(conj) == 4:
return (x, y, w, z)
aux = None
if (z + 1) < len(a):
aux = backtrack(a, s, x, y, w, z + 1)
if not aux is None:
return aux
if (w + 1) < len(a):
aux = backtrack(a, s, x, y, w + 1, z)
if not aux is None:
return aux
if (y + 1) < len(a):
aux = backtrack(a, s, x, y + 1, w, z)
if not aux is None:
return aux
if (x + 1) < len(a):
aux = backtrack(a, s, x + 1, y, w, z)
if not aux is None:
return aux
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment