当前位置:   article > 正文

发现一个宝藏!全网最全的Python算法仓库

算法仓

学习编程、学习Python最好的方式就是练习,哪怕是新手,只要不断地敲代码输出,肯定会有神效。

Python的练手项目很多,特别是Github上,建议不管新手、老司机都去看看。

这里推荐给大家一个Gitthub上练习的项目,算法仓库-algorithms。

https://github.com/keon/algorithms

这里面集合众多核心算法的Python实现,比如排序、图计算、回溯、队列、流计算、堆、搜索、压缩等等。

该仓库支持第三方库安装,在python中进行调用,非常方便。

首先使用pip进行安装:

pip3 install algorithms

然后导入相关模块进行调用,比如sort模块里的merge_sort归并排序算法。

  1. from algorithms.sort import merge_sort
  2. if __name__ == "__main__":
  3.     my_list = [18356]
  4.     my_list = merge_sort(my_list)
  5.     print(my_list)

举几个常见的算法案例。

1、排序算法-桶排序

  1. def bucket_sort(arr):
  2.     ''' Bucket Sort
  3.         Complexity: O(n^2)
  4.         The complexity is dominated by nextSort
  5.     '''
  6.     # The number of buckets and make buckets
  7.     num_buckets = len(arr)
  8.     buckets = [[] for bucket in range(num_buckets)]
  9.     # Assign values into bucket_sort
  10.     for value in arr:
  11.         index = value * num_buckets // (max(arr) + 1)
  12.         buckets[index].append(value)
  13.     # Sort
  14.     sorted_list = []
  15.     for i in range(num_buckets):
  16.         sorted_list.extend(next_sort(buckets[i]))
  17.     return sorted_list
  18. def next_sort(arr):
  19.     # We will use insertion sort here.
  20.     for i in range(1, len(arr)):
  21.         j = i - 1
  22.         key = arr[i]
  23.         while arr[j] > key and j >= 0:
  24.             arr[j+1= arr[j]
  25.             j = j - 1
  26.         arr[j + 1= key
  27.     return arr

2、机器学习-最近邻插值法

  1. import math
  2. def distance(x,y):
  3.     """[summary]
  4.     HELPER-FUNCTION
  5.     calculates the (eulidean) distance between vector x and y.
  6.     Arguments:
  7.         x {[tuple]} -- [vector]
  8.         y {[tuple]} -- [vector]
  9.     """
  10.     assert len(x) == len(y), "The vector must have same length"
  11.     result = ()
  12.     sum = 0
  13.     for i in range(len(x)):
  14.         result += (x[i] -y[i],)
  15.     for component in result:
  16.         sum += component**2
  17.     return math.sqrt(sum)
  18. def nearest_neighbor(x, tSet):
  19.     """[summary]
  20.     Implements the nearest neighbor algorithm
  21.     Arguments:
  22.         x {[tupel]} -- [vector]
  23.         tSet {[dict]} -- [training set]
  24.     Returns:
  25.         [type] -- [result of the AND-function]
  26.     """
  27.     assert isinstance(x, tupleand isinstance(tSet, dict)
  28.     current_key = ()
  29.     min_d = float('inf')
  30.     for key in tSet:
  31.         d = distance(x, key)
  32.         if d < min_d:
  33.             min_d = d
  34.             current_key = key
  35.     return tSet[current_key]

3、字符串解码编码

  1. # Implement the encode and decode methods.
  2. def encode(strs):
  3.     """Encodes a list of strings to a single string.
  4.     :type strs: List[str]
  5.     :rtype: str
  6.     """
  7.     res = ''
  8.     for string in strs.split():
  9.         res += str(len(string)) + ":" + string
  10.     return res
  11. def decode(s):
  12.     """Decodes a single string to a list of strings.
  13.     :type s: str
  14.     :rtype: List[str]
  15.     """
  16.     strs = []
  17.     i = 0
  18.     while i < len(s):
  19.         index = s.find(":", i)
  20.         size = int(s[i:index])
  21.         strs.append(s[index+1index+1+size])
  22.         i = index+1+size
  23.     return strs

4、直方分布

  1. def get_histogram(input_list: list) -> dict:
  2.     """
  3.     Get histogram representation
  4.     :param input_list: list with different and unordered values
  5.     :return histogram: dict with histogram of input_list
  6.     """
  7.     # Create dict to store histogram
  8.     histogram = {}
  9.     # For each list valueadd one to the respective histogram dict position
  10.     for i in input_list:
  11.         histogram[i] = histogram.get(i, 0+ 1
  12.     return histogram

个人感觉这个仓库里的算法很齐全,适合做练习,小伙伴们可以试试。

【python学习】
学Python的伙伴,欢迎加入新的交流【君羊】:1020465983
一起探讨编程知识,成为大神,群里还有软件安装包,实战案例、学习资料 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/973136
推荐阅读
相关标签
  

闽ICP备14008679号