From 88644d9fc912be5f31e16804c2f8e6a5c5d57e3e Mon Sep 17 00:00:00 2001 From: hetzz Date: Thu, 4 Jul 2019 02:19:04 +0530 Subject: [PATCH 1/5] Adding nqueens.py for backtracking --- backtracking/nqueens.py | 87 ++++++++++++++++++++++++++++++++++ backtracking/sum_of_subsets.py | 24 ++++++++++ 2 files changed, 111 insertions(+) create mode 100644 backtracking/nqueens.py create mode 100644 backtracking/sum_of_subsets.py diff --git a/backtracking/nqueens.py b/backtracking/nqueens.py new file mode 100644 index 000000000000..945303eb4df2 --- /dev/null +++ b/backtracking/nqueens.py @@ -0,0 +1,87 @@ +''' + + The nqueens problem is of placing N queens on a N * N + chess board such that no queen can attack any other queen placed + on that chess board. + This means that one queen cannot have any other queen on its horizontal, vertical and + diagonal lines. + +''' +solution = [] + +def isSafe(board, row, column): + ''' + This function returns a boolean value True if it is safe to place a queen there considering + the current state of the board. + + Parameters : + board(2D matrix) : board + row ,column : coordinates of the cell on a board + + Returns : + Boolean Value + + ''' + for i in range(len(board)): + if board[row][i] == 1: + return False + for i in range(len(board)): + if board[i][column] == 1: + return False + for i,j in zip(range(row,-1,-1),range(column,-1,-1)): + if board[i][j] == 1: + return False + for i,j in zip(range(row,-1,-1),range(column,len(board))): + if board[i][j] == 1: + return False + return True + +def solve(board, row): + ''' + It creates a state space tree and calls the safe function untill it receives a + False Boolean and terminates that brach and backtracks to the next + poosible solution branch. + + ''' + if row >= len(board): + ''' + If the row number exceeds N we have board with a successful combination + and that combination is appended to the solution list and the board is printed. + + ''' + solution.append(board) + printboard(board) + print() + return + for i in range(len(board)): + ''' + For every row it iterates through each column to check if it is feesible to place a + queen there. + If all the combinations for that particaular branch are successfull the board is + reinitialized for the next possible combination. + + ''' + if isSafe(board,row,i): + board[row][i] = 1 + solve(board,row+1) + board[row][i] = 0 + return False + +def printboard(board): + ''' + Prints the boards that have a successfull combination. + + ''' + for i in range(len(board)): + for j in range(len(board)): + if board[i][j] == 1: + print("Q", end = " ") + else : + print(".", end = " ") + print() + +#n=int(input("The no. of queens")) +n = 8 +board = [[0 for i in range(n)]for j in range(n)] +solve(board, 0) +print("The total no. of solutions are :", len(solution)) \ No newline at end of file diff --git a/backtracking/sum_of_subsets.py b/backtracking/sum_of_subsets.py new file mode 100644 index 000000000000..bf29182861e4 --- /dev/null +++ b/backtracking/sum_of_subsets.py @@ -0,0 +1,24 @@ +def generate_sum_of_subsets_soln(nums, max_sum): + result = [] + path = [] + num_index = 0 + remaining_nums_sum = sum(nums) + create_state_space_tree(nums, max_sum, num_index, path,result, remaining_nums_sum) + return result + +def create_state_space_tree(nums,max_sum,num_index,path,result, remaining_nums_sum): + if sum(path) > max_sum or (remaining_nums_sum + sum(path)) < max_sum: + return + if sum(path) == max_sum: + result.append(path) + return + for num_index in range(num_index,len(nums)): + create_state_space_tree(nums, max_sum, num_index + 1, path + [nums[num_index]], result, remaining_nums_sum - nums[num_index]) + +print("Enter the elements") +nums = list(map(int, input().split())) +print("Enter max_sum sum") +max_sum = int(input()) + +result = generate_sum_of_subsets_soln(nums,max_sum) +print(result) \ No newline at end of file From fc3cee3e3b6bc52f8cbd59b222b934ae05b90aa2 Mon Sep 17 00:00:00 2001 From: hetzz Date: Thu, 4 Jul 2019 02:31:48 +0530 Subject: [PATCH 2/5] Adding sum_of_subsets.py for backtracking --- backtracking/sum_of_subsets.py | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/backtracking/sum_of_subsets.py b/backtracking/sum_of_subsets.py index bf29182861e4..b01bffbb651d 100644 --- a/backtracking/sum_of_subsets.py +++ b/backtracking/sum_of_subsets.py @@ -1,3 +1,11 @@ +''' + The sum-of-subsetsproblem states that a set of non-negative integers, and a value M, + determine all possible subsets of the given set whose summation sum equal to given M. + + Summation of the chosen numbers must be equal to given number M and one number can + be used only once. +''' + def generate_sum_of_subsets_soln(nums, max_sum): result = [] path = [] @@ -7,6 +15,13 @@ def generate_sum_of_subsets_soln(nums, max_sum): return result def create_state_space_tree(nums,max_sum,num_index,path,result, remaining_nums_sum): + ''' + Creates a state space tree to iterate through each branch using DFS. + It terminates the branching of a node when any of the two conditions + given below satisfy. + This algorithm follows depth-fist-search and backtracks when the node is not branchable. + + ''' if sum(path) > max_sum or (remaining_nums_sum + sum(path)) < max_sum: return if sum(path) == max_sum: @@ -15,10 +30,16 @@ def create_state_space_tree(nums,max_sum,num_index,path,result, remaining_nums_s for num_index in range(num_index,len(nums)): create_state_space_tree(nums, max_sum, num_index + 1, path + [nums[num_index]], result, remaining_nums_sum - nums[num_index]) +''' +remove the comment to take an input from the user + print("Enter the elements") nums = list(map(int, input().split())) print("Enter max_sum sum") max_sum = int(input()) +''' +nums = [3, 34, 4, 12, 5, 2] +max_sum = 9 result = generate_sum_of_subsets_soln(nums,max_sum) -print(result) \ No newline at end of file +print(*result) \ No newline at end of file From ba20ec56ce3641217a45bc73dda385a5533ae595 Mon Sep 17 00:00:00 2001 From: John Law Date: Thu, 4 Jul 2019 23:11:17 +0800 Subject: [PATCH 3/5] Update nqueens.py --- backtracking/nqueens.py | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/backtracking/nqueens.py b/backtracking/nqueens.py index 945303eb4df2..dfd4498b166b 100644 --- a/backtracking/nqueens.py +++ b/backtracking/nqueens.py @@ -1,7 +1,7 @@ ''' The nqueens problem is of placing N queens on a N * N - chess board such that no queen can attack any other queen placed + chess board such that no queen can attack any other queens placed on that chess board. This means that one queen cannot have any other queen on its horizontal, vertical and diagonal lines. @@ -41,7 +41,6 @@ def solve(board, row): It creates a state space tree and calls the safe function untill it receives a False Boolean and terminates that brach and backtracks to the next poosible solution branch. - ''' if row >= len(board): ''' @@ -59,7 +58,6 @@ def solve(board, row): queen there. If all the combinations for that particaular branch are successfull the board is reinitialized for the next possible combination. - ''' if isSafe(board,row,i): board[row][i] = 1 @@ -70,7 +68,6 @@ def solve(board, row): def printboard(board): ''' Prints the boards that have a successfull combination. - ''' for i in range(len(board)): for j in range(len(board)): @@ -84,4 +81,4 @@ def printboard(board): n = 8 board = [[0 for i in range(n)]for j in range(n)] solve(board, 0) -print("The total no. of solutions are :", len(solution)) \ No newline at end of file +print("The total no. of solutions are :", len(solution)) From f6169499f7770f3ca2ca87c9ef66c246c1fc0baa Mon Sep 17 00:00:00 2001 From: Anup Kumar Panwar <1anuppanwar@gmail.com> Date: Fri, 5 Jul 2019 13:52:02 +0530 Subject: [PATCH 4/5] Rename nqueens.py to n_queens.py --- backtracking/{nqueens.py => n_queens.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename backtracking/{nqueens.py => n_queens.py} (100%) diff --git a/backtracking/nqueens.py b/backtracking/n_queens.py similarity index 100% rename from backtracking/nqueens.py rename to backtracking/n_queens.py From 45355bcdd0cd68abf12ea7b1356a00677ebace94 Mon Sep 17 00:00:00 2001 From: hetzz Date: Fri, 5 Jul 2019 14:01:05 +0530 Subject: [PATCH 5/5] Deleting /other/n_queens.py --- other/n_queens.py | 77 ----------------------------------------------- 1 file changed, 77 deletions(-) delete mode 100644 other/n_queens.py diff --git a/other/n_queens.py b/other/n_queens.py deleted file mode 100644 index 0e80a0cff5e9..000000000000 --- a/other/n_queens.py +++ /dev/null @@ -1,77 +0,0 @@ -#! /usr/bin/python3 -import sys - -def nqueens(board_width): - board = [0] - current_row = 0 - while True: - conflict = False - - for review_index in range(0, current_row): - left = board[review_index] - (current_row - review_index) - right = board[review_index] + (current_row - review_index); - if (board[current_row] == board[review_index] or (left >= 0 and left == board[current_row]) or (right < board_width and right == board[current_row])): - conflict = True; - break - - if (current_row == 0 and conflict == False): - board.append(0) - current_row = 1 - continue - - if (conflict == True): - board[current_row] += 1 - - if (current_row == 0 and board[current_row] == board_width): - print("No solution exists for specificed board size.") - return None - - while True: - if (board[current_row] == board_width): - board[current_row] = 0 - if (current_row == 0): - print("No solution exists for specificed board size.") - return None - - board.pop() - current_row -= 1 - board[current_row] += 1 - - if board[current_row] != board_width: - break - else: - current_row += 1 - if (current_row == board_width): - break - - board.append(0) - return board - -def print_board(board): - if (board == None): - return - - board_width = len(board) - for row in range(board_width): - line_print = [] - for column in range(board_width): - if column == board[row]: - line_print.append("Q") - else: - line_print.append(".") - print(line_print) - - -if __name__ == '__main__': - default_width = 8 - for arg in sys.argv: - if (arg.isdecimal() and int(arg) > 3): - default_width = int(arg) - break - - if (default_width == 8): - print("Running algorithm with board size of 8. Specify an alternative Chess board size for N-Queens as a command line argument.") - - board = nqueens(default_width) - print(board) - print_board(board)