def compress(string):
# Get the unique characters and numeric base.
unique = set(string)
base = len(unique)
# Create a key that will encode data properly.
key = random.sample(unique, base)
mapping = dict(map(reversed, enumerate(key)))
while not mapping[string[-1]]:
key = random.sample(unique, base)
mapping = dict(map(reversed, enumerate(key)))
# Create a compressed numeric representation.
value = 0
for place, char in enumerate(string):
value += mapping[char] * base ** place
# Return the number as a string with the table.
return decode(value), bytes(key)
评论列表
文章目录