Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
Im trying to put in valid numbers into the board and meet all the conditions for the game.
The code doesnt run for some reason.
board = [
[0,0,6,9,0,5,0,1,0],
[9,7,0,0,1,2,3,0,5],
[0,2,0,0,0,4,8,6,0],
[5,0,3,8,0,0,0,2,0],
[0,0,0,0,0,0,0,0,0],
[0,8,0,0,0,1,9,0,7],
[0,5,4,1,0,0,0,7,0],
[2,0,7,4,5,0,0,9,3],
[0,6,0,7,0,3,1,0,0]
]
#cheking that the 3x3 squares dont have sum of 45, game continues if False
def check_conditions():
a = board[0][0:3] + board[1][0:3] + board[2][0:3]
b = board[3][0:3] + board[4][0:3] + board[5][0:3]
c = board[6][0:3] + board[7][0:3] + board[8][0:3]
d = board[0][3:6] + board[1][1:6] + board[2][1:6]
e = board[3][3:6] + board[4][1:6] + board[5][1:6]
f = board[6][3:6] + board[7][1:6] + board[8][1:6]
g = board[0][6:9] + board[1][6:9] + board[2][6:9]
h = board[3][6:9] + board[4][6:9] + board[5][6:9]
i = board[6][6:9] + board[7][6:9] + board[8][6:9]
all_squares = [a,b,c,d,e,f,g,h,i]
for i in all_squares:
if sum(i) != 45:
return False
#checking for duplicate in row, this function is under check_conditions()
for i in board:
if len(i) != len(set(i)):
return False
#checking that there no zeros in the board
def zero_condition():
for i in board:
for j in i:
if j == 0:
return False
#checking for duplicates in column
def get_column(col, board):
column = []
for i in range(len(board)):
column.append(board[i][col])
return column
all_column = [get_column(0, board), get_column(1, board), get_column(2, board), get_column(3, board), get_column(4, board), get_column(5, board), get_column(6, board), get_column(7, board), get_column(8, board)]
def check_column():
for i in all_column:
if len(i) != len(set(i)):
return False
#putting numbers into chosen rows and column
def choose_cell():
row = int(input("choose row:"))
column = int(input("choose column:"))
choose_num = int(input("choose a num between 1 og 9:"))
if 0< choose_num <=9:
board[row][column] = choose_num
else:
print("illegal num try again")
choose_cell()
#this is where the game starts
def begin_soduko():
answer= input("play soduko?")
if answer == "yes":
while zero_condition() == False and check_conditions == False and check_column() == False:
choose_cell()
print("you have finished soduko!!!")
I copy pasted all your code into a script and attempted to run it. If this is all your code, the first thing you are missing is a call to "begin_sudoku()" before your finishing print statement.
Afterwards, I ran it and was able to be asked whether to play, but entering "yes" still ended the game despite all three conditions being false. I found the last reason your game isn't running is because you are forgetting the parenthesis on "check_conditions()" when checking conditions in the while loop. I added the () to the end of it along with the call to begin_sudoku() and the game ran fine for me.
def begin_soduko():
answer= input("play soduko?")
if answer == "yes":
while zero_condition() == False and check_conditions() == False and check_column() == False:
choose_cell()
begin_soduko()
print("you have finished soduko!!!")
Replace your last code block with this and it should finally run.
Related
I am currently writing an eight queens problem solving algorithm.
The alogorithm is not the problem tho. Its the storing of the solutions.
I am trying to append the solutions (solutions are stored in a list of lists) to a list,
but after saving the solution and continuing through the algorithm,
the Values of the saved list keep changing.
I suppose the saved list and the one I am changing are somehow still "connected",
but I dont know how.
Does anyone know a solution or a different approach to my saving strategy?
This is the part of the code I am having Problems with.
# The Code only gets executed if there is a valid solution.
if found_solution():
# Saving solution
solutions.append(board)
# deleting last Queen
temp = last_queen.pop()
board[temp[0]][temp[1]] = "-"
# going back one Row
Reihe -= 1
# return
return
The board does look like this
board = [["-","-","-","-"],
["-","-","-","-"],
["-","-","-","-"],
["-","-","-","-"]]
the solution list like this
solutions = []
If anyone wants to take a look at the whole code (There are a few german variables tho):
board = [["-","-","-","-"],
["-","-","-","-"],
["-","-","-","-"],
["-","-","-","-"]]
Reihe = 0
solutions = []
last_queen = []
def found_solution():
count = 0
for i in range(4):
for j in range(4):
if board[i][j] == "D":
count += 1
if count == 4:
return True
return False
def board_clear(temp_Reihe, temp_i):
#Check Column and Row
for k in range(4):
if board[temp_Reihe][k] == "D":
return False
if board[k][temp_i] == "D":
return False
#Check Diagonals
#temp_i == x and temp_Reihe == y
st1_x = temp_i - min(temp_i, temp_Reihe)
st1_y = temp_Reihe - min(temp_i, temp_Reihe)
st2_x = temp_i - min(temp_i, 3-temp_Reihe)
st2_y = temp_Reihe + min(temp_i, 3-temp_Reihe)
while st1_x < 4 and st1_y < 4:
if board[st1_y][st1_x] == "D":
return False
st1_x += 1
st1_y += 1
while st2_x < 4 and st2_y > -1:
if board[st2_y][st2_x] == "D":
return False
st2_x += 1
st2_y -= 1
return True
def main():
global Reihe, board, solutions, last_queen
if found_solution():
#Saving solution
solutions.append(board)
#deleting last Queen
temp = last_queen.pop()
board[temp[0]][temp[1]] = "-"
#going back one Row
Reihe -= 1
return
for i in range(4):
#placing Queen if valid spot
if board_clear(Reihe, i):
board[Reihe][i] = "D"
last_queen.append([Reihe,i])
Reihe += 1
main()
#delete last Queen
temp = last_queen.pop()
board[temp[0]][temp[1]] = "-"
#going back one Row
Reihe -= 1
return
main()
People have suggested using copy or deepcopy
list2 = list1.deepcopy()
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I only have to do this:
Take a string entered by the user and print the game grid as in the previous stage.
Analyze the game state and print the result.
Like this:
1. Enter cells: XXXOO__O_ ---------
| X X X |
| O O _ |
| _ O _ | ---------
X wins
The problem is that my program never reaches the elif statements and I don´t know why.
n = input()
number_grid = []
Winner = ""
print("---------")
Cont = {"X": 0, "O": 0, "_": 0} # This will count to check for impossible games
for i in range(0, len(n), 3):
print("|", n[i], n[i+1], n[i+2], "|")
number_grid.append([n[i], n[i+1], n[i+2]])
Cont[n[i]] = Cont[n[i]] + 1
Cont[n[i + 1]] = Cont[n[i + 1]] + 1
Cont[n[i + 2]] = Cont[n[i + 2]] + 1
print("---------")
Impossible = False
if 2 <= Cont["X"] - Cont["O"] or Cont["X"] - Cont["O"] <= -2:
Impossible = True
print("Impossible")
exit()
if Winner == "" and Impossible is False:
for rows in range(0, 3): # Check winner in rows
if number_grid[rows][0] == number_grid[rows][1] == number_grid[rows][2] != "_":
Winner = number_grid[rows][0]
print(Winner, "wins")
for columns in range(0, 3): # Check winner in columns
if number_grid[0][columns] == number_grid[1][columns] == number_grid[2][columns] != "_":
Winner = number_grid[0][columns]
print(Winner, "wins")
if number_grid[0][0] == number_grid[1][1] == number_grid[2][2] != "_": # Check winner in first diagonal
Winner = number_grid[0][0]
print(Winner, "wins")
if number_grid[0][2] == number_grid[1][1] == number_grid[2][0] != "_": # Check winner in second diagonal
Winner = number_grid[0][2]
print(Winner, "wins")
elif Cont["_"] != 0:
print("Game not finished")
elif Cont["X"] + Cont["O"] == 9:
print("Draw")
Reducing your code down...
Winner = ""
Impossible = False
if Winner == "" and Impossible is False:
# Stuff
elif Cont["_"] != 0:
print("Game not finished")
elif Cont["X"] + Cont["O"] == 9:
print("Draw")
In your current code, it's not possible for Winner != "" or Impossible != True. So you will never enter the elif statement.
The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. I have solved this program earlier, but am trying to rework my code to mirror that which I used to fashion a sudoku solver. I cannot seem to find the logical error but when I run the code, nothing prints. My program is attached below and if anyone could find my error that would be very helpful!
import numpy as np
def main():
global n
n = input("Enter N")
n = int(n)
global board
board = np.zeros((n,n), dtype=int)
solve_board()
def solve_board():
for row in range(n):
for col in range(n):
if board[row][col] == 0: #no queen
if (is_valid (board,row,col,n)):
board[row][col] = 1 #Assigning 1 for queen
solve_board()
board[row][col] = 0
return False
print('-'*n)
for row in board:
for col in row:
if col == 1:
print ("Q", end = " ")
else:
print (".", end = " ")
def is_valid(board,i,j,n):
if 1 in board[i]: #Checking row
return False
for row in range(0,i): #Checking column
if (board[row][j]==1):
return False
x,y = i,j
while (x>=0 and y>=0): #left diagonal
if (board[x][y]==1):
return False
x-=1
y-=1
x,y = i,j
while (x>=0 and y<n): #right diagonal
if (board[x][y]==1):
return False
x-=1
y+=1
return True
if __name__ == "__main__":
main()
This is how I had solved this code earlier, with solve_board being altered as followed.
def solve_board(row):
if(row == n):
print('-'*n)
for row in board:
for col in row:
if col == 1:
print ("Q", end = " ")
else:
print (".", end = " ")
print("")
else:
for col in range(n):
if (is_valid (board,row,col,n)):
board[row][col]=1
solve_board(row+1)
board[row][col] = 0
return False
Here is where the inspiration for my current code came from, a sudoku solver that I designed where I used 2 nested for loops; one for rows and one for columns. Based on this I had altered my solve_board(row) in my original n-queens code to the current function without a parameter. This sudoku code works perfectly.
def solve_board():
global board
for rowno in range(9):
#print ("row",rowno)
for colno in range(9):
#print("col",colno)
if board[rowno][colno] == 0:
for i in range(1,10):
#print(i)
if (is_valid(board,rowno,colno,i)):
board[rowno][colno]=i
solve_board()
board[rowno][colno]=0
return False
print (np.matrix(board))
I think the issue might lie in the fact that in the N-Queens problem the board does not fill up, i.e there are still 0s while for sudoku the entire board fills up and therefore when the ''if board[row][col] == 0'' is proven false exits the loop and prints. In the N-Queens problem since zero's are always present, it becomes an issue.
Try this
import numpy as np
def main():
global n
n = input("Enter N: ")
n = int(n)
global board
board = np.zeros((n,n), dtype=int)
solve_board()
def print_board():
print('-'*n)
for row in board:
for col in row:
if col == 1:
print ("Q", end = " ")
else:
print (".", end = " ")
print()
def is_valid(board,i,j,n):
if 1 in board[i]: #Checking row
return False
for row in range(0, n): #Checking column
if (board[row][j]==1):
return False
for k in range(0,n):
for l in range(0,n):
if (k+l==i+j) or (k-l==i-j):
if board[k][l]==1:
return False
return True
def solve_board():
for row in range(n):
for col in range(n):
if board[row][col] == 0: #no queen
if (is_valid (board,row,col,n)):
board[row][col] = 1 #Assigning 1 for queen
if np.count_nonzero(board) == n:
print_board()
return True
solve_board()
board[row][col] = 0
else:
return False
if __name__ == "__main__":
main()
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
im trying to code this caesar cipher decoder, but whenever the input message has any " "(spaces) it just print " " infinitely
[ps: just started coding]
already tried to change -if- to check if meslist[x] is equal to " ", but it doesent seems like a "valid" thing
here is the code:
import string
letras = list(string.ascii_lowercase)
message = input("qual sua menssagem codificada?")
cod = input("qual a numeração da cifra?")
meslist = list(message)
trans = True
num = len(meslist)
x = 0
while trans:
if num > x:
if meslist[x] in letras:
a = letras.index(meslist[x])
print(letras[a + 2])
x = x + 1
trans = True
else:
print(" ")
trans = True
elif num == 0:
trans = False'
just expecting for it to print it the right way.
I fixed the code as below :
while trans:
if num > x:
if meslist[x] in letras:
a = letras.index(meslist[x])
print(letras[a + 2])
x = x + 1
trans = True
else:
print(" ")
trans = True
# to increase x by 1, to take the next char. in the next loop
x = x + 1
# num == x means the end of the loop
elif num == x:
trans = False
I have an excercise to do and I'm stuck. It's the board game Alak, not much known, that I have to code in python. I can link the execrcise with the rules so you can help me better. The code has the main part and the library with all the procedures and function.
from Library_alak import *
n = 0
while n < 1:
n = int(input('Saisir nombre de case strictement positif : '))
loop = True
player = 1
player2 = 2
removed = [-1]
board = newboard(n)
display(board, n)
while loop:
i = select(board, n, player, removed)
print(i)
board = put(board, player, i)
display(board, n)
capture(board, n, player, player2)
loop = True if again(board, n, player, removed) is True else False
if player == 1 and loop:
player, player2 = 2, 1
elif player == 2 and loop:
player, player2 = 1, 2
win(board, n)
print(win(board, n))
And here is the library:
def newboard(n):
board = ([0] * n)
return board
def display(board, n):
for i in range(n):
if board[i] == 1:
print('X', end=' ')
elif board[i] == 2:
print('O', end=' ')
else:
print(' . ', end=' ')
def capture(board, n, player, player2):
for place in range(n):
if place == player:
place_beginning = place
while board[place] != player:
place_end = place
if board[place + x] == player:
return board
else:
return board
def again(board, n, player, removed):
for p in board(0):
if p == 0:
if p not in removed:
return True
else:
return False
def possible(n, removed, player, i, board):
for p in range(n + 1):
if p == 1:
if board[p-1] == 0:
if p not in removed:
return True
else:
return False
def win(board, n):
piecesp1 = 0
piecesp2 = 0
for i in board(0):
if i == 1:
piecesp1 += 1
else:
piecesp2 += 1
if piecesp1 > piecesp2:
print('Victory : Player 1')
elif piecesp2 > piecesp1:
print('Victory : Player 2')
else:
return 'Equality'
def select(board, n, player, removed):
loop = True
while loop:
print('player', player)
i = int(input('Enter number of boxes : '))
loop = False if possible(n, removed, player, i, board)is True else True
return i
def put(board, player, i):
i -= 1
if board[i] == 0:
if player == 1:
board[i] = 1
return board
else:
board[i] = 2
return board
else:
put(board, player, i)
So my problems here are that I have few errors, the first one is that when I enter the number '1' when asked to enter a number of boxes ( which is the place to play on ) nothing happens. Then when entering any other number, either the error is : if board[place + x] == player:
NameError: name 'x' is not defined
or there seems to be a problem with the : if board[place + x] == player:
NameError: name 'x' is not defined
I would appreciate a lot if anyone could help me. I'm conscious that it might not be as detailed as it should be and that you maybe don't get it all but you can contact me for more.
Rules of the Alak game:
Black and white take turns placing stones on the line. Unlike Go, this placement is compulsory if a move is available; if no move is possible, the game is over.
No stone may be placed in a location occupied by another stone, or in a location where a stone of your own colour has just been removed. The latter condition keeps the game from entering a neverending loop of stone placement and capture, known in Go as ko.
If placing a stone causes one or two groups of enemy stones to no longer have any adjacent empty spaces--liberties, as in Go--then those stones are removed. As the above rule states, the opponent may not play in those locations on their following turn.
If placing a stone causes one or two groups of your own colour to no longer have any liberties, the stones are not suicided, but instead are safe and not removed from play.
You shouldn't use "player2" as a variable, there's an easier way, just use "player" which take the value 1 or 2 according to the player. You know, something like that : player = 1 if x%2==0 else 2
and x is just a increasing int from 0 until the end of the game.