常用Python算法的33个示例
下面是一些常用Python算法的示例,涵盖了排序、搜索、图算法以及一些数论和字符串处理的基本算法:
1. 排序算法
- 冒泡排序:
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
- 选择排序:
def selection_sort(arr):
for i in range(len(arr)):
min_idx = i
for j in range(i+1, len(arr)):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
return arr
- 插入排序:
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i-1
while j >=0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
- 快速排序:
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
- 归并排序:
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
def merge(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result
2. 搜索算法
- 线性搜索:
def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i
return -1
- 二分搜索:
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
3. 图算法
- 深度优先搜索:
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
print(start)
for next in graph[start] - visited:
dfs(graph, next, visited)
return visited
- 广度优先搜索:
from collections import deque
def bfs(graph, start):
visited = set()
queue = deque([start])
while queue:
vertex = queue.popleft()
if vertex not in visited:
print(vertex)
visited.add(vertex)
queue.extend(graph[vertex] - visited)
- Dijkstra算法:
import heapq
def dijkstra(graph, start):
pq = [(0, start)]
distances = {vertex: float('infinity') for vertex in graph}
distances[start] = 0
while pq:
current_distance, current_vertex = heapq.heappop(pq)
if current_distance > distances[current_vertex]:
continue
for neighbor, weight in graph[current_vertex]:
distance = current_distance + weight
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(pq, (distance, neighbor))
return distances
4. 数论和字符串处理
- 欧几里得算法 (GCD):
def gcd(a, b):
while b:
a, b = b, a % b
return a
- 质数检测:
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
- 埃拉托色尼筛法:
def sieve_of_eratosthenes(n):
primes = [True] * (n+1)
p = 2
while p**2 <= n:
if primes[p]:
for i in range(p**2, n+1, p):
primes[i] = False
p += 1
return [p for p in range(2, n) if primes[p]]
- 字符串反转:
def reverse_string(s):
return s[::-1]
- 最长公共子序列:
def lcs(X, Y):
m = len(X)
n = len(Y)
L = [[0] * (n + 1) for i in range(m + 1)]
for i in range(m + 1):
for j in range(n + 1):
if i == 0 or j == 0:
L[i][j] = 0
elif X[i - 1] == Y[j - 1]:
L[i][j] = L[i - 1][j - 1] + 1
else:
L[i][j] = max(L[i - 1][j], L[i][j - 1])
return L[m][n]
这些代码示例涵盖了一些常见的算法,帮助你理解和实现各种计算任务。如果有其他具体算法需求或额外解释需要讲解的地方,可以随时问我!