當前位置:
首頁 > 知識 > Python LZW 演算法

Python LZW 演算法

Python LZW 演算法

LZW 壓縮演算法

string = "thisisthe"
dictionary = {chr(i):i for i in range(97,123)}

last = 256
p = ""
result = []

for c in string:
pc = p+c
if pc in dictionary:
p = pc
else:
result.append(dictionary[p])
dictionary[pc] = last
last += 1
p = c

if p != "":
result.append(dictionary[p])

print(result)

以上代碼運行結果為:

[116, 104, 105, 115, 258, 256, 101]

LZW 解壓縮演算法

dictionary = {i:chr(i) for i in range(97,123)}
last = 256
arr = [97, 97, 98, 256, 258, 257, 259]

result = []
p = arr.pop(0)
result.append(dictionary[p])

for c in arr:
if c in dictionary:
entry = dictionary[c]
result.append(entry)
dictionary[last] = dictionary[p] + entry[0]
last += 1
p = c

print("".join(result))

以上代碼運行結果為:

aabaabaabaab

Python LZW 演算法

喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 程序員小新人學習 的精彩文章:

Windows下BVLC Caffe的安裝與配置
python解包和壓包

TAG:程序員小新人學習 |