-
Notifications
You must be signed in to change notification settings - Fork 0
/
lzw.py
72 lines (50 loc) · 1.56 KB
/
lzw.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# sentence = "wabba wabba wabba wabba woo woo woo"
# sentence = 'a bar array by barryar bay'
# sentence = 'woo woo'
sentence = raw_input('Enter string to encode and decode: ')
dictionary = [0]
print 'Index\tEntry\tEncoded Symbol'
for letter in sentence:
if letter not in dictionary:
dictionary.append(letter)
print dictionary.index(letter), "\t", letter
dictionary.sort()
initial_dictionary = dictionary[:]
# Encoding
encoded = []
i = 0
while i < len(sentence):
letter = sentence[i]
if i <= len(sentence) - 1:
j = i + 1
combined = letter
i = i + 1
while j < len(sentence):
next_letter = sentence[j]
combined = combined + next_letter
j = j + 1
if combined not in dictionary:
dictionary.append(combined)
print dictionary.index(combined), "\t", combined,
i = j - 1
break;
word = combined[0:len(combined)-1]
if word in dictionary:
encoded.append(dictionary.index(word))
print "\t", dictionary.index(word)
# Encode the last remaining symbol
encoded.append(dictionary.index(combined[-1]))
print "\t\t", dictionary.index(combined[-1])
print "Encoded string: ", encoded
# Decoding
dictionary = initial_dictionary[:]
decoded_string = ''
previous_decoded = ''
for code in encoded:
decoded = dictionary[code]
decoded_string += decoded
combined = previous_decoded + decoded[0]
if combined not in dictionary:
dictionary.append(combined)
previous_decoded = decoded
print "Decoded String: ", decoded_string