from rfc1751wordlist import WORD_LIST, WORD_LIST_SIZE
-# TODO: Decode
+WORD_LIST_INVERTED = {word: i for (i, word) in enumerate(WORD_LIST)}
+assert len(WORD_LIST_INVERTED) == WORD_LIST_SIZE
def encode_actual(x: int) -> list[str]:
return [WORD_LIST[x]] if x == 0 else encode_actual(x)
+def decode(x: list[str]) -> int:
+ return WORD_LIST_SIZE * decode(x[:-1]) + \
+ WORD_LIST_INVERTED[x[-1]] if x else 0
+
+
def main() -> None:
- print(' '.join(encode(int(sys.argv[1]))))
+ if sys.argv[1].isnumeric():
+ print(' '.join(encode(int(sys.argv[1]))))
+ elif len(sys.argv) == 2:
+ print(decode(sys.argv[1].split(' ')))
+ else:
+ print(decode(sys.argv[1:]))
if __name__ == '__main__':
import unittest
-from rfc1751 import encode
+from rfc1751 import encode, decode
class TestRFC1751(unittest.TestCase):
+ def check(self, num: int, words: list[str]) -> None:
+ self.assertEqual(encode(num), words)
+ self.assertEqual(decode(words), num)
+
def testRFC1751(self) -> None:
- self.assertEqual(encode(0), ['A'])
- self.assertEqual(encode(1), ['ABE'])
- self.assertEqual(encode(2), ['ACE'])
- self.assertEqual(encode(2047), ['YOKE'])
- self.assertEqual(encode(2048), ['ABE', 'A'])
- self.assertEqual(encode(2049), ['ABE', 'ABE'])
- self.assertEqual(encode(2050), ['ABE', 'ACE'])
+ self.check(0, ['A'])
+ self.check(1, ['ABE'])
+ self.check(2, ['ACE'])
+ self.check(2047, ['YOKE'])
+ self.check(2048, ['ABE', 'A'])
+ self.check(2049, ['ABE', 'ABE'])
+ self.check(2050, ['ABE', 'ACE'])
# Note: These can get NSFW
- self.assertEqual(encode(2112325), ['FIRM', 'COCK'])
+ self.check(2112325, ['FIRM', 'COCK'])
if __name__ == '__main__':