使随机像素移动更有效地运行

2024-04-19 18:34:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码使用三个随机数和一些if语句来随机移动一个像素。使用cProfiler,结果发现这个函数效率很低。你知道吗

s = self.surrounding()
surroundingBool = [False if i == None else True for i in s]

r1 = random.random()
r2 = random.random()
r3 = random.random()

if r1 <= 0.333:
    if r3 < 0.5 and not surroundingBool[4]: self.x += 1
    elif not surroundingBool[3]: self.x -= 1
elif r1 <= 0.666:
    if r3 < 0.5 and not surroundingBool[6]: self.y += 1
    elif not surroundingBool[1]: self.y -= 1
else:
    if r2 < 0.25 and not surroundingBool[7]:
        self.x += 1
        self.y += 1
    elif r2 < 0.5 and not surroundingBool[2]:
        self.x += 1
        self.y -= 1
    elif r2 < 0.75 and not surroundingBool[5]:
        self.x -= 1
        self.y += 1
    elif not surroundingBool[0]:
        self.x -= 1
        self.y -= 1

self.x %= width
self.y %= height
    self.pos = self.y * width + self.x

希望这是非常不言自明的,但我可以根据需要提供上下文。 如何使这些if-else语句更快或更有效?你知道吗

如果需要,可以在here找到完整的代码。你知道吗


Tags: and代码selfifnotrandom像素语句
1条回答
网友
1楼 · 发布于 2024-04-19 18:34:17

这里有一种不同的方法,如果你认为它与你的像素移动方法不同,你可以忽略它。由于在二维像素阵列中最多有八种可能的移动到相邻像素,因此您可以定义一个恒定的移动list,并将它们与一个索引配对,该索引引用由所述移动产生的像素。你知道吗

根据我对代码的解释,这是可以在pixel类的__init__方法中定义的。你知道吗

设置:

changes_1d = (-1, 0, 1)
changes_2d = [(i,j) for j in changes_1d for i in changes_1d if i or j]
self.movements = tuple(enumerate(changes_2d))  # Assign pixel index to each movement

self.movements的内容:

0 (-1, -1)
1 (0, -1)
2 (1, -1)
3 (-1, 0)
4 (1, 0)
5 (-1, 1)
6 (0, 1)
7 (1, 1)

为什么要这么做?现在我们可以利用random.choice()快速选择随机的二维像素移动,我们可以使用(dx,dy)移动对旁边返回的索引来检查此移动是否有效:

def move(self):
    s = self.surrounding()
    surroundingBool = [i is not None for i in s]

    pixel, movement = random.choice(self.movements)

    if surroundingBool[pixel]:
        self.x += movement[0]
        self.y += movement[1]

注意:这假设移动到周围八个像素中任何一个的概率相等。你知道吗

然而,我相信self.surrounding()功能也可能存在很多低效,特别是在这方面:

PAI = allPixels[(self.x + x) % width][(self.y + y) % height] if allPixels[(self.x + x) % width][(self.y + y) % height] != None else None

检查像素是否为无,然后将其分配给PAI。如果为None,则将None赋值给PAI,使if else检查变得多余。以下语句是等效的:

PAI = allPixels[(self.x + x) % width][(self.y + y) % height]

我会提供更多的建议,但是有很多代码可以理解。不断寻找改进的方法!你知道吗

相关问题 更多 >