Python 算法學習是一門非常有用的技能。隨著數據量的增加,算法優化已成為越來越重要的事情。在Python中,有很多種算法可以使用,本文將會介紹Python中的一些常用算法。
1. 排序算法
def bubble_sort(data): for i in range(len(data)): for j in range(len(data)-i-1): if data[j] >data[j+1]: data[j], data[j+1] = data[j+1], data[j] return data def quick_sort(data): if len(data)<= 1: return data else: pivot = data[0] left = [x for x in data[1:] if x<= pivot] right = [x for x in data[1:] if x >pivot] return quick_sort(left) + [pivot] + quick_sort(right)
2. 查找算法
def binary_search(data, target): low = 0 high = len(data) - 1 while low<= high: mid = (low + high) // 2 if data[mid] == target: return mid elif data[mid]< target: low = mid + 1 else: high = mid - 1 return None
3. 圖算法
class Graph: def __init__(self, graph_dict=None): self.graph_dict = graph_dict or {} def add_edge(self, vertex, edge): self.graph_dict[vertex].append(edge) def bfs(self, start_vertex): visited = [False] * len(self.graph_dict) queue = [start_vertex] visited[start_vertex] = True while queue: current_vertex = queue.pop(0) print(current_vertex) for neighbor in self.graph_dict[current_vertex]: if not visited[neighbor]: visited[neighbor] = True queue.append(neighbor) def dfs(self, start_vertex, visited=None): if visited is None: visited = set() visited.add(start_vertex) print(start_vertex) for neighbor in self.graph_dict[start_vertex]: if neighbor not in visited: self.dfs(neighbor, visited)
Python中算法的學習可以幫助我們更好地處理數據,提高代碼的性能。學習這些算法前需要掌握Python的基礎知識,只有掌握了Python的基礎知識才能更好地理解這些算法。