I am very new to Python.
I am a firm believer of simple, concise and efficient algorithmic design as well as coding style. As I am learning Python, I realize that Python does a lot of things behind the scene so that the language itself is super friendly to programmers. This is nice but I wanted to learn deeply about what optimizations I can do or keep a habit of when coding. And today I ran into trouble simplify my code.
The following function is used to create empty spots on a sudoku board based on difficulty level that is chosen.
Here is my code:
class normalSudoku(Board):
def __init__(self,difficulties):
super.__init__()
self.Create_Empty_Entries(difficulties)
def Create_Empty_Entries(self,difficulties):
numbers = list(range(0,9))
if difficulties == "Easy":
for x in range(25):
a,b = choice(numbers),choice(numbers)
if self.sudoku[a][b] != None:
self.sudoku[a][b] = None
self.holes += 1
self.holes += 1
return None
elif difficulties == "Medium":
for x in range(35):
a,b = choice(numbers),choice(numbers)
if self.sudoku[a][b] != None:
self.sudoku[a][b] = None
self.holes += 1
return None
elif difficulties == "Hard":
for x in range(45):
a,b = choice(numbers),choice(numbers)
if self.sudoku[a][b] != None:
self.sudoku[a][b] = None
self.holes += 1
return None
else:
for x in range(65):
a,b = choice(numbers),choice(numbers)
if self.sudoku[a][b] != None:
self.sudoku[a][b] = None
self.holes += 1
return None
As you can see it is very repetitive. Any idea on simplifying it or a more efficient coding style will be appreciated.
Also, is there a better way of initializing a class in python rather than calling __init__()
in terms of performance and memory usage? Just like in C++ there is initialization list where it is cleaner and faster.
Please feel free to point out the mistakes I have made. Any advice will be greatly appreciated. Thanks
Since the only thing that is changing is the range of numbers being chosen from, I'd recommend creating a dict where difficulty maps to that number then using it in a single function that sets the numbers.