Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Is that for kids?! solution in Uncategorized category for Huffman Encode by Kolia951
import collections
def huffman_encode(text: str) -> str:
if len(set(text)) == 1:
return "0" * len(text)
binary_path = collections.defaultdict(str)
huffman_code = ""
tree = [(i, text.count(i)) for i in set(text)]
tree.sort(key=lambda x: (x[1],x[0]), reverse=True)
while len(tree) > 1:
r = tree.pop()
l = tree.pop()
for symbol in r[0]:
binary_path[symbol] += "0"
for symbol in l[0]:
binary_path[symbol] += "1"
tree.append((r[0]+l[0], r[1] + l[1]))
tree.sort(key=lambda x: (x[1],x[0]), reverse=True)
for letter in text:
huffman_code += binary_path[letter][::-1]
return huffman_code
if __name__ == "__main__":
print("Example:")
print(huffman_encode("BADABUM"))
# These "asserts" are used for self-checking and not for an auto-testing
assert huffman_encode("BADABUM") == "1001110011000111"
assert (
huffman_encode("A DEAD DAD CEDED A BAD BABE A BEADED ABACA BED")
== "1000011101001000110010011101100111001001000111110010011111011111100010001111110100111001001011111011101000111111001"
)
assert (
huffman_encode("no devil lived on")
== "100101111000001110010011111011010110001000111101100"
)
assert huffman_encode("an assassin sins") == "110111100110001100010111110001011110"
print("Huffman Encode coding complete? Click 'Check' to earn cool rewards!")
Jan. 30, 2023