I decided to try and make a Huffman Tree program. So far, I've managed to have it produce a list of all the weighted outputs (which I believe is correct), but I'm having difficulties presenting this in a viewable format.
I messed with a recursive object I made called 'Node', but I know I've done something wrong, and the output is nonsensical. My code is as below:
main.py
:
import sys
word = ' '.join(sys.argv[1:])
freq = {}
for char in word:
if char in freq.keys():
freq[char] += 1
else:
freq[char] = 1
freq = [[x, y] for x, y in freq.items()]
freq.sort(key=lambda x: x[1])
while len(freq) != 1:
freq[1][0] = [freq[0][0], freq[1][0]]
freq[1][1] = freq[0][1] + freq[1][1]
freq.pop(0)
freq.sort(key=lambda x: x[1])
print(freq[0][0])
freq = freq[0][0]
class Node(object):
value = None
def __init__(self, li):
if type(li) not in [tuple, list, set, dict]:
self.value = li
else:
if len(li) != 2:
raise ValueError('\'Node\' object only takes 2-part iterables or raw values as an argument')
self.left = Node(li[0])
self.right = Node(li[1])
def __repr__(self):
if self.value != None:
return '"' + str(self.value) + '"'
return ' ' * self.left.size() + '|' + self.right.size() * ' ' + '\n' + str(self.left) + str(self.right)
def size(self):
if self.value != None:
return 1
return self.left.size() + self.right.size()
n = Node(freq)
print(n)
I'm currently not so bothered about errors in my actual Huffman creation code, since it'll be easier for me to go back and fix these once I can view the output nicer.
Example in/out:
she sells sea shells on the sea shore
produces:
[[' ', ['h', 'l']], ['s', [[['t', ['n', 'r']], ['a', 'o']], 'e']]]
or,
|
|
" " |
"h""l" |
"s" |
|
|
"t" |
"n""r" |
"a""o""e"
(clearly unclear 'tree' thing)