Home > Blockchain >  RLE ALgorithm in python
RLE ALgorithm in python

Time:04-29

like the title suggest I want to do an RLE algorithm and I have few problems with that

for example in RLE algorithm if we take aaaabbbccd it should return a4b3c2d1 as a result

the rle function should return the compressed string of aaabbbccccddddd

rle(data : str) : str

so it would be a3b3c4d5

Here's the code I know it's wrong but I don't know If it was a good way to begin

def rle(data):
            
    data = 'aaabbbccccddddd'    
    for i in range(0,len(data)):
                                  
        if data.count(f'{i}') > 1:
           
           data.replace(i, data.count(f'{i}'))
           print(data)

print(rle(data))

CodePudding user response:

data = 'aaabbbccccddddd'
seq = []
r = None
for d in data:
    if d != r:
        seq.append(d)
        seq.append(str(1))
        r = d
    else:
        seq[-1] = str(int(seq[-1])   1)
print("".join(seq))

CodePudding user response:

This shoudl work better

def rle(data):
    # Initialize a few variables
    prev = None
    cnt = 0 
    res = ""
    for i in data:
        if i == prev:
           # if same char as previous one, just add one to counter
           cnt  = 1
        else:
           # Check that we are not at first round and add to result
           if prev != None:
              res  = "%s%s" % (cnt,prev)
           # Set new character as previous one
           prev = i
    # Add last char to result
    res  = "%s%s" % (cnt,prev)
    return res
           
      
                                
print(rle("aaabbbccccddddd"))

  • Related