creating board for 8 queen in python -


i trying create chess board 8 queen problem. challenge let user enter queens' positions , tell them if position wouldn't allowed due other queens. have board far

this code have far:

boardsize = input('board size: ')  rows = [[0] * int(boardsize)] rows = str(rows).replace('[','').replace(']','').replace(',','')  in range(int(boardsize)):     print(i + 1, rows) 

this produces:

board size: 8

1 0 0 0 0 0 0 0 0

2 0 0 0 0 0 0 0 0

3 0 0 0 0 0 0 0 0

4 0 0 0 0 0 0 0 0

5 0 0 0 0 0 0 0 0

6 0 0 0 0 0 0 0 0

7 0 0 0 0 0 0 0 0

8 0 0 0 0 0 0 0 0

i can't see way enter "q" (to symbolise queen) want enter it. reprint board q instead of 1 of zeros , repeat until 8 queens placed or there no space queen. must user controlled.

i recommend instead of storing whole grid, store queen position in each row. because 1 queen can exist in each row, know enough store queen. makes life bit easier have direct pointers queens (rather having iterate through board find queens). use this:

sample_positions = [0, 2, 4, 1, 3, 5, none, none]  def print_positions(positions):     ind, pos in enumerate(positions):         row = ["_"] * len(positions)          if pos not none:             row[pos] = "q"          print("{}: {}".format(ind, " ".join(row)))  x, y = map(int, input("enter new queen position> ").split())  sample_positions[y] = x  print_positions(sample_positions) 

this program runs this:

enter new queen position> 6 7 0: q _ _ _ _ _ _ _ 1: _ _ q _ _ _ _ _ 2: _ _ _ _ q _ _ _ 3: _ q _ _ _ _ _ _ 4: _ _ _ q _ _ _ _ 5: _ _ _ _ _ q _ _ 6: _ _ _ _ _ _ _ _ 7: _ _ _ _ _ _ q _ 

i've included example of how might take input (although want write validation function , apply first. i've replaced printing functionality little more pythonic - generally, doing string operations on repr of list isn't idea. also, example input assumes both x , y given integers - can change letters or whatever appropriate. i've moved whole thing little more 0-based simplicity of implementation - i'd recommend using underscore empty cell, not integer.

presumably you're not too interested in performance. program build empty row each row goes through - funky generator chaining make couple of nanoseconds faster, make answer more complicated is.

this modified excerpt queens project. (disclaimer: wrote it). should wish refer more on how representation works or how might validate board in model, feel free. note project different yours- mine brute-forces possible solutions , features no interactive input.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -