如何计算Python中排序所需的步骤数?
我在冒泡排序的函数里用了这段代码来计算排序所需的步骤
def bubble(self):
def bubble_sort ( array ) :
swap_test = False
for i in range ( 0, len ( array ) - 1 ):
for j in range ( 0, len ( array ) - i - 1 ):
if array[j] > array[j + 1] :
array[j], array[j + 1] = array[j + 1], array[j]#elegentan way of swap
swap_test = True
self.textbox()
else:
self.sortingend()
break
#if swap_test == False:
#else:
#self.create_label()
#print('bubble to be implemented')
bubble_sort(self.nums)
return self.nums
而对于这两个函数 sortingend() 和 textbox(),我用了这两段代码
def sortingend(self):
self.label21 = Label(self, text="Sorting Finish", width=25, height=2)
self.label21.grid(row=7, column=1, sticky=N)
def textbox(self):
count=0
count +=1
self.label1 = Label(self, text="Step: %i " % count, width=25, height=2)
self.label1.grid(row=6, column=1, sticky=N)
但是不知怎么的,这些代码没有正常工作,我只收到一个错误提示,说 count+=1 这个变量没有定义。不过如果我在 sortingend() 里把 count 设置为 0,那每次计数器就会从 0 开始。而且当我在第一步运行冒泡排序时,它就显示排序已经完成。请问该怎么修正这个问题。
2 个回答
0
你遇到错误是因为“count”这个东西没有定义。你在说“count = count + 1”,可是一开始的时候“count”是什么呢?你应该考虑使用递归,最开始把“count”设为0,然后再调用“textbox(self, count + 1)”。
textbox(self, count):
self.label1 = Label(self, text="Step: %i " % count, width=25, height=2)
self.label1.grid(row=6, column=1, sticky=N)
def bubble_sort ( array ) :
count = 0
swap_test = False
for i in range ( 0, len ( array ) - 1 ):
for j in range ( 0, len ( array ) - i - 1 ):
if array[j] > array[j + 1] :
array[j], array[j + 1] = array[j + 1], array[j]#elegentan way of swap
swap_test = True
self.textbox(count+1)
0
在你的代码中,你写了:
def textbox(self):
count=0
count +=1
这意味着每次你调用 textbox(self)
的时候,都会创建一个 count=0
,然后把它加一——下次你再调用 textbox(self)
的时候,又会重新开始这个过程。