Python String Data Compression Question (no more than two iterations)

Asked 1 years ago, Updated 1 years ago, 262 views

Hello. I have a question about compressing Python string data. AAAAAABBCCCDDDZZZWW. These strings I compressed up to A5B2C3D3Z3W2 If you want to compress characters that are repeated less than two times, like AABB, to just compress them into characters, What conditions should I add (e.g. A5BBC3D3Z3WW)?

//python
def encode(text):
    encoded = ""
    count = 1

    for i in range(1,len(text)):
        if text[i] == text[i-1]:
            count += 1
        else:
            encoded += text[i-1] + str(count)
            count = 1

    if i == len(text)-1:
        encoded += text[i] +str(count)  
    return encoded 

python string

2022-10-28 00:00

1 Answers

If the count is less than or equal to 2, you can put the character in the encoded as many as the count.


2022-10-28 00:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.