Merge branch 'master' of gitlab.com:shockrahwow/csnotes
This commit is contained in:
31
370/homework/huff.py
Normal file
31
370/homework/huff.py
Normal file
@@ -0,0 +1,31 @@
|
||||
class Node():
|
||||
def __init__(self, c, weight):
|
||||
self.c = c
|
||||
self.freq = weight
|
||||
self.left = None
|
||||
self.right = None
|
||||
|
||||
def __repr__(self):
|
||||
return f'{self.c}|{self.freq}'
|
||||
|
||||
class Huffman:
|
||||
def __init__(self, string):
|
||||
self.heap = []
|
||||
self.charMap = self.charFrequencies(string)
|
||||
|
||||
def charFrequencies(self, string):
|
||||
ret = []
|
||||
for i in string:
|
||||
if i in ret:
|
||||
ret[i] += 1
|
||||
else:
|
||||
ret[i] = 1
|
||||
return ret.sort()
|
||||
|
||||
if __name__ == '__main__':
|
||||
text = input()
|
||||
binary = input()
|
||||
|
||||
# encode the first given string to build a tree from it
|
||||
huff = Huffman(text)
|
||||
print(huff.charMap)
|
||||
@@ -4,14 +4,14 @@ import heapq
|
||||
class Node:
|
||||
def __init__(self, c, weight):
|
||||
self.c = c
|
||||
self.weight = weight
|
||||
self.freq = weight
|
||||
self.left = None
|
||||
self.right = None
|
||||
|
||||
self.code = ''
|
||||
|
||||
def __repr__(self):
|
||||
return f'{self.c}|{self.weight}'
|
||||
return f'{self.c}|{self.freq}'
|
||||
|
||||
def __lt__(self, other):
|
||||
return self.weight < other.weight
|
||||
@@ -27,7 +27,7 @@ def frequencyMap(string):
|
||||
# otherwise increment the frequency of that node
|
||||
for k in ret:
|
||||
if k.c == i:
|
||||
k.weight += 1
|
||||
k.freq += 1
|
||||
|
||||
# Sort the charmap alphabetically
|
||||
ret.sort(key=lambda x: x.c)
|
||||
|
||||
Reference in New Issue
Block a user