Python
Python在机器学习、数据科学、人工智能、web开发等许多领域逐渐占据主导地位。
根据PYPL编程语言人气指数,python占据编程语言额约为31.6%。
我想最好学习python的方式,通过构建一个项目来掌握编程语言的基础------排序。
在本文结束时,您将使用五种不同的算法构建一个算法排序可视化工具:
- 选择排序
- 冒泡排序
- 插入排序
- 归并排序
- 快速排序
算法
让我们创建一个名为algorithm .py的文件,在这个文件中,我们将用python编写所有的排序算法。导入时间模块,告知用户可视化工具所花费的时间。
创建一个名为Algorithm的类,并将这段代码粘贴到其中:
Python
class Algorithm:
def __init__(self, name):
self.array = random.sample(range(512), 512) # Random array of size 512
self.name = name # Get name of the variable
def update_display(self, swap1=None, swap2=None):
import visualizer
visualizer.update(self, swap1, swap2) # pass the indexes to be swapped into the visualizer
def run(self): # Start the timer and run the algorithm
self.start_time = time.time()
self.algorithm()
time_elapsed = time.time() - self.start_time
return self.array, time_elapsed
我们将首先创建一个大小为512的随机数组。在update_display方法中,我们将调用visualizer.py中的更新函数,稍后我们将编写该函数来处理图形。最后,run方法将启动计时器并调用算法函数。
Selection Sort选择排序
Python
class SelectionSort(Algorithm):
def __init__(self):
super().__init__("SelectionSort")
def algorithm(self):
for i in range(len(self.array)):
min_idx = i
for j in range(i+1, len(self.array)):
if self.array[j] < self.array[min_idx]:
min_idx = j
self.array[i], self.array[min_idx] = self.array[min_idx], self.array[i]
self.update_display(self.array[i], self.array[min_idx])
SelectionSort类将继承Algorithm类,并在其中实现选择排序。每当数组更新时,我们调用update_display方法并实时呈现数组的排序。类似地,我们对其他算法也同样实现。
Bubble Sort冒泡排序
Python
class BubbleSort(Algorithm):
def __init__(self):
super().__init__("BubbleSort")
def algorithm(self):
for i in range(len(self.array)):
for j in range(len(self.array)-1-i):
if self.array[j] > self.array[j+1]:
self.array[j], self.array[j+1] = self.array[j+1], self.array[j]
self.update_display(self.array[j], self.array[j+1])
Insertion Sort插入排序
Python
class InsertionSort(Algorithm):
def __init__(self):
super().__init__("InsertionSort")
def algorithm(self):
for i in range(len(self.array)):
cursor = self.array[i]
idx = i
while idx > 0 and self.array[idx-1] > cursor:
self.array[idx] = self.array[idx-1]
idx -= 1
self.array[idx] = cursor
self.update_display(self.array[idx], self.array[i])
Merge Sort归并排序
Python
class MergeSort(Algorithm):
def __init__(self):
super().__init__("MergeSort")
def algorithm(self, array=[]):
if array == []:
array = self.array
if len(array) < 2:
return array
mid = len(array) // 2
left = self.algorithm(array[:mid])
right = self.algorithm(array[mid:])
return self.merge(left, right)
def merge(self, left, right):
result = []
i, j = 0, 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
self.update_display()
result += left[i:]
result += right[j:]
self.array = result
self.update_display()
return result
Quick Sort快速排序
Python
class QuickSort(Algorithm):
def __init__(self):
super().__init__("QuickSort")
def algorithm(self, array=[], start=0, end=0):
if array == []:
array = self.array
end = len(array) - 1
if start < end:
pivot = self.partition(array,start,end)
self.algorithm(array,start,pivot-1)
self.algorithm(array,pivot+1,end)
def partition(self, array, start, end):
x = array[end]
i = start-1
for j in range(start, end+1, 1):
if array[j] <= x:
i += 1
if i < j:
array[i], array[j] = array[j], array[i]
self.update_display(array[i], array[j])
return i
可视化
恭喜你!你刚刚写了所有流行的排序算法。最后一步是可视化地显示这些排序算法。
下面是visualizer.py文件的代码。
Python
import algorithms
import time
import os
import sys
import pygame
# Set the window length and breadth (Make sure that the breadth is equal to size of array. [512])
dimensions = [1024, 512]
# List all the algorithms available in the project in dictionary and call the necessary functions from algorithms.py
algorithms = {"SelectionSort": algorithms.SelectionSort(), "BubbleSort": algorithms.BubbleSort(), "InsertionSort": algorithms.InsertionSort(), "MergeSort": algorithms.MergeSort(), "QuickSort": algorithms.QuickSort()}
# Check list of all the available sorting techniques using 'list'
if len(sys.argv) > 1:
if sys.argv[1] == "list":
for key in algorithms.keys(): print(key, end=" ") # Display the available algorithms
print("")
sys.exit(0)
# Initalise the pygame library
pygame.init()
# Set the dimensions of the window and display it
display = pygame.display.set_mode((dimensions[0], dimensions[1]))
# Fill the window with purple hue
display.fill(pygame.Color("#a48be0"))
def check_events(): # Check if the pygame window was quit
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit();
sys.exit();
def update(algorithm, swap1=None, swap2=None, display=display): # The function responsible for drawing the sorted array on each iteration
display.fill(pygame.Color("#a48be0"))
pygame.display.set_caption("Sorting Visualizer Algorithm: {} Time: {:.3f} Status: Sorting...".format(algorithm.name, time.time() - algorithm.start_time)) # Display on title bar
k = int(dimensions[0]/len(algorithm.array))
for i in range(len(algorithm.array)):
colour = (80, 0, 255)
if swap1 == algorithm.array[i]:
colour = (0,255,0)
elif swap2 == algorithm.array[i]:
colour = (255,0,0)
# The most important step that renders the rectangles to the screen that gets sorted.
# pygame.draw.rect(dsiplay_window, color_of_rectangle, size_of_rectangle)
pygame.draw.rect(display, colour, (i*k,dimensions[1],k,-algorithm.array[i]))
check_events()
pygame.display.update()
def keep_open(algorithm, display, time): # Keep the window open until sort completion
pygame.display.set_caption("Sorting Visualizer Algorithm: {} Time: {:.3f} Status: Done!".format(algorithm.name, time))
while True:
check_events()
pygame.display.update()
def main():
if len(sys.argv) < 2:
print("Please select a sorting algorithm.")
else:
try:
algorithm = algorithms[sys.argv[1]] # Pass the algorithm selected
try:
time_elapsed = algorithm.run()[1]
keep_open(algorithm, display, time_elapsed)
pass
except:
pass
except:
print("Error.")
if __name__ == "__main__":
main()
是的!我知道,有很多代码需要消化,但我向您保证,当您按下运行按钮时,所有代码都将变得有趣。
让我来解释一下可视化器的代码。
结果
是时候运行我们的项目了。在项目目录中打开终端并执行 python visualizer.py list
获得所有可用算法的列表。
markdown
Available algorithms:
SelectionSort
BubbleSort
InsertionSort
MergeSort
QuickSort
比如执行:python visualizer.py SelectionSort
PS:在运行过程中发现有一处代码不对,修改如下:
Python
def update(algorithm, swap1=None, swap2=None, display=display):
# The function responsible for drawing the sorted array on each iteration
display.fill(pg.Color("#a48be0"))
pg.display.set_caption("Sorting Visualizer 11 Algorithm: {} Time: {:.3f} Status: Sorting...".format(algorithm.name, time.time() - algorithm.start_time)) # Display on title bar
k = int(dimensions[0]/len(algorithm.array))
for i in range(len(algorithm.array)):
colour = (80, 0, 255)
if swap1 == algorithm.array[i]:
colour = (0,255,0)
elif swap2 == algorithm.array[i]:
colour = (255,0,0)
# 设置帧率为每秒60帧
# The most important step that renders the rectangles to the screen that gets sorted.
# pg.draw.rect(dsiplay_window, color_of_rectangle, size_of_rectangle)
pg.draw.rect(display, colour, (i*k, 512 - algorithm.array[i], k, algorithm.array[i]))
time.sleep(0.3)
check_events()
pg.display.update()