-
-
Save justjkk/372468 to your computer and use it in GitHub Desktop.
Recursive solution for N-Queens problem in Python
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
from math import * | |
import sys | |
chosen = {} | |
n = int(sys.argv[1]) | |
def place(xpos, ypos): | |
if (ypos in chosen.values()): | |
return False | |
opponent = 1 | |
while(opponent < xpos): | |
if abs(chosen[opponent]-ypos) == abs(opponent-xpos): | |
return False | |
opponent+=1 | |
return True | |
def clear_all_future_positions(xpos): | |
for i in range(xpos,n+1): | |
chosen[i]=None | |
def NQueens(xpos): | |
# print 'NQueens(',xpos,') entering' | |
for ypos in range(1, n + 1): | |
clear_all_future_positions(xpos) | |
if place(xpos, ypos): | |
chosen[xpos] = ypos | |
# print 'chosen=',chosen | |
if (xpos==n): | |
for opponent in chosen: | |
print chosen[opponent] | |
print '------------------' | |
else: | |
NQueens(xpos+1) | |
# print 'NQueens(',xpos,') returns' | |
NQueens(1) |
#code error line 14, in
n = int(sys.argv[1])IndexError: list index out of range
Try running with python3 nqueens.py [value of n that you want]
#code error line 14, in
n = int(sys.argv[1])
IndexError: list index out of range
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
#code error line 14, in
n = int(sys.argv[1])
IndexError: list index out of range