Section Text Chain Compression

... by Bittle in Programming Help December 26, 2020

Part 1:

Enter a section chain to compress:

kkkpppppaaaaaaabttttttttttt

The compressed string is: k3p5a7b1t11



Part 2:

Enter a compressed string:

b1k2g14

The restored string is: bkkgggggggggggggg


if __name__ == '__main__':

    '''
    PART 1
    A chain of letters: aabccc -> aa b ccc -> a2b1c3
    '''
    keyboard_in = input("Enter a section chain to compress:\n")

    prev_char = keyboard_in[0]
    current_counter = 0
    final_string = ""
    for i in range(0, len(keyboard_in)+1):
        if i == (len(keyboard_in)) or keyboard_in[i] != prev_char:
            # at the end or character changed
            final_string += str(prev_char) + str(current_counter)
            current_counter = 1
        elif keyboard_in[i] == prev_char:
            # current character = previous character
            current_counter += 1
        if i < len(keyboard_in):
            # not at the end
            prev_char = keyboard_in[i]

    print("the compressed string is:", final_string)

    '''
    PART 2
    single letter followed by multi-digit: K1U8I2 -> K1 U8 I2 -> KUUUUUUUUII
    '''
    keyboard_in = input("Enter a compressed string:\n")

    current_letter = keyboard_in[0]
    running_digit = ""
    final_string = ""

    for i in range(0, len(keyboard_in)+1):
        if i == len(keyboard_in) or not keyboard_in[i].isdigit():
            # either hit a new letter, or just started reading
            if running_digit != "":
                for _ in range(0, int(running_digit)):
                    final_string += current_letter
                running_digit = ""
            if i < len(keyboard_in):
                # not at the end so can still read
                current_letter = keyboard_in[i]
        else:
            # its a digit
            running_digit += keyboard_in[i]

    print("The restored string is:", final_string)


Comments (0)

Search Here