Python是一種流行的編程語言,它具有廣泛的應用和豐富的算法庫。在Python中,算法可以分為幾個系列:
1. 排序算法
def bubble_sort(arr): n = len(arr) for i in range(n - 1): for j in range(n - 1 - i): if arr[j] >arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] return arr
2. 查找算法
def binary_search(arr, low, high, x): if high >= low: mid = (high + low) // 2 if arr[mid] == x: return mid elif arr[mid] >x: return binary_search(arr, low, mid - 1, x) else: return binary_search(arr, mid + 1, high, x) else: return -1
3. 圖算法
class Graph: def __init__(self, vertices): self.V = vertices self.graph = [[0 for column in range(vertices)] for row in range(vertices)] def isSafe(self, v, pos, path): if self.graph[path[pos - 1]][v] == 0: return False for vertex in path: if vertex == v: return False return True def hamiltonianCycleUtil(self, path, pos): if pos == self.V: if self.graph[path[pos - 1]][path[0]] == 1: return True else: return False for v in range(1, self.V): if self.isSafe(v, pos, path) is True: path[pos] = v if self.hamiltonianCycleUtil(path, pos + 1) is True: return True path[pos] = -1 return False
4. 動態規劃算法
def knapsack(wt, val, W, n): K = [[0 for x in range(W + 1)] for x in range(n + 1)] for i in range(n + 1): for w in range(W + 1): if i == 0 or w == 0: K[i][w] = 0 elif wt[i - 1]<= w: K[i][w] = max(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w]) else: K[i][w] = K[i - 1][w] return K[n][W]
以上是Python算法系列的四個主要方向,我們可以根據具體需求選擇合適的算法方法,在解決實際問題中提升代碼效率。