Улучшение рекурсивной функции за счет упрощения нескольких условных операторов - PullRequest
0 голосов
/ 07 ноября 2019

Я пытаюсь превратить все «1» в self.data в нули, если они не находятся в безопасной зоне, окруженной нулями. Мой код в настоящее время работает, но я ищу способы улучшить его. Кто-нибудь знает, как упростить мой рекурсивный вызов для функции start_infect? Кроме того, возможно ли, что он может зацикливаться бесконечно? Что я могу сделать, чтобы исправить / улучшить это?

import sys
class Spreading:
    # (self, self.height (up and down) ---> y, self.width (side to side) ---> x)
    def setdata(self):
        self.data = [[1, 1, 1, 1, 1, 1, 1, 1],
                     [1, 1, 1, 1, 1, 1, 1, 1],
                     [1, 0, 0, 0, 0, 0, 0, 1],
                     [1, 0, 0, 1, 1, 0, 0, 1],
                     [1, 0, 0, 1, 1, 0, 0, 1],
                     [1, 0, 0, 0, 0, 0, 0, 1],
                     [1, 0, 0, 0, 0, 0, 0, 1],
                     [1, 1, 1, 1, 1, 1, 1, 1],
                     [1, 1, 1, 1, 1, 1, 1, 1]]

    def init_infect(self, x, y):    # width, height
        self.height = len(self.data)    # y
        self.width = len(self.data[0])  # x
        self.data[y][x] = 0
        print(type(self.data))

    def start_infect(self, x, y):
        if ((x < 0 or y < 0) or self.data[y][x] == 0):
            return
        if y != 0:
            self.data[y][x] = 0
            self.start_infect(x, y-1)           # north
        if x < self.width-1 and y != 0:
            self.data[y][x] = 0
            self.start_infect(x + 1, y - 1)     # northeast
        if x < self.width - 1:
            self.data[y][x] = 0
            self.start_infect(x + 1, y)         # east
        if x < self.width-1 and y < self.height-1:
            self.data[y][x] = 0
            self.start_infect(x + 1, y + 1)     # southeast
        if y < self.height-1:
            self.data[y][x] = 0
            self.start_infect(x, y + 1)         # south
        if x != 0 and y < self.height-1:
             self.data[y][x] = 0
             self.start_infect(x - 1, y + 1)     # southwest
        if x != 0:
             self.data[y][x] = 0
             self.start_infect(x - 1, y)         # west
        if x != 0 and y != 0:
             self.data[y][x] = 0
             self.start_infect(x - 1, y - 1)     # northwest

    def getdata(self):
        return self.data

sys.setrecursionlimit(500000)
Spread = Spreading()
Spread.setdata()
Spread.init_infect(0, 0)
Spread.start_infect(0, 1)
myresults = Spread.getdata()
...