python - 我想使用 pygame 在 python 中创建一个合并排序可视化器。代码没有给出正确的结果
问题描述
我正在创建一个排序可视化器,但代码没有打印正确的输出。我是 python 新手,所以这可能是一个愚蠢的错误,但我想不通也许问题在于在合并函数中创建 List L 和 R ...
import pygame
import random
pygame.init()
screen = pygame.display.set_mode((1000, 700))
pygame.display.set_caption("SORTING VISUALS")
class Rect:
def __init__(self, x, y, width, height):
self.X = x
self.Y = y
self.width = width
self.height = height
self.colour = BLACK
def show(self):
pygame.draw.rect(screen, self.colour, (self.X, self.Y, self.width, self.height))
def changeCol(self, colour):
self.colour = colour
在下面的代码中声明和复制类的元素可能有问题...
def merge(l, m, r):
global rect, n
n1 = m - l + 1
n2 = r - m
# create temp arrays
L = []
R = []
# Copy data to temp arrays L[] and R[]
for i in range(n1):
L.append(Rect(rect[l + 1].X, rect[l + 1].Y, rect[l + 1].width, rect[l + 1].height))
refresh()
for j in range(n2):
R.append(Rect(rect[m + 1 + j].X, rect[m + 1 + j].Y, rect[m + 1 + j].width, rect[m + 1 + j].height))
refresh()
i = 0
j = 0
k = l
while i < n1 and j < n2:
print("checking merge...")
if L[i].height <= R[j].height:
# rect[k] = Rect(L[i].X, L[i].Y, L[i].width, L[i].height)
rect[k], L[i] = L[i], rect[k]
rect[k].X, L[i].X = L[i].X, rect[k].X
i += 1
else:
# rect[k] = Rect(R[j].X, R[j].Y, R[j].width, R[j].height)
rect[k], R[j] = R[j], rect[k]
rect[k].X, R[j].X = R[j].X, rect[k].X
j += 1
k += 1
for a in range(n):
print(rect[a].height, end=" ")
print()
refresh()
# Copy the remaining elements of L[], if there
# are any
while i < n1:
rect[k], L[i] = L[i], rect[k]
rect[k].X, L[i].X = L[i].X, rect[k].X
i += 1
k += 1
refresh()
# Copy the remaining elements of R[], if there
# are any
while j < n2:
rect[k], R[j] = R[j], rect[k]
rect[k].X, R[j].X = R[j].X, rect[k].X
j += 1
k += 1
refresh()
我知道代码很可疑,但任何帮助都会很棒...您还可以提出一些优化建议...。
解决方案
有一条线显然是错误的。创建列表时,列表中R
源元素的索引而不是:rect
l + i
l + 1
L.append(Rect(rect[l + 1].X, rect[l + 1].Y, rect[l + 1].width, rect[l + 1].height))
for i in range(n1):
L.append(Rect(rect[l + i].X, rect[l + i].Y, rect[l + i].width, rect[l + i].height))
推荐阅读
- ios - 在 testflight 中添加一些来测试 ios 应用程序
- jenkins - Jenkins 共享管道 java.io.NotSerializableException: hudson.plugins.sshslaves.SSHLauncher
- r - 如何将变量从服务器传递到 ui 并在闪亮的模板中显示?
- .net - 让 process.start 与 WindowStyle 一起工作
- python - 如何计算大型文本语料库中出现的每一个二元组
- java - for循环的效率
- python - 在 Python 中计算时间序列网格的 ACF
- laravel - Laravel Eloquent 选择使用 group by
- ffmpeg - ffmpeg在Video JS中重新编码手机上的mp4文件错误
- keras - 在使用 K.gradients 计算梯度时,使用微调网络可视化 ConvNet 过滤器导致“NoneType”