Python面试题【数据结构和算法部分161-200】 Python面试题【数据结构和算法部分161-200】
Python面试题【数据结构和算法部分161-200】
问题:如何在Python中找到最近公共祖先(LCA)? 答案:
class TreeNode : def __init__ ( self, x) : self. val = xself. left = None self. right = None def lowest_common_ancestor ( root, p, q) : if not root or root == p or root == q: return rootleft = lowest_common_ancestor( root. left, p, q) right = lowest_common_ancestor( root. right, p, q) if left and right: return rootreturn left if left else right
问题:如何在Python中实现计数质数的功能? 答案:
def count_primes ( n) : if n < 2 : return 0 primes = [ True ] * nprimes[ 0 ] = primes[ 1 ] = False for i in range ( 2 , int ( n ** 0.5 ) + 1 ) : if primes[ i] : primes[ i* i: n: i] = [ False ] * len ( primes[ i* i: n: i] ) return sum ( primes)
问题:在Python中如何有效地实现斐波那契数列? 答案:
def fibonacci ( n, memo= { } ) : if n in memo: return memo[ n] if n <= 2 : return 1 memo[ n] = fibonacci( n- 1 , memo) + fibonacci( n- 2 , memo) return memo[ n]
问题:如何在Python中实现一个简单的散列表? 答案:
class HashTable : def __init__ ( self) : self. MAX = 100 self. arr = [ None for i in range ( self. MAX) ] def get_hash ( self, key) : h = 0 for char in key: h += ord ( char) return h % self. MAXdef add ( self, key, value) : h = self. get_hash( key) self. arr[ h] = valuedef get ( self, key) : h = self. get_hash( key) return self. arr[ h]
问题:Python中的动态规划是如何工作的? 答案:
动态规划是一种算法思想,用于解决具有重叠子问题和最优子结构特性的问题。通过将问题分解为更小的子问题,并存储这些子问题的解(通常是在一个数组或字典中),动态规划避免了重复计算子问题,从而提高了效率。
问题:如何在Python中找到数组中重复的数字? 答案:
def find_duplicates ( nums) : seen = set ( ) duplicates = set ( ) for num in nums: if num in seen: duplicates. add( num) else : seen. add( num) return list ( duplicates)
问题:如何在Python中检测链表中的环? 答案:
class ListNode : def __init__ ( self, val= 0 , next = None ) : self. val = valself. next = next def has_cycle ( head) : slow = headfast = headwhile fast and fast. next : slow = slow. next fast = fast. next . next if slow == fast: return True return False
问题:在Python中如何使用递归进行二叉树的中序遍历? 答案:
def inorder_traversal ( root) : res = [ ] def inorder ( node) : if not node: return inorder( node. left) res. append( node. val) inorder( node. right) inorder( root) return res
问题:如何在Python中合并两个有序链表? 答案:
class ListNode : def __init__ ( self, val= 0 , next = None ) : self. val = valself. next = next def merge_two_lists ( l1, l2) : dummy = ListNode( ) tail = dummywhile l1 and l2: if l1. val < l2. val: tail. next , l1 = l1, l1. next else : tail. next , l2 = l2, l2. next tail = tail. next tail. next = l1 or l2return dummy. next
问题:如何在Python中找到字符串中的所有排列? 答案:
from itertools import permutationsdef all_permutations ( s) : return [ '' . join( p) for p in permutations( s) ]
问题:如何在Python中使用动态规划求解背包问题? 答案:
def knapSack ( W, wt, val, 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中如何实现二分查找树的删除操作? 答案:
class TreeNode : def __init__ ( self, key) : self. left = None self. right = None self. val = keydef deleteNode ( root, key) : if root is None : return rootif key < root. val: root. left = deleteNode( root. left, key) elif ( key > root. val) : root. right = deleteNode( root. right, key) else : if root. left is None : temp = root. rightroot = None return tempelif root. right is None : temp = root. leftroot = None return temptemp = minValueNode( root. right) root. val = temp. valroot. right = deleteNode( root. right, temp. val) return rootdef minValueNode ( node) : current = nodewhile ( current. left is not None ) : current = current. leftreturn current
问题:Python中如何实现图的拓扑排序? 答案:
from collections import defaultdictclass Graph : def __init__ ( self, vertices) : self. graph = defaultdict( list ) self. V = verticesdef addEdge ( self, u, v) : self. graph[ u] . append( v) def topologicalSortUtil ( self, v, visited, stack) : visited[ v] = True for i in self. graph[ v] : if visited[ i] == False : self. topologicalSortUtil( i, visited, stack) stack. insert( 0 , v) def topologicalSort ( self) : visited = [ False ] * self. Vstack = [ ] for i in range ( self. V) : if visited[ i] == False : self. topologicalSortUtil( i, visited, stack) print ( stack)
问题:如何在Python中找出数组中重复出现的所有元素? 答案:
def findDuplicates ( nums) : duplicates = [ ] for num in nums: if nums[ abs ( num) - 1 ] < 0 : duplicates. append( abs ( num) ) else : nums[ abs ( num) - 1 ] *= - 1 return duplicates
问题:在Python中如何实现深度优先搜索(DFS)用于解决迷宫问题? 答案:
def solveMaze ( maze) : def dfs ( x, y) : if x < 0 or x >= len ( maze) or y < 0 or y >= len ( maze[ 0 ] ) or maze[ x] [ y] == 1 : return False if maze[ x] [ y] == 'E' : return True maze[ x] [ y] = 1 if dfs( x+ 1 , y) or dfs( x- 1 , y) or dfs( x, y+ 1 ) or dfs( x, y- 1 ) : return True return False for i in range ( len ( maze) ) : for j in range ( len ( maze[ 0 ] ) ) : if maze[ i] [ j] == 'S' : return dfs( i, j) return False
问题:Python中如何实现数组的旋转? 答案:
def rotate_array ( nums, k) : n = len ( nums) k = k % nnums[ : ] = nums[ n- k: ] + nums[ : n- k]
问题:如何在Python中实现链表排序? 答案:
class ListNode : def __init__ ( self, val= 0 , next = None ) : self. val = valself. next = next def sortList ( head) : if not head or not head. next : return headslow, fast = head, head. next while fast and fast. next : slow = slow. next fast = fast. next . next mid = slow. next slow. next = None left, right = sortList( head) , sortList( mid) return merge( left, right) def merge ( l1, l2) : dummy = ListNode( 0 ) tail = dummywhile l1 and l2: if l1. val < l2. val: tail. next , l1 = l1, l1. next else : tail. next , l2 = l2, l2. next tail = tail. next tail. next = l1 or l2return dummy. next
问题:如何在Python中找到前K个高频元素? 答案:
import heapqfrom collections import Counterdef topKFrequent ( nums, k) : count = Counter( nums) return heapq. nlargest( k, count. keys( ) , key= count. get)
问题:在Python中如何实现两数之和? 答案:
def twoSum ( nums, target) : seen = { } for i, num in enumerate ( nums) : if target - num in seen: return [ seen[ target - num] , i] seen[ num] = i
问题:如何在Python中找到最小路径和? 答案:
def minPathSum ( grid) : for i in range ( len ( grid) ) : for j in range ( len ( grid[ 0 ] ) ) : if i == 0 and j == 0 : continue elif i == 0 : grid[ i] [ j] += grid[ i] [ j- 1 ] elif j == 0 : grid[ i] [ j] += grid[ i- 1 ] [ j] else : grid[ i] [ j] += min ( grid[ i- 1 ] [ j] , grid[ i] [ j- 1 ] ) return grid[ - 1 ] [ - 1 ]
问题:如何在Python中实现一个最大堆? 答案:
import heapqclass MaxHeap : def __init__ ( self) : self. heap = [ ] def push ( self, val) : heapq. heappush( self. heap, - val) def pop ( self) : return - heapq. heappop( self. heap) def peek ( self) : return - self. heap[ 0 ]
问题:在Python中如何实现一个图的深度优先搜索(DFS)来检测环? 答案:
def detect_cycle_dfs ( graph) : def dfs ( node, visited, rec_stack) : visited[ node] = True rec_stack[ node] = True for neighbour in graph[ node] : if not visited[ neighbour] : if dfs( neighbour, visited, rec_stack) : return True elif rec_stack[ neighbour] : return True rec_stack[ node] = False return False visited = [ False ] * len ( graph) rec_stack = [ False ] * len ( graph) for node in range ( len ( graph) ) : if not visited[ node] : if dfs( node, visited, rec_stack) : return True return False
问题:如何在Python中实现一个简单的LRU缓存? 答案:
from collections import OrderedDictclass LRUCache : def __init__ ( self, capacity: int ) : self. cache = OrderedDict( ) self. capacity = capacitydef get ( self, key: int ) - > int : if key not in self. cache: return - 1 else : self. cache. move_to_end( key) return self. cache[ key] def put ( self, key: int , value: int ) - > None : if key in self. cache: self. cache. move_to_end( key) self. cache[ key] = valueif len ( self. cache) > self. capacity: self. cache. popitem( last= False )
问题:如何在Python中找到一个数组中的所有子集的和? 答案:
def subset_sums ( arr) : sums = [ 0 ] for num in arr: sums += [ num + s for s in sums] return sums
问题:如何在Python中实现一个二叉树的后序遍历迭代器? 答案:
class BSTIterator : def __init__ ( self, root: TreeNode) : self. stack = [ ] self. _leftmost_inorder( root) def _leftmost_inorder ( self, root) : while root: self. stack. append( root) root = root. leftdef next ( self) - > int : topmost_node = self. stack. pop( ) if topmost_node. right: self. _leftmost_inorder( topmost_node. right) return topmost_node. valdef hasNext ( self) - > bool : return len ( self. stack) > 0
问题:如何在Python中实现一个字符串的所有排列的迭代器? 答案:
from itertools import permutationsclass PermutationIterator : def __init__ ( self, string) : self. permutations = permutations( string) self. index = 0 def next ( self) : if self. index < len ( self. permutations) : result = '' . join( self. permutations[ self. index] ) self. index += 1 return resultelse : raise StopIterationdef hasNext ( self) : return self. index < len ( self. permutations)
问题:如何在Python中实现一个简单的文本模式匹配算法? 答案:
def text_search ( text, pattern) : for i in range ( len ( text) - len ( pattern) + 1 ) : if text[ i: i+ len ( pattern) ] == pattern: return ireturn - 1
问题:如何在Python中实现一个简单的加权图的Dijkstra算法? 答案:
import heapqdef dijkstra ( graph, start) : distances = { vertex: float ( 'infinity' ) for vertex in graph} distances[ start] = 0 pq = [ ( 0 , start) ] while pq: current_distance, current_vertex = heapq. heappop( pq) if current_distance > distances[ current_vertex] : continue for neighbor, weight in graph[ current_vertex] . items( ) : distance = current_distance + weightif distance < distances[ neighbor] : distances[ neighbor] = distanceheapq. heappush( pq, ( distance, neighbor) ) return distances
问题:如何在Python中实现一个简单的正则表达式匹配算法? 答案:
def is_match ( text, pattern) : if not pattern: return not textfirst_match = bool ( text) and pattern[ 0 ] in { text[ 0 ] , '.' } if len ( pattern) >= 2 and pattern[ 1 ] == '*' : return ( is_match( text, pattern[ 2 : ] ) or first_match and is_match( text[ 1 : ] , pattern) ) else : return first_match and is_match( text[ 1 : ] , pattern[ 1 : ] )
问题:如何在Python中实现一个简单的表达式求值算法? 答案:
def evaluate_expression ( expr) : def calc ( op, second, first) : if op == '+' : return first + secondif op == '-' : return first - secondif op == '*' : return first * secondif op == '/' : return first // secondstack = [ ] num = '' precedence = { '+' : 1 , '-' : 1 , '*' : 2 , '/' : 2 } operators = set ( '+-*/' ) for c in expr: if c. isdigit( ) : num += celif c in operators: while ( stack and stack[ - 1 ] in operators and precedence[ stack[ - 1 ] ] >= precedence[ c] ) : stack. append( calc( stack. pop( ) , stack. pop( ) , stack. pop( ) ) ) stack. append( num) num = '' stack. append( c) if num: stack. append( num) while len ( stack) > 1 : stack. append( calc( stack. pop( ) , stack. pop( ) , stack. pop( ) ) ) return stack[ 0 ]
问题:如何在Python中实现一个双向链表? 答案:
class ListNode : def __init__ ( self, value= 0 , prev= None , next = None ) : self. value = valueself. prev = prevself. next = next class DoublyLinkedList : def __init__ ( self) : self. head = ListNode( 0 ) self. tail = ListNode( 0 , self. head) self. head. next = self. taildef insert ( self, value) : node = ListNode( value, self. tail. prev, self. tail) self. tail. prev. next = nodeself. tail. prev = nodedef delete ( self, node) : node. prev. next = node. next node. next . prev = node. prev
问题:如何在Python中检测一个数组中是否存在重复元素? 答案:
def contains_duplicate ( nums) : return len ( nums) != len ( set ( nums) )
问题:在Python中如何实现一个基本的哈希映射? 答案:
class HashMap : def __init__ ( self) : self. size = 1000 self. table = [ [ ] for _ in range ( self. size) ] def _hash ( self, key) : return hash ( key) % self. sizedef put ( self, key, value) : hash_key = self. _hash( key) for i, ( k, v) in enumerate ( self. table[ hash_key] ) : if k == key: self. table[ hash_key] [ i] = ( key, value) return self. table[ hash_key] . append( ( key, value) ) def get ( self, key) : hash_key = self. _hash( key) for ( k, v) in self. table[ hash_key] : if k == key: return vreturn - 1 def remove ( self, key) : hash_key = self. _hash( key) for i, ( k, v) in enumerate ( self. table[ hash_key] ) : if k == key: del self. table[ hash_key] [ i]
问题:如何在Python中实现快速幂算法? 答案:
def fast_power ( base, power) : result = 1 while power > 0 : if power % 2 == 1 : result *= basebase *= basepower //= 2 return result
问题:如何在Python中实现一个简单的字符串哈希函数? 答案:
def string_hash ( s, mod) : hash_val = 0 p = 31 p_power = 1 for char in s: hash_val = ( hash_val + ( ord ( char) - ord ( 'a' ) + 1 ) * p_power) % modp_power = ( p_power * p) % modreturn hash_val
问题:如何在Python中找到一个数的所有正因数? 答案:
def find_factors ( n) : factors = [ ] for i in range ( 1 , int ( n** 0.5 ) + 1 ) : if n % i == 0 : factors. append( i) if i != n // i: factors. append( n // i) return factors
问题:如何在Python中实现一个简单的计算器解析器? 答案:
def calculate ( s) : num, stack, sign = 0 , [ ] , '+' for i in range ( len ( s) ) : if s[ i] . isdigit( ) : num = num * 10 + int ( s[ i] ) if s[ i] in '+-*/' or i == len ( s) - 1 : if sign == '+' : stack. append( num) elif sign == '-' : stack. append( - num) elif sign == '*' : stack. append( stack. pop( ) * num) else : stack. append( int ( stack. pop( ) / num) ) num = 0 sign = s[ i] return sum ( stack)
问题:如何在Python中实现二叉树的层序遍历? 答案:
from collections import dequedef level_order ( root) : if not root: return [ ] result, queue = [ ] , deque( [ root] ) while queue: level = [ ] for _ in range ( len ( queue) ) : node = queue. popleft( ) level. append( node. val) if node. left: queue. append( node. left) if node. right: queue. append( node. right) result. append( level) return result
问题:如何在Python中实现一个简单的前缀和数组? 答案:
def prefix_sum ( nums) : prefix_sums = [ 0 ] * ( len ( nums) + 1 ) for i in range ( len ( nums) ) : prefix_sums[ i+ 1 ] = prefix_sums[ i] + nums[ i] return prefix_sums
问题:如何在Python中实现一个简单的后缀和数组? 答案:
def suffix_sum ( nums) : suffix_sums = [ 0 ] * ( len ( nums) + 1 ) for i in range ( len ( nums) - 1 , - 1 , - 1 ) : suffix_sums[ i] = suffix_sums[ i+ 1 ] + nums[ i] return suffix_sums