首頁 >後端開發 >Python教學 >Algorithms,最完整的Python演算法倉庫

Algorithms,最完整的Python演算法倉庫

WBOY
WBOY轉載
2023-06-03 08:46:031538瀏覽

學習程式設計、學習Python最好的方式就是練習,哪怕是新手,只要不斷地敲程式碼輸出,一定會有神效。

Python的練手專案很多,特別是Github上,建議不管新手、老司機都去看看。

Algorithms,最完整的Python演算法倉庫

這裡推薦給大家一個Gitthub上練習的項目,演算法倉庫-algorithms。

https://github.com/keon/algorithms

這裡面集合眾多核心演算法的Python實現,例如排序、圖計算、回溯、隊列、流計算、堆、搜尋、壓縮等等。

Algorithms,最完整的Python演算法倉庫

此倉庫支援第三方程式庫安裝,在python中進行調用,非常方便。

首先使用pip進行安裝:

pip3 install algorithms

然後導入相關模組進行調用,例如sort模組裡的merge_sort歸併排序演算法。

from algorithms.sort import merge_sort

if __name__ == "__main__":
my_list = [1, 8, 3, 5, 6]
my_list = merge_sort(my_list)
print(my_list)

舉出幾個常見的演算法案例。

1. 排序演算法-桶排序

def bucket_sort(arr):
''' Bucket Sort
Complexity: O(n^2)
The complexity is dominated by nextSort
'''
# The number of buckets and make buckets
num_buckets = len(arr)
buckets = [[] for bucket in range(num_buckets)]
# Assign values into bucket_sort
for value in arr:
index = value * num_buckets // (max(arr) + 1)
buckets[index].append(value)
# Sort
sorted_list = []
for i in range(num_buckets):
sorted_list.extend(next_sort(buckets[i]))
return sorted_list

def next_sort(arr):
# We will use insertion sort here.
for i in range(1, len(arr)):
j = i - 1
key = arr[i]
while arr[j] > key and j >= 0:
arr[j+1] = arr[j]
j = j - 1
arr[j + 1] = key
return arr

2. 機器學習-最近鄰插值法

import math

def distance(x,y):
"""[summary]
HELPER-FUNCTION
calculates the (eulidean) distance between vector x and y.

Arguments:
x {[tuple]} -- [vector]
y {[tuple]} -- [vector]
"""
assert len(x) == len(y), "The vector must have same length"
result = ()
sum = 0
for i in range(len(x)):
result += (x[i] -y[i],)
for component in result:
sum += component**2
return math.sqrt(sum)

def nearest_neighbor(x, tSet):
"""[summary]
Implements the nearest neighbor algorithm

Arguments:
x {[tupel]} -- [vector]
tSet {[dict]} -- [training set]

Returns:
[type] -- [result of the AND-function]
"""
assert isinstance(x, tuple) and isinstance(tSet, dict)
current_key = ()
min_d = float('inf')
for key in tSet:
d = distance(x, key)
if d < min_d:
min_d = d
current_key = key
return tSet[current_key]

3. 字串解碼編碼

# Implement the encode and decode methods.

def encode(strs):
"""Encodes a list of strings to a single string.
:type strs: List[str]
:rtype: str
"""
res = ''
for string in strs.split():
res += str(len(string)) + ":" + string
return res

def decode(s):
"""Decodes a single string to a list of strings.
:type s: str
:rtype: List[str]
"""
strs = []
i = 0
while i < len(s):
index = s.find(":", i)
size = int(s[i:index])
strs.append(s[index+1: index+1+size])
i = index+1+size
return strs

4 . 直方分佈

def get_histogram(input_list: list) -> dict:
"""
Get histogram representation
:param input_list: list with different and unordered values
:return histogram: dict with histogram of input_list
"""
# Create dict to store histogram
histogram = {}
# For each list value, add one to the respective histogram dict position
for i in input_list:
histogram[i] = histogram.get(i, 0) + 1
return histogram

個人感覺這個倉庫裡的演算法很齊全,適合做練習,小夥伴們可以試試。

以上是Algorithms,最完整的Python演算法倉庫的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:51cto.com。如有侵權,請聯絡admin@php.cn刪除