Stores a continuous sequence of the same bits as a pair containing:
- the bit value
- the repetition of the bit value
Implementation
def perform_encoding(string: str) -> str:
encoded_string = ""
count = 1
for i in range(1, len(string)):
if string[i] == string[i - 1]:
count += 1
else:
encoded_string += f"{string[i - 1]}{count}"
count = 1
encoded_string += f"{string[-1]}{count}"
return encoded_string
def perform_decoding(encoded_string: str) -> str:
decoded_string = ""
for i in range(0, len(encoded_string), 2):
decoded_string += encoded_string[i] * int(encoded_string[i + 1])
return decoded_string
message = "aaaabbbccdeee"
encoded_message = perform_encoding(message)
decoded_message = perform_decoding(encoded_message)
print(f"Encoded message: {encoded_message}")
print(f"Decoded message: {decoded_message}")
print(f"Passed test? {message == decoded_message}")
Example
Example Application: Text