Skip to content

[Python] challenge 12 (Unreviewed) #392

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions challenge_12/python/mindm/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Challenge_12
## Compression and Decompression I
These methods handle string compression and decompression.
The input can contain any characters but only alphabethicals are compressed.

These methods use re-library, which is a builtin.

You can run tests with:
```
$ python3 test.py
```
35 changes: 35 additions & 0 deletions challenge_12/python/mindm/src/compression.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re


def sub_com(matchobj):
""" Calculates the compressed string from the first letter of the match
and the length of the match
"""
letter = matchobj.group(0)[0]
length = len(matchobj.group(0))
return "{}#{}".format(letter, length)


def sub_def(matchobj):
""" Decompresses the match by multiplying the first character by the
digit after the hash character
"""
letter = matchobj.group(0)[0]
length = int(matchobj.group(0)[2:])
return "{}".format(letter * length)


def compress(input):
""" Compresses string using 're'-library
"""
out = re.sub(r'(.)\1\1\1+', sub_com, input)
return out


def decompress(input):
""" Decompresses string using 're'-library
"""
out = re.sub(r'([A-Za-z]#\d+)', sub_def, input)
return out
29 changes: 29 additions & 0 deletions challenge_12/python/mindm/src/test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import unittest
import random
from compression import compress, decompress


class TestComp(unittest.TestCase):

def test_1(self):
self.assertEqual(decompress("a#5"), "aaaaa")

def test_2(self):
self.assertEqual(compress("abbcccddddeeeee"), "abbcccd#4e#5")

def test_3(self):
original = "aliiiiicia foooooooohx"
compressed = compress(original)
decompressed = decompress(compressed)
self.assertEqual(original, decompressed)

def test_long(self):
self.assertEqual(compress("fooooooooooooooox"), "fo#15x")

def test_long2(self):
self.assertEqual(decompress("fo#15x"), "fooooooooooooooox")

if __name__ == '__main__':
unittest.main()