Created
August 3, 2015 12:17
-
-
Save ramalho/54685fdf51eafb5c032c to your computer and use it in GitHub Desktop.
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
| def backtracking_sort(input_list, output_list, level): | |
| print(level * ' ', input_list, output_list); | |
| # Reject - this path doesn't lead to any solution | |
| if len(output_list) > 1 and output_list[-2] > output_list[-1]: | |
| return False | |
| # Accept - one solution | |
| if not input_list: | |
| print("Solution: ", output_list) | |
| return True | |
| # Step - go over all the possible options in the input | |
| for n in input_list: | |
| clone_input_list = input_list[:] | |
| clone_input_list.remove(n) | |
| clone_output_list = output_list[:] | |
| clone_output_list.append(n) | |
| test = backtracking_sort(clone_input_list, | |
| clone_output_list, level + 1) | |
| if test: | |
| return True | |
| # No solution | |
| return False | |
| if __name__ == '__main__': | |
| input_list = [4, 1, 3] | |
| output_list = [] | |
| # First call | |
| backtracking_sort(input_list, output_list, 0); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment