简体   繁体   中英

Run Length Encoding Python

The problem I have is:

Write a function that takes, as an argument, a list of characters and returns a list reflecting the run-length encoding of that list. The elements in the returned list follow the following pattern: the even indices contain the characters and the odd indices contain the number of times the character is repeated consecutively. Name your function runLengthEncoding(myList).

For example, runLengthEncoding([aaabbccd]) should return [a,3,b,2,c,2,d,1] .

Here is what I have, but I can't figure out what is wrong:

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

You almost had it, there are a couple of changes necessary however. Calling runLengthEncoding([aaabbccd]) will not work as it is calling aabbccd as a variable, not as a string. If you replace the square brackets with quotation marks, you will have the intended input as a string (also known in python as a list of chars).

Also, depending on how picky you have to be on the format of the output of the function, you are currently outputting a list of tuples, instead of a straight up list of the chars with their counts. To output this as specified in the question, you can change your aList.append((count, myList[i-1])) lines to be:

aList.append(myList[i-1])
aList.append(count)   

And finally, the only thing wrong with the code you posted was that you want your for loop to start at 1 rather than 0. This will mean that the i-1 will start at 0 instead of -1. Here is the working modified code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM