Skip to content

Instantly share code, notes, and snippets.

@abarax
Created June 3, 2013 12:36
Show Gist options
  • Save abarax/5697831 to your computer and use it in GitHub Desktop.
Save abarax/5697831 to your computer and use it in GitHub Desktop.
Based off the backtracking algorithm in 'The Algorithm Design Manual' but written in python.
__author__ = 'cody'
finished = False # found all solutions yet?
def backtrack(a, k):
if is_a_solution(a, k):
return process_solution(a)
else:
candidates = construct_candidates(a, k)
# print(candidates)
for candidate in candidates:
# make_move(a,k,data_input)
backtrack(a + [candidate], k)
# unmake_move(a,k,data_input)
if finished:
return # terminate early
def construct_candidates(a, k):
return [candidate for candidate in k if candidate not in a ]
def process_solution(a):
print("permutation", a)
def is_a_solution(a, k):
return len(a) == 3
def generate_permutations():
backtrack([],['red', 'green', 'blue'])
generate_permutations()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment