performance - Trouble simplifying repetitive - multiple if elif statements and multiple loops in a function in python -
i new python.
i firm believer of simple, concise , efficient algorithmic design coding style. learning python, realize python lot of things behind scene language super friendly programmers. nice wanted learn optimizations can or keep habit of when coding. , today ran trouble simplify code.
the following function used create empty spots on sudoku board based on difficulty level chosen.
here 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": 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": 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": 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: 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 can see repetitive. idea on simplifying or more efficient coding style appreciated.
also, there better way of initializing class in python rather calling __init__()
in terms of performance , memory usage? in c++ there initialization list cleaner , faster.
please feel free point out mistakes have made. advice appreciated.
since thing changing range of numbers being chosen from, i'd recommend creating dict difficulty maps number using in single function sets numbers.
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)) difficulty_values = {'easy':25,'medium':35, 'hard':45, 'default':65} # check difficulty level exists in dict. # if does, use value, if doesn't use default value difficulty = difficulty_values.get(difficulties, difficulty_values['default']) # use difficulty set numbers once. x in range(difficulty): 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
Comments
Post a Comment