Created
May 31, 2015 23:16
-
-
Save senarukana/1a893ff8c09f911b7d5e to your computer and use it in GitHub Desktop.
encode words
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class InvalidException(Exception): | |
pass | |
def encode1(words): | |
res = "" | |
for word in words: | |
res += str(len(word)) + ':' + word | |
return res | |
def decode1(s): | |
n, i, words = len(s), 0, [] | |
while i < len(s): | |
idx = s.find(':', i) | |
if idx == -1: | |
raise InvalidException | |
try: | |
m = int(s[i:idx]) | |
if m+idx+1 > n: | |
raise InvalidException | |
words.append(s[idx+1:idx+m+1]) | |
except ValueError: | |
raise InvalidException | |
i = idx+m+1 | |
return words | |
def encode2(words): | |
res = "" | |
for word in words: | |
for c in word: | |
if c != '\t': | |
res += c | |
else: | |
res += '\t\t' | |
res += '\t\n' | |
return res | |
def decode2(s): | |
i, n, word, words = 0, len(s), "", [] | |
while i < n: | |
if s[i] != '\t': | |
word += s[i] | |
else: | |
if i+1 < n and s[i+1] == '\t': | |
word += '\t' | |
elif i+1 < n and s[i+1] == '\n': | |
words.append(word) | |
word = "" | |
else: | |
raise InvalidException | |
i += 1 | |
i += 1 | |
return words | |
words = ['abc', 'a', 't\t\t'] | |
s = encode2(words) | |
print s | |
print decode2(s) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment