Skip to contentKEEP THE CRAFTTHE SANCTUARY

Encode and Decode Strings

Turn a list of strings into one string and back, even when the strings contain any character.

The problem

Implement the class Codec with two methods. encode(strings) turns a list of strings into a single string, and decode(encoded) turns that string back into the original list. Use this format: for each string, write its length in decimal, then '#', then the string itself, with nothing in between the pieces. For example, ["hello", "world"] becomes "5#hello5#world", [""] becomes "0#", and [] becomes "". Strings may contain any character, including '#' and digits. There are fewer than 100 strings, each shorter than 200 characters, and one Codec object may be used for several calls.

Starter code

class Codec:
    def encode(self, strings):
        pass

    def decode(self, encoded):
        pass

Public examples

  1. obj = Codec() obj.encode(["hello", "world"]) obj.decode("5#hello5#world")gives[None, "5#hello5#world", ["hello", "world"]]
  2. obj = Codec() obj.encode([""]) obj.decode("0#")gives[None, "0#", [""]]
  3. obj = Codec() obj.encode(["abcdefghijklm"]) obj.decode("13#abcdefghijklm")gives[None, "13#abcdefghijklm", ["abcdefghijklm"]]

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.