分享

Python LZW 算法 | 菜鸟教程

 dinghj 2019-09-29

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

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多