I've started learning python and currently working on making a simple Sudoku game.
I have 2 modules sudoku.py and sudoku_GUI.py
sudoku.py contains one class - Board and it's purpose is to solve the game based on an input.
solve method, in order to generate solution, needs to call other methods:
def solve(self):
empty_fields = self.find_empty()
if empty_fields == []:
return True
self.init_rows_columns_squares()
row, column = empty_fields[0]
square = 3 * (row//3) + column//3
valid_numbers = list(set(Board.number_arr) - (set(self.rows[row] + self.columns[column] + self.squares[square])))
valid_numbers.sort()
for i in valid_numbers:
if not self.is_valid(empty_fields[0], i):
return False
self.insert_number(empty_fields[0], i)
if self.solve():
return True
self.insert_number(empty_fields[0], 0)
return False
And this works just fine when it is called from its own module. However, when I try to call it from Sudoku_GUI:
import sudoku
def solve_board(self, board):
board.solve()
board_1 = sudoku.Board(sudoku.board)
solve_board(self, board_1)
It doesn't work, solve method gets called and it won't call other methods as it does in its own module. Obviously, I could solve it in first module and just import solved board, but since I'm learning I want to know why this happens.
If someone could explain this to me, I would be very greatful. Thank you!
-
2what is the error you see?Mohsen_Fatemi– Mohsen_Fatemi2020年01月30日 00:09:10 +00:00Commented Jan 30, 2020 at 0:09
-
There is no error, it runs, just won't call self.init_rows_columns_squares() and other I tested it by putting print("method_name") in every method and it just prints "solve"kaktus_car– kaktus_car2020年01月30日 00:11:26 +00:00Commented Jan 30, 2020 at 0:11
-
1paste your whole code to paste.ubuntu.com and send short link hereMohsen_Fatemi– Mohsen_Fatemi2020年01月30日 00:12:14 +00:00Commented Jan 30, 2020 at 0:12
-
Ok, will do, just a seckaktus_car– kaktus_car2020年01月30日 00:12:53 +00:00Commented Jan 30, 2020 at 0:12
-
Does it work correctly if everything is in a single file?Barmar– Barmar2020年01月30日 00:13:38 +00:00Commented Jan 30, 2020 at 0:13
1 Answer 1
From the code you wrote, i understand you are calling your functions in a wrong way! you only use self keyword when you are writing code in a class. outside the class you don't need to write self when you call the class methods.
i will rewrite your code in order to work :
>>> import sudoku
>>> from pprint import pprint
>>>
>>> class test_gui:
... def solve_board(self, board):
... board.solve()
...
>>> board_1 = sudoku.Board(sudoku.board)
>>> gui = test_gui()
>>> gui.solve_board(board_1)
>>> pprint(board_1.board)
[[1, 4, 6, 7, 9, 2, 3, 8, 5],
[2, 5, 8, 3, 4, 6, 7, 9, 1],
[3, 7, 9, 5, 8, 1, 4, 6, 2],
[4, 3, 7, 9, 1, 5, 8, 2, 6],
[5, 8, 1, 6, 2, 7, 9, 3, 4],
[6, 9, 2, 4, 3, 8, 1, 5, 7],
[7, 1, 3, 2, 6, 9, 5, 4, 8],
[8, 2, 4, 1, 5, 3, 6, 7, 9],
[9, 6, 5, 8, 7, 4, 2, 1, 3]]