Python面试题【数据结构和算法部分131-160】
- Python面试题【数据结构和算法部分131-160】
Python面试题【数据结构和算法部分131-160】
- 问题:在Python中如何实现一个优先队列?
答案:
import heapqclass PriorityQueue:def __init__(self):self._queue = []self._index = 0def push(self, item, priority):heapq.heappush(self._queue, (-priority, self._index, item))self._index += 1def pop(self):return heapq.heappop(self._queue)[-1]
- 问题:如何在Python中实现一个循环数组?
答案:
class CircularArray:def __init__(self, size):self.array = [None] * sizeself.size = sizeself.head = 0def get(self, index):return self.array[(self.head + index) % self.size]def set(self, index, value):self.array[(self.head + index) % self.size] = valuedef rotate(self, shift):self.head = (self.head + shift) % self.size
- 问题:如何在Python中检查一个数是否是快乐数?
答案:
def is_happy(n):seen = set()while n != 1 and n not in seen:seen.add(n)n = sum(int(i)**2 for i in str(n))return n == 1
- 问题:Python中如何实现计数排序?
答案:
def counting_sort(arr):count = [0] * (max(arr) + 1)for num in arr:count[num] += 1i = 0for num, freq in enumerate(count):for _ in range(freq):arr[i] = numi += 1return arr
- 问题:如何在Python中找到所有可能的排列组合?
答案:
from itertools import permutationsdef get_permutations(arr):return list(permutations(arr))
- 问题:在Python中如何实现希尔排序?
答案:
def shell_sort(arr):n = len(arr)gap = n // 2while gap > 0:for i in range(gap, n):temp = arr[i]j = iwhile j >= gap and arr[j - gap] > temp:arr[j] = arr[j - gap]j -= gaparr[j] = tempgap //= 2return arr
-
问题:在Python中如何实现最小生成树算法?
答案:
可以使用Kruskal或Prim算法实现最小生成树。这些算法通过选择边的方式来构造树,以确保树的权重总和最小,且不形成环。 -
问题:如何在Python中实现KMP字符串匹配算法?
答案:
KMP算法通过计算一个"部分匹配"表来改善匹配过程,减少比较的次数。 -
问题:在Python中如何实现冒泡排序?
答案:
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
- 问题:在Python中如何实现基数排序?
答案:
def radix_sort(arr):RADIX = 10placement = 1max_digit = max(arr)while placement < max_digit:buckets = [[] for _ in range(RADIX)]for i in arr:tmp = int((i / placement) % RADIX)buckets[tmp].append(i)a = 0for b in range(RADIX):buck = buckets[b]for i in buck:arr[a] = ia += 1placement *= RADIXreturn arr
- 问题:如何在Python中实现深度优先搜索(DFS)用于图的遍历?
答案:
def dfs(graph, start, visited=None):if visited is None:visited = set()visited.add(start)for next in graph[start] - visited:dfs(graph, next, visited)return visited
- 问题:在Python中如何使用广度优先搜索(BFS)找到图中从起点到终点的最短路径?
答案:
from collections import dequedef bfs_shortest_path(graph, start, goal):explored = set()queue = deque([(start, [start])])while queue:current, path = queue.popleft()if current == goal:return pathfor next in graph[current]:if next not in explored:explored.add(next)queue.append((next, path + [next]))return None
- 问题:如何在Python中检测有向图中的环?
答案:
def detect_cycle(graph):WHITE, GRAY, BLACK = 0, 1, 2color = {u: WHITE for u in graph}def dfs(node):if color[node] == GRAY:return Trueif color[node] == BLACK:return Falsecolor[node] = GRAYfor neighbour in graph[node]:if dfs(neighbour):return Truecolor[node] = BLACKreturn Falsefor node in graph:if color[node] == WHITE:if dfs(node):return Truereturn False
- 问题:如何在Python中实现Floyd-Warshall算法?
答案:
def floyd_warshall(weights):V = len(weights)dist = list(map(lambda i: list(map(lambda j: j, i)), weights))for k in range(V):for i in range(V):for j in range(V):dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])return dist
- 问题:如何在Python中实现Dijkstra算法?
答案:
import heapqdef dijkstra(graph, start):min_dist = {vertex: float('infinity') for vertex in graph}min_dist[start] = 0pq = [(0, start)]while pq:current_dist, current_vertex = heapq.heappop(pq)if current_dist > min_dist[current_vertex]:continuefor neighbor, weight in graph[current_vertex].items():distance = current_dist + weightif distance < min_dist[neighbor]:min_dist[neighbor] = distanceheapq.heappush(pq, (distance, neighbor))return min_dist
- 问题:如何在Python中找出数组中的第k个最大元素?
答案:
import heapqdef findKthLargest(nums, k):return heapq.nlargest(k, nums)[-1]
- 问题:在Python中如何实现并查集?
答案:
class UnionFind:def __init__(self, size):self.root = [i for i in range(size)]def find(self, x):while x != self.root[x]:x = self.root[x]return xdef union(self, x, y):rootX = self.find(x)rootY = self.find(y)if rootX != rootY:self.root[rootY] = rootXdef connected(self, x, y):return self.find(x) == self.find(y)
- 问题:如何在Python中实现二叉搜索树的插入操作?
答案:
class TreeNode:def __init__(self, val=0, left=None, right=None):self.val = valself.left = leftself.right = rightdef insert_into_bst(root, val):if not root:return TreeNode(val)if val < root.val:root.left = insert_into_bst(root.left, val)else:root.right = insert_into_bst(root.right, val)return root
- 问题:如何在Python中实现二叉树的后序遍历?
答案:
def postorder_traversal(root):result = []if root:result += postorder_traversal(root.left)result += postorder_traversal(root.right)result.append(root.val)return result
- 问题:如何在Python中找到未排序数组中的最长连续序列?
答案:
def longest_consecutive(nums):num_set = set(nums)longest = 0for num in num_set:if num - 1 not in num_set:current_num = numcurrent_streak = 1while current_num + 1 in num_set:current_num += 1current_streak += 1longest = max(longest, current_streak)return longest
- 问题:在Python中如何实现线性查找?
答案:
def linear_search(arr, x):for i in range(len(arr)):if arr[i] == x:return ireturn -1
- 问题:如何在Python中实现插入排序算法?
答案:
def insertion_sort(arr):for i in range(1, len(arr)):key = arr[i]j = i - 1while j >= 0 and key < arr[j]:arr[j + 1] = arr[j]j -= 1arr[j + 1] = keyreturn arr
- 问题:在Python中如何实现选择排序算法?
答案:
def selection_sort(arr):for i in range(len(arr)):min_idx = ifor j in range(i+1, len(arr)):if arr[min_idx] > arr[j]:min_idx = jarr[i], arr[min_idx] = arr[min_idx], arr[i]return arr
- 问题:如何在Python中找到数组中的峰值元素?
答案:
def find_peak_element(nums):left, right = 0, len(nums) - 1while left < right:mid = (left + right) // 2if nums[mid] > nums[mid + 1]:right = midelse:left = mid + 1return left
- 问题:在Python中如何实现桶排序算法?
答案:
def bucket_sort(arr):max_value = max(arr)size = max_value // len(arr)buckets = [[] for _ in range(size)]for i in range(len(arr)):j = arr[i] // sizeif j != size:buckets[j].append(arr[i])else:buckets[size - 1].append(arr[i])for i in range(size):insertion_sort(buckets[i])result = []for i in range(size):result = result + buckets[i]return result
- 问题:如何在Python中实现计算一个数的幂?
答案:
def power(x, n):if n == 0:return 1elif n % 2 == 0:return power(x, n // 2) ** 2else:return x * power(x, n // 2) ** 2
- 问题:在Python中如何在一个包含从0到n的整数的数组中找到缺失的数字?
答案:
def missing_number(nums):n = len(nums)expected_sum = n * (n + 1) // 2actual_sum = sum(nums)return expected_sum - actual_sum
- 问题:在Python中如何实现二叉树的前序遍历?
答案:
def preorder_traversal(root):result = []if root:result.append(root.val)result += preorder_traversal(root.left)result += preorder_traversal(root.right)return result
- 问题:如何在Python中实现一个简单的散列表?
答案:
class HashTable:def __init__(self, size):self.size = sizeself.table = [None] * sizedef hash_function(self, key):return key % self.sizedef insert(self, key, value):hash_index = self.hash_function(key)self.table[hash_index] = valuedef get(self, key):hash_index = self.hash_function(key)return self.table[hash_index]
- 问题:在Python中如何找到第n个斐波那契数?
答案:
def fibonacci(n):a, b = 0, 1for _ in range(n):a, b = b, a + breturn a