2025年3月31日 星期一 乙巳(蛇)年 正月初一 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Python

Python LZW 算法

时间:02-20来源:作者:点击数:41

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
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门