Reputation: 41
The question asks: 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.
When I type a list into the function, it does not iterate through the whole length of the list. It will work for lists of shorter lengths but not for longer ones.Not sure how to fix it.
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(myList[i-1])
aList.append(count)
count=1
if i == (len(myList)-1):
aList.append(myList[i])
aList.append(count)
return aList
Upvotes: 1
Views: 3826
Reputation: 27283
Your code is failing when the last item(s) are repeating, or when the length of the list is 1:
>>> runLengthEncoding("fooobar")
['f', 1, 'o', 3, 'b', 1, 'a', 1, 'r', 1]
>>> runLengthEncoding("fooobarr")
['f', 1, 'o', 3, 'b', 1, 'a', 1]
>>> runLengthEncoding("a")
[]
A fix for your solution would be to remove the three lines starting with if i == (len(myList)-1):
and replace them with
if myList:
aList.append(myList[-1])
aList.append(count)
Move that block outside the loop.
However, the easiest way to implement run-length encoding would probably be with the itertools module:
from itertools import chain, groupby
def run_length(iterable):
return list(chain.from_iterable(
(val, len([*thing]))
for val, thing in groupby(iterable)
))
Upvotes: 1