python的练手项目很多,特别是github上,建议不管新手、老司机都去看看。
这里推荐给大家一个gitthub上练习的项目,算法仓库-algorithms。
https://github.com/keon/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 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算法仓库的详细内容。
