Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Make it shorter (commented)! solution in Clear category for Huffman Encode by CDG.Axel
def huffman_encode(s: str) -> str:
# code table
code = dict.fromkeys(s, '')
# list of tuples (count, letter)
seq = sorted((s.count(i), i) for i in code)
while len(seq) > 1: # reduce sequence to the end
(lq, ls), (rq, rs), *seq = seq # take two minimal elements
seq = sorted(seq + [(lq + rq, ls + rs)]) # add concatenation
for i in ls + rs: # update code table with 0 for left node
code[i] = '01'[i in rs] + code[i] # update code table with 1 for right node
# there will be no 'while loop' for one different symbols in input
# so code will contain single value '', and "or '0'" construction transform it to zero
return ''.join(code[i] or '0' for i in s)
Dec. 12, 2022
Comments: