class Graph:
def __init__(self):
self.nodes = set()
self.edges = {}
def add_node(self, node):
self.nodes.add(node)
self.edges[node] = []
def add_edge(self, from_node, to_node, weight=1):
if from_node not in self.nodes or to_node not in self.nodes:
raise ValueError("Both nodes need to be in graph")
self.edges[from_node].append((to_node, weight))
self.edges[to_node].append((from_node, weight))
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 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)
搜索算法:适用于需要在大量数据中查找特定元素的情况。例如,线性搜索、二分搜索等。
线性搜索 :这是一种简单的搜索算法,它遍历整个数组,比较每个元素与目标元素,如果匹配则返回该元素。
python复制代码
def linear_search(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return i
return -1
def dijkstra(graph, start_vertex):
D = {v:float('infinity') for v in graph}
D[start_vertex] = 0
queue = [(0, start_vertex)]
while queue:
current_distance, current_vertex = min(queue, key=lambda x:x[0])
queue.remove((current_distance, current_vertex))
if current_distance > D[current_vertex]:
continue
for neighbor, weight in graph[current_vertex].items():
old_distance = D[neighbor]
new_distance = current_distance + weight
if new_distance < oldDistance:
D[neighbor] = newDistance
queue.append((newDistance, neighbor))
return D #returns dictionary of shortest distances from start node to every other node in the graph.
def knapsack(weights, values, W):
n = len(weights)
dp = [[0 for _ in range(W+1)] for _ in range(n+1)]
for i in range(1, n+1):
for w in range(1, W+1):
if weights[i-1] <= w:
dp[i][w] = max(dp[i-1][w], dp[i-1][w-weights[i-1]] + values[i-1])
else:
dp[i][w] = dp[i-1][w]
return dp[n][W]
class HuffmanNode:
def __init__(self, freq, char=None):
self.freq = freq
self.char = char
self.left = None
self.right = None
self.huff = None
def __cmp__(self, other):
if(other == None):
return -1
if(self.freq == other.freq):
return 0
elif(self.freq > other.freq):
return 1
else:
return -1
def build_heap(arr):
n = len(arr)
for i in range(n//2 - 1, -1, -1):
heapify(arr, n, i)
def heapify(arr, n, i):
smallest = i
left = 2*i + 1
right = 2*i + 2
if left < n and arr[smallest].freq > arr[left].freq:
smallest = left
if right < n and arr[smallest].freq < arr[right].freq:
smallest = right
if smallest != i:
arr[i], arr[smallest] = arr[smallest], arr[i] # swap
heapify(arr, n, smallest) # call heapify for the smallest element at root.
def huffman_encode(arr):
arr_min = None # to store the minimum frequency object
heap = [] # to store the heap minimum at the root of heap. //创建最小堆,根节点为最小值。 //将数组转化为最小堆。 build_heap(heap) for item in arr: heap.append(item) build_heap(heap) //删除重复的元素 arr_min = heap[0] //将频率最小的元素移除 heap.remove(arr_min) //添加到 huffman tree 中 if arr_min.charif arr_min.char == None:
arr_min = heap[0]
heap.remove(arr_min)
tree.add_node(arr_min)
else:
tree.add_node(arr_min)
heap.remove(arr_min)
# The function to print the binary tree.
def print_binary_tree(root):
if root is not None:
print_binary_tree(root.left)
print(root.data, end=" ")
print_binary_tree(root.right)
# The main function to find the Huffman编码 of a string.
def find_huffman_encoding(text):
# Create a frequency table for all characters in the text.
char_freq = {}
for char in text:
char_freq[char] = char_freq.get(char, 0) + 1
# Create a priority queue to store the nodes of the Huffman tree.
# The priority of a node is defined by the sum of the frequencies
# of its two children.
pq = []
for char, freq in char_freq.items():
pq.append((freq, char))
heapq.heapify(pq)
# Create an empty Huffman tree and add the nodes to it in a way
# that maintains the property that the priority of a node is
# defined by the sum of the frequencies of its two children.
while len(pq) > 1:
left = heapq.heappop(pq)
right = heapq.heappop(pq)
merge_node = HuffmanNode(left[0] + right[0], None)
merge_node.left = HuffmanNode(left[0], left[1])
merge_node.right = HuffmanNode(right[0], right[1])
heapq.heappush(pq, merge_node)
# The last element in the priority queue is the root of the Huffman tree.
root = pq[-1]
# Now, we can build the Huffman encoding by traversing the Huffman tree.
huff_enc = []
print_binary_tree(root)print("Huffman encoding for text: ")
huff_enc.reverse() # reverse the list because the traversal is in reverse order.
print(huff_enc)