提示信息

常用Python算法的33个示例

深海的鱼 已关注

下面是一些常用Python算法的示例,涵盖了排序、搜索、图算法以及一些数论和字符串处理的基本算法:

1. 排序算法

  1. 冒泡排序:
  1. def bubble_sort(arr):
  2. n = len(arr)
  3. for i in range(n):
  4. for j in range(0, n-i-1):
  5. if arr[j] > arr[j+1]:
  6. arr[j], arr[j+1] = arr[j+1], arr[j]
  7. return arr
  1. 选择排序:
  1. def selection_sort(arr):
  2. for i in range(len(arr)):
  3. min_idx = i
  4. for j in range(i+1, len(arr)):
  5. if arr[j] < arr[min_idx]:
  6. min_idx = j
  7. arr[i], arr[min_idx] = arr[min_idx], arr[i]
  8. return arr
  1. 插入排序:
  1. def insertion_sort(arr):
  2. for i in range(1, len(arr)):
  3. key = arr[i]
  4. j = i-1
  5. while j >=0 and key < arr[j]:
  6. arr[j + 1] = arr[j]
  7. j -= 1
  8. arr[j + 1] = key
  9. return arr
  1. 快速排序:
  1. def quick_sort(arr):
  2. if len(arr) <= 1:
  3. return arr
  4. pivot = arr[len(arr) // 2]
  5. left = [x for x in arr if x < pivot]
  6. middle = [x for x in arr if x == pivot]
  7. right = [x for x in arr if x > pivot]
  8. return quick_sort(left) + middle + quick_sort(right)
  1. 归并排序:
  1. def merge_sort(arr):
  2. if len(arr) <= 1:
  3. return arr
  4. mid = len(arr) // 2
  5. left = merge_sort(arr[:mid])
  6. right = merge_sort(arr[mid:])
  7. return merge(left, right)
  8. def merge(left, right):
  9. result = []
  10. i = j = 0
  11. while i < len(left) and j < len(right):
  12. if left[i] < right[j]:
  13. result.append(left[i])
  14. i += 1
  15. else:
  16. result.append(right[j])
  17. j += 1
  18. result.extend(left[i:])
  19. result.extend(right[j:])
  20. return result

2. 搜索算法

  1. 线性搜索:
  1. def linear_search(arr, target):
  2. for i in range(len(arr)):
  3. if arr[i] == target:
  4. return i
  5. return -1
  1. 二分搜索:
  1. def binary_search(arr, target):
  2. left, right = 0, len(arr) - 1
  3. while left <= right:
  4. mid = (left + right) // 2
  5. if arr[mid] == target:
  6. return mid
  7. elif arr[mid] < target:
  8. left = mid + 1
  9. else:
  10. right = mid - 1
  11. return -1

3. 图算法

  1. 深度优先搜索:
  1. def dfs(graph, start, visited=None):
  2. if visited is None:
  3. visited = set()
  4. visited.add(start)
  5. print(start)
  6. for next in graph[start] - visited:
  7. dfs(graph, next, visited)
  8. return visited
  1. 广度优先搜索:
  1. from collections import deque
  2. def bfs(graph, start):
  3. visited = set()
  4. queue = deque([start])
  5. while queue:
  6. vertex = queue.popleft()
  7. if vertex not in visited:
  8. print(vertex)
  9. visited.add(vertex)
  10. queue.extend(graph[vertex] - visited)
  1. Dijkstra算法:
  1. import heapq
  2. def dijkstra(graph, start):
  3. pq = [(0, start)]
  4. distances = {vertex: float('infinity') for vertex in graph}
  5. distances[start] = 0
  6. while pq:
  7. current_distance, current_vertex = heapq.heappop(pq)
  8. if current_distance > distances[current_vertex]:
  9. continue
  10. for neighbor, weight in graph[current_vertex]:
  11. distance = current_distance + weight
  12. if distance < distances[neighbor]:
  13. distances[neighbor] = distance
  14. heapq.heappush(pq, (distance, neighbor))
  15. return distances

4. 数论和字符串处理

  1. 欧几里得算法 (GCD):
  1. def gcd(a, b):
  2. while b:
  3. a, b = b, a % b
  4. return a
  1. 质数检测:
  1. def is_prime(n):
  2. if n <= 1:
  3. return False
  4. for i in range(2, int(n**0.5) + 1):
  5. if n % i == 0:
  6. return False
  7. return True
  1. 埃拉托色尼筛法:
  1. def sieve_of_eratosthenes(n):
  2. primes = [True] * (n+1)
  3. p = 2
  4. while p**2 <= n:
  5. if primes[p]:
  6. for i in range(p**2, n+1, p):
  7. primes[i] = False
  8. p += 1
  9. return [p for p in range(2, n) if primes[p]]
  1. 字符串反转:
  1. def reverse_string(s):
  2. return s[::-1]
  1. 最长公共子序列:
  1. def lcs(X, Y):
  2. m = len(X)
  3. n = len(Y)
  4. L = [[0] * (n + 1) for i in range(m + 1)]
  5. for i in range(m + 1):
  6. for j in range(n + 1):
  7. if i == 0 or j == 0:
  8. L[i][j] = 0
  9. elif X[i - 1] == Y[j - 1]:
  10. L[i][j] = L[i - 1][j - 1] + 1
  11. else:
  12. L[i][j] = max(L[i - 1][j], L[i][j - 1])
  13. return L[m][n]

这些代码示例涵盖了一些常见的算法,帮助你理解和实现各种计算任务。如果有其他具体算法需求或额外解释需要讲解的地方,可以随时问我!

    遇到难题? "AI大模型GPT4.0、GPT" 是你的私人解答专家! 点击按钮去提问......
深海的鱼 关注 已关注

最近一次登录:2024-11-21 10:03:35   

暂时还没有签名,请关注我或评论我的文章
×
免费图表工具,画流程图、架构图