[Python] Given a string containing uppercase alphabets (A-Z), compress the string using Run...

Discussão em 'Python' iniciado por Stack, Janeiro 18, 2025.

  1. Stack

    Stack Membro Participativo

    Given a string containing uppercase alphabets (A-Z), compress the string using Run Length encoding. Repetition of character has to be replaced by storing the length of that run.

    I tried the following codes

    #Code 1: Tried on my own


    def encode(message):
    list1=[]
    for i in range (0,len(message)):
    count = 1
    while(i < len(message)-1 and message==message[i+1]):
    count+=1
    i+=1
    list1=str(count)+message
    return list1
    encoded_message=encode("ABBBBCCCCCCCCAB")
    print(encoded_message)



    Input:AAAABBBBCCCCCCCC
    Expected Output: 4A4B8C



    #code 2:I tried this by looking at another code based on run-length encoding

    def encode(message):
    list1=[]
    count=1
    for i in range (1,len(message)):
    if(message==message[i-1]):
    count+=1
    else:
    list1.append((count,list1[i-1]))
    count=1
    if i == len(messege) - 1 :
    list1.append((count , data))
    return list1

    encoded_message=encode("ABBBBCCCCCCCCAB")
    print(encoded_message)


    Input:AAAABBBBCCCCCCCC
    Expected Output: 4A4B8C

    The first code gives output as 2B

    Continue reading...

Compartilhe esta Página