简化重复性问题 - python 中一个函数中有多个 if elif 语句和多个循环

Trouble simplifying repetitive - multiple if elif statements and multiple loops in a function in python

我对 Python 很陌生。

我坚信简单、简洁、高效的算法设计和编码风格。当我学习 Python 时,我意识到 Python 在幕后做了很多事情,因此语言本身对程序员非常友好。这很好,但我想深入了解我可以做哪些优化或在编码时保持习惯。而今天我 运行 陷入了简化我的代码的麻烦。

以下函数用于根据选择的难度级别在数独板上创建空位。

这是我的代码:

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

如您所见,它非常重复。任何关于简化它或更有效的编码风格的想法将不胜感激。

此外,在性能和内存使用方面,是否有更好的方法在 python 中初始化 class 而不是调用 __init__()?就像在 C++ 中一样,有初始化列表,它更干净、更快。

还请大家指出我犯的错误。任何建议将不胜感激。谢谢

由于唯一改变的是从中选择的数字范围,我建议创建一个难度映射到该数字的字典,然后在设置数字的单个函数中使用它。

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 the difficulty level exists in the dict. 
        # If it does, use that value, if it doesn't then use the default value
           difficulty = difficulty_values.get(difficulties, difficulty_values['Default'])

            # now use that difficulty to set the numbers once.
            for 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

你可以给你添加一个检查方法class:

# add this to the class body
def auto_increment(self, a, b):
    if self.sudoku[a][b] != None:
       self.sudoku[a][b] = None
       self.holes += 1
    self.holes += 1
    return

然后您可以使用以下方法将参数传递给您的方法:

self.auto_increment(choices(number), choices(number))

插槽是减少内存使用的有效方法 Usage of __slots__?

一种选择是将参数从代码移动到数据,然后对数据进行操作:

# You could source these two dicts from elsewhere, like a JSON/YAML/config file
difficulties = {
  Easy: {
    size: 25
  },
  Medium: {
    size: 35
  },
  Hard: {
    size: 45
  }
}

defaultDifficulty = {
  size: 65
}

# ...

def Create_Empty_Entries(self, difficultyName):
  if difficultyName in difficulties:
    difficulty = difficulties[difficultyName]
  else:
    difficulty = defaultDifficulty

  numbers = list(range(0,9))
  for x in range(difficulty.size):
    a,b = choice(numbers),choice(numbers)
    if self.sudoku[a][b] != None:
      self.sudoku[a][b] = None
      self.holes += 1