Python 中的 Pygorithm 模組


Pygorithm 模組是一個教育模組,包含各種演算法的實現。此模組的最佳用途是從實現的演算法中獲取用 Python 編寫的程式碼。但它也可以用於實際程式設計,我們可以在給定的資料集中應用各種演算法。

查詢資料結構

在 Python 環境中安裝模組後,我們可以在包中找到各種資料結構。

示例

from pygorithm import data_structures
help(data_structures

執行上述程式碼,我們會得到以下結果 -

輸出

Help on package pygorithm.data_structures in pygorithm:
NAME
   pygorithm.data_structures - Collection of data structure examples

PACKAGE CONTENTS
   graph
   heap
   linked_list
   quadtree
   queue
   stack
   tree
   trie

DATA
   __all__ = ['graph', 'heap', 'linked_list', 'queue', 'stack', 'tree', '...

獲取演算法程式碼

在下面的程式中,我們看到了如何獲取佇列資料結構演算法的程式碼。

示例

from pygorithm.data_structures.queue import Queue

the_Queue = Queue()
print(the_Queue.get_code())

執行上述程式碼,我們會得到以下結果 -

輸出

class Queue(object):
   """Queue
   Queue implementation
   """
   def __init__(self, limit=10):
      """
      :param limit: Queue limit size, default @ 10
      """
      self.queue = []
      self.front = None
      self.rear = None
      self.limit = limit
      self.size = 0
…………………………
………………

應用排序

在以下示例中,我們看到了如何對給定的列表應用快速排序。

示例

from pygorithm.sorting import quick_sort

my_list = [3,9,5,21,2,43,18]
sorted_list = quick_sort.sort(my_list)
print(sorted_list)

執行上述程式碼,我們會得到以下結果 -

輸出

[2, 3, 5, 9, 18, 21, 43]

更新於: 2020 年 12 月 28 日

263 次瀏覽

開啟你的 職業生涯

完成學習即可獲得認證

立即開始
廣告
© . All rights reserved.