Search code examples
pythondecodeencode

Encode and Decode a String using the repetition of characters along the string


I've been trying to tackle this problem but I haven't got any luck so far :( so any guidance would be awesome, especially since I'm just learning Python, so the problem is this:

Given a certain string, first you'll have to encode it using the following algorithm:

  • For every letter, strip the consecutive repetitions, if any, and add a number with the number of times it appears consecutively, including the first time.

After you've completed the encoding you'll have to create a function to decode it using the same criteria/assumptions.

Some examples of how it should work:

  • “Goooooooooddddd” => “G1o9d5”
  • “Oooo” => “O1o3”
  • “anagram” => “a1n1a1g1r1a1m1”

So far I have the following code for the encoding:

def encode(s) :
 
    i = 0
    while( i < len(s) - 1) : 
        count = 1 
        while s[i] == s[i + 1] :
            i += 1
            count += 1
             
            if i + 1 == len(s):
                break         
        print(str(s[i]) + str(count),  
                          end = "")
        i += 1 
    print()

# Code for the driver
if __name__ == "__main__" :

    encode("Goooooooooddddd")
    encode("Oooo") 

With this I'm getting the needed output for the encoding part at least.

But I'm unable to actually do the "decoding" part by using this encoding as a starting point.

I know this question is quite silly/basic but I really can't get my head over it Thanks in advance for the guidance/tips for this challenge problem


Solution

  • Decoding would be very simple in python since it allows character multiplication: It might be like:

    def decode(s):
        a = list(s) # separate each character and number
        i = 0
        z = len(a)
        while i < z-1:   #This for block checks for any 2 digit numbers
            print(i, a[i])
            if a[i].isdigit() and a[i+1].isdigit():
                a[i] = a[i]+a[i+1]
                a.pop(i+1)
                print(a)
                z-=1
                try: 
                    if a[i+2].isdigit():
                        i-=1
                except IndexError:
                    i-=1
            i+=1
        final_str = '' # the string that will have the value
        for i in range(0, len(a), 2):
            final_str += a[i]*int(a[i+1]) #a[i] is the character and int(a[i+1]) is the number of times. 
                                          # They are multiplied and then added to the final string
        print(final_str) # The final string is printed
    
    

    Thanks to @Tobi208 for pointing out the bug.