From ef890ccba905d221665587e8efe38b3fa4462ca1 Mon Sep 17 00:00:00 2001 From: Matthew Grove Date: Thu, 4 Feb 2021 22:37:30 +0000 Subject: [PATCH] Add simple run length encoding program --- run-length-encoding.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 run-length-encoding.py diff --git a/run-length-encoding.py b/run-length-encoding.py new file mode 100644 index 0000000..7e92b86 --- /dev/null +++ b/run-length-encoding.py @@ -0,0 +1,19 @@ +def sameChar(chars): + if len(chars) < 2 or chars[0] != chars[1]: + return 1 + else: + return 1 + sameChar(chars[1:]) + +def RLE(uncompressed): + total_chars = 0 + compressed = [] + + while total_chars < len(uncompressed): + char_count = sameChar(uncompressed[total_chars:]) + compressed.append(f"{uncompressed[total_chars]} {char_count}") + total_chars += char_count + + return " ".join(compressed) + + +print(RLE(input("Uncompressed text: ")))