最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用Python可視化展示排序算法

 更新時(shí)間:2024年11月25日 08:30:41   作者:關(guān)山月  
這篇文章主要介紹了使用Python可視化展示排序算法,讓我們創(chuàng)建一個(gè)名為algorithm?.py的文件,在這個(gè)文件中,我們將用python編寫(xiě)所有的排序算法,需要的朋友可以參考下

算法

讓我們創(chuàng)建一個(gè)名為algorithm .py的文件,在這個(gè)文件中,我們將用python編寫(xiě)所有的排序算法。導(dǎo)入時(shí)間模塊,告知用戶(hù)可視化工具所花費(fèi)的時(shí)間。

創(chuàng)建一個(gè)名為Algorithm的類(lèi),并將這段代碼粘貼到其中:

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

我們將首先創(chuàng)建一個(gè)大小為512的隨機(jī)數(shù)組。在update_display方法中,我們將調(diào)用visualizer.py中的更新函數(shù),稍后我們將編寫(xiě)該函數(shù)來(lái)處理圖形。最后,run方法將啟動(dòng)計(jì)時(shí)器并調(diào)用算法函數(shù)。

Selection Sort選擇排序

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類(lèi)將繼承Algorithm類(lèi),并在其中實(shí)現(xiàn)選擇排序。每當(dāng)數(shù)組更新時(shí),我們調(diào)用update_display方法并實(shí)時(shí)呈現(xiàn)數(shù)組的排序。類(lèi)似地,我們對(duì)其他算法也同樣實(shí)現(xiàn)。

Bubble Sort冒泡排序

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插入排序

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歸并排序

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快速排序

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

可視化

恭喜你!你剛剛寫(xiě)了所有流行的排序算法。最后一步是可視化地顯示這些排序算法。

下面是visualizer.py文件的代碼。

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()

是的!我知道,有很多代碼需要消化,但我向您保證,當(dāng)您按下運(yùn)行按鈕時(shí),所有代碼都將變得有趣。

讓我來(lái)解釋一下可視化器的代碼。

結(jié)果

是時(shí)候運(yùn)行我們的項(xiàng)目了。在項(xiàng)目目錄中打開(kāi)終端并執(zhí)行 python visualizer.py list 獲得所有可用算法的列表。

Available algorithms:
        SelectionSort
        BubbleSort
        InsertionSort
        MergeSort
        QuickSort

比如執(zhí)行:python visualizer.py SelectionSort

PS:在運(yùn)行過(guò)程中發(fā)現(xiàn)有一處代碼不對(duì),修改如下:

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)
        # 設(shè)置幀率為每秒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()

以上就是使用Python可視化展示排序算法的詳細(xì)內(nèi)容,更多關(guān)于Python可視化展示算法的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Python連接字符串過(guò)程詳解

    Python連接字符串過(guò)程詳解

    這篇文章主要介紹了python連接字符串過(guò)程詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-01-01
  • 使用Python+psutil開(kāi)發(fā)一個(gè)簡(jiǎn)易系統(tǒng)監(jiān)控工具

    使用Python+psutil開(kāi)發(fā)一個(gè)簡(jiǎn)易系統(tǒng)監(jiān)控工具

    在運(yùn)維自動(dòng)化、服務(wù)器巡檢、故障排查和資源告警場(chǎng)景中,經(jīng)常需要快速獲取機(jī)器的 CPU、內(nèi)存、磁盤(pán)和進(jìn)程狀態(tài),Python 的 psutil 庫(kù)正好解決了這個(gè)問(wèn)題,本文會(huì)從 psutil 基礎(chǔ)用法開(kāi)始,逐步實(shí)現(xiàn)一個(gè)可以實(shí)時(shí)刷新的簡(jiǎn)易系統(tǒng)監(jiān)控工具,需要的朋友可以參考下
    2026-05-05
  • python單線程實(shí)現(xiàn)多個(gè)定時(shí)器示例

    python單線程實(shí)現(xiàn)多個(gè)定時(shí)器示例

    這篇文章主要介紹了python單線程實(shí)現(xiàn)多個(gè)定時(shí)器示例,需要的朋友可以參考下
    2014-03-03
  • Python實(shí)現(xiàn)csv文件(點(diǎn)表和線表)轉(zhuǎn)換為shapefile文件的方法

    Python實(shí)現(xiàn)csv文件(點(diǎn)表和線表)轉(zhuǎn)換為shapefile文件的方法

    這篇文章主要介紹了Python實(shí)現(xiàn)csv文件(點(diǎn)表和線表)轉(zhuǎn)換為shapefile文件的方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-10-10
  • Python使用OpenCV轉(zhuǎn)換圖像大小

    Python使用OpenCV轉(zhuǎn)換圖像大小

    在Python中,使用OpenCV庫(kù)來(lái)轉(zhuǎn)換圖像大小是一個(gè)常見(jiàn)的操作,它可以幫助你調(diào)整圖像到特定的尺寸,以適應(yīng)不同的應(yīng)用場(chǎng)景,比如圖像預(yù)處理、模型輸入等,下面是一個(gè)詳細(xì)的代碼示例,展示了如何使用OpenCV來(lái)轉(zhuǎn)換圖像的大小,需要的朋友可以參考下
    2024-09-09
  • Python中的pygal安裝和繪制直方圖代碼分享

    Python中的pygal安裝和繪制直方圖代碼分享

    這篇文章主要介紹了Python中的pygal安裝和繪制直方圖代碼分享,具有一定借鑒價(jià)值,需要的朋友可以參考下。
    2017-12-12
  • Python使用Pandas處理缺失值的技巧分享

    Python使用Pandas處理缺失值的技巧分享

    爬蟲(chóng)抓取的數(shù)據(jù)就像剛從泥坑里挖出來(lái)的土豆,表面沾滿(mǎn)泥土(缺失值、重復(fù)值、異常值),內(nèi)部可能還有壞掉的部分(無(wú)效數(shù)據(jù)),本文聚焦最讓人頭疼的缺失值問(wèn)題,用Python的Pandas庫(kù)演示如何像處理食材一樣清洗數(shù)據(jù),讓臟數(shù)據(jù)變成可直接分析的凈數(shù)據(jù),需要的朋友可以參考下
    2025-10-10
  • python中的pygame實(shí)現(xiàn)接球小游戲

    python中的pygame實(shí)現(xiàn)接球小游戲

    這篇文章主要介紹了python中的pygame實(shí)現(xiàn)接球小游戲,文章基于python的相關(guān)資料展開(kāi)詳細(xì)的內(nèi)容,具有一定的參考價(jià)值,需要的小伙伴可以參考一下
    2022-04-04
  • python實(shí)現(xiàn)發(fā)消息提醒功能的常見(jiàn)方法

    python實(shí)現(xiàn)發(fā)消息提醒功能的常見(jiàn)方法

    這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)發(fā)消息提醒功能的常見(jiàn)方法,文中的示例代碼講解詳細(xì),有需要的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2026-05-05
  • 淺談Python pygame繪制機(jī)制

    淺談Python pygame繪制機(jī)制

    今天給大家?guī)?lái)的是關(guān)于Python的相關(guān)知識(shí),文章圍繞著Python pygame繪制機(jī)制展開(kāi),文中有非常詳細(xì)的介紹及圖文示例,需要的朋友可以參考下
    2021-06-06

最新評(píng)論

西安市| 西和县| 砚山县| 房产| 延寿县| 左权县| 手游| 渝中区| 登封市| 互助| 祁阳县| 额敏县| 台前县| 博野县| 连江县| 大新县| 巴里| 从化市| 宜州市| 铜梁县| 铜陵市| 莆田市| 五家渠市| 攀枝花市| 隆安县| 清远市| 临湘市| 保康县| 清丰县| 定日县| 建始县| 大邑县| 霍林郭勒市| 肇州县| 栾川县| 福贡县| 华安县| 易门县| 玉树县| 淳化县| 山丹县|