This action will force synchronization from 编程语言算法集/Python, which will overwrite any changes that you have made since you forked the repository, and can not be recovered!!!
Synchronous operation will process in the background and will refresh the page when finishing processing. Please be patient.
compression (#5570)
from __future__ import annotationsimport sysclass Letter:def __init__(self, letter: str, freq: int):self.letter: str = letterself.freq: int = freqself.bitstring: dict[str, str] = {}def __repr__(self) -> str:return f"{self.letter}:{self.freq}"class TreeNode:def __init__(self, freq: int, left: Letter | TreeNode, right: Letter | TreeNode):self.freq: int = freqself.left: Letter | TreeNode = leftself.right: Letter | TreeNode = rightdef parse_file(file_path: str) -> list[Letter]:"""Read the file and build a dict of all letters and theirfrequencies, then convert the dict into a list of Letters."""chars: dict[str, int] = {}with open(file_path) as f:while True:c = f.read(1)if not c:breakchars[c] = chars[c] + 1 if c in chars.keys() else 1return sorted((Letter(c, f) for c, f in chars.items()), key=lambda l: l.freq)def build_tree(letters: list[Letter]) -> Letter | TreeNode:"""Run through the list of Letters and build the min heapfor the Huffman Tree."""response: list[Letter | TreeNode] = letters # type: ignorewhile len(response) > 1:left = response.pop(0)right = response.pop(0)total_freq = left.freq + right.freqnode = TreeNode(total_freq, left, right)response.append(node)response.sort(key=lambda l: l.freq)return response[0]def traverse_tree(root: Letter | TreeNode, bitstring: str) -> list[Letter]:"""Recursively traverse the Huffman Tree to set eachLetter's bitstring dictionary, and return the list of Letters"""if type(root) is Letter:root.bitstring[root.letter] = bitstringreturn [root]treenode: TreeNode = root # type: ignoreletters = []letters += traverse_tree(treenode.left, bitstring + "0")letters += traverse_tree(treenode.right, bitstring + "1")return lettersdef huffman(file_path: str) -> None:"""Parse the file, build the tree, then run through the fileagain, using the letters dictionary to find and print out thebitstring for each letter."""letters_list = parse_file(file_path)root = build_tree(letters_list)letters = {k: v for letter in traverse_tree(root, "") for k, v in letter.bitstring.items()}print(f"Huffman Coding of {file_path}: ")with open(file_path) as f:while True:c = f.read(1)if not c:breakprint(letters[c], end=" ")print()if __name__ == "__main__":# pass the file path to the huffman functionhuffman(sys.argv[1])
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。