import heapq import numpy as np from typing import List class Node: def __init__(self, p, s): self.left = None self.right = None self.symbol = s self.prob = p def __lt__(self, other): return self.prob < other.prob def __repr__(self): return "Node({})".format(repr([self.prob, self.symbol])) def buildingHeap(P, S): heap = [] for p,s in zip(P,S): heap.append(Node(p,s)) heapq.heapify(heap) while len(heap) > 1: r1 = heapq.heappop(heap) r2 = heapq.heappop(heap) newN = Node(r1.prob+r2.prob, r1.symbol+r2.symbol) newN.left = r1 newN.right = r2 heapq.heappush(heap, newN) print(heap) return heap def encode(top, dict_code, code): if top.left is None and top.right is None: dict_code[top.symbol] = code else: encode(top.left, dict_code, code + '0') encode(top.right, dict_code, code + '1') def p1(S: List[str], P: List[float]) -> List[float]: dict_code = dict((S[i],'') for i in range(len(S))) heap = buildingHeap(P,S) encode(heap[0],dict_code, '') print(dict_code) lmed = 0 Hs = 0 K = 0 for i in range(len(S)): lmed += P[i]*len(dict_code[S[i]]) Hs += -1*P[i]*np.log2(P[i]) K += pow(2,-len(dict_code[S[i]])) Hs = round(Hs,2) print(Hs) lmin = Hs niu = float(format((lmin/lmed), ".2f")) return [lmed, niu, K] print(p1(['s1','s2','s3', 's4', 's5', 's6'],[0.3,0.1,0.05,0.25,0.2, 0.1]))
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question