Search code examples
pythonrecursionrun-length-encoding

How to use Run Length Encoding in Python the recursive ways


I want to make a Run Length encoding but using recursive ways for some reason, but I can't figure out how to transfer my code from looping to recursive. This is for python. This is looping one, I really want to make it to recursive.

def runLengthEncoding(words):
    mylist=[]
    count=1
    for i in range(1,len(words)):
        if words[i] == words[i-1]:
            count=count+1
        else:
            mylist.append(words[i-1])
            mylist.append(count)
            count=1
    if words:
        mylist.append(words[-1])
        mylist.append(count)
    return mylist

I expect the answer ['A', 7, 'B', 3, 'C', 1, 'E', 1, 'Z', 1] for runLengthEncoding("AAAAAAABBBCEZ"). Just like the answer from the last code. but I just want to change the code to recursive ways.


Solution

  • This could have solved easily by other methods but since you are particular about recursive solution and a list form in the end, here is my solution.

    String = "AAAAAAABBBCEZ"
    
    Global_List = []
    StartWord = String[0]
    Count = 0
    def RecursiveLength(String):
        global Global_List
        global StartWord
        global Count
        if len(String)==0:
            Global_List.append(StartWord)
            Global_List.append(Count)
            return
        else:
            if String[0] == StartWord:
                Count += 1
                String = String[1:]
                return RecursiveLength(String)
            else:
                Global_List.append(StartWord)
                Global_List.append(Count)
                StartWord = String[0]
                Count = 1
                String = String[1:]
                return RecursiveLength(String)         
    
    
    
    RecursiveLength(String)
    print(Global_List)
    

    This gave me the following output. However there are better ways than recursion to solve this.

    ['A', 7, 'B', 3, 'C', 1, 'E', 1, 'Z', 1]
    

    All the best