Skip to content

Instantly share code, notes, and snippets.

@justjkk
Forked from yuvipanda/nqueens.py
Created April 20, 2010 13:57
Show Gist options
  • Save justjkk/372468 to your computer and use it in GitHub Desktop.
Save justjkk/372468 to your computer and use it in GitHub Desktop.
Recursive solution for N-Queens problem in Python
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)
@ajinkyajawale14499
Copy link

#code error line 14, in
n = int(sys.argv[1])

IndexError: list index out of range

@edutra
Copy link

edutra commented Nov 25, 2019

#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]

@ahmadjz
Copy link

ahmadjz commented May 29, 2021

#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