RLE Decompress/ compress
unknown
python
10 days ago
2.1 kB
2
Indexable
def compress(input_string): if not input_string: return "" compressed = [] count = 1 length = len(input_string) for i in range(1, length): if input_string[i] == input_string[i - 1]: count += 1 else: compressed.append(input_string[i - 1] + str(count)) count = 1 # Append the last character and its count compressed.append(input_string[-1] + str(count)) return ''.join(compressed) def decompress(compressed_string): if not compressed_string: return "" decompressed = [] i = 0 length = len(compressed_string) while i < length: char = compressed_string[i] i += 1 # Check if the next character(s) are digits count_str = '' while i < length and compressed_string[i].isdigit(): count_str += compressed_string[i] i += 1 if not count_str: return "Invalid format: Missing count after character." count = int(count_str) decompressed.append(char * count) return ''.join(decompressed) if __name__ == "__main__": while True: print("\nRun-Length Encoding (RLE) Compression and Decompression") print("1. Compress a string") print("2. Decompress a string") print("3. Exit") choice = input("Choose an option (1/2/3): ") if choice == '1': input_string = input("Enter the string to compress: ") compressed_string = compress(input_string) print(f"Compressed: {compressed_string}") elif choice == '2': compressed_string = input("Enter the RLE-compressed string to decompress: ") decompressed_string = decompress(compressed_string) print(f"Decompressed: {decompressed_string}") elif choice == '3': print("Exiting the program.") break else: print("Invalid choice. Please select 1, 2, or 3.")
Editor is loading...
Leave a Comment