forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* Init rle_compression file * Added encoding rle method * Added decoding rle method * Fixed typo and a bug where count would reset * RLE encode/decode unit tests * Added rle compression in README
- Loading branch information
Showing
3 changed files
with
70 additions
and
0 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
""" | ||
Run-length encoding (RLE) is a simple compression algorithm | ||
that gets a stream of data as the input and returns a | ||
sequence of counts of consecutive data values in a row. | ||
When decompressed the data will be fully recovered as RLE | ||
is a lossless data compression. | ||
""" | ||
|
||
def encode_rle(input): | ||
""" | ||
Gets a stream of data and compresses it | ||
under a Run-Length Encoding. | ||
:param input: The data to be encoded. | ||
:return: The encoded string. | ||
""" | ||
if not input: return '' | ||
|
||
encoded_str = '' | ||
prev_ch = '' | ||
count = 1 | ||
|
||
for ch in input: | ||
|
||
# Check If the subsequent character does not match | ||
if ch != prev_ch: | ||
# Add the count and character | ||
if prev_ch: | ||
encoded_str += str(count) + prev_ch | ||
# Reset the count and set the character | ||
count = 1 | ||
prev_ch = ch | ||
else: | ||
# Otherwise increment the counter | ||
count += 1 | ||
else: | ||
return encoded_str + (str(count) + prev_ch) | ||
|
||
|
||
def decode_rle(input): | ||
""" | ||
Gets a stream of data and decompresses it | ||
under a Run-Length Decoding. | ||
:param input: The data to be decoded. | ||
:return: The decoded string. | ||
""" | ||
decode_str = '' | ||
count = '' | ||
|
||
for ch in input: | ||
# If not numerical | ||
if not ch.isdigit(): | ||
# Expand it for the decoding | ||
decode_str += ch * int(count) | ||
count = '' | ||
else: | ||
# Add it in the counter | ||
count += ch | ||
return decode_str |
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