I'm trying to write a simple python algorithm to solve this problem. Can you please help me figure out why my code is not working:
Problem:
If any character is repeated more than 4 times, the entire set of repeated characters should be replaced with a slash '/', followed by a 2-digit number which is the length of this run of repeated characters, and the character. For example, "aaaaa" would be encoded as "/05a". Runs of 4 or less characters should not be replaced since performing the encoding would not decrease the length of the string.
My Code:
def runLengthEncode (plainText):
res=''
a=''
for i in plainText:
if a.count(i)>0:
a+=i
else:
if len(a)>4:
res+="/" + str(len(a)) + a[0][:1]
else:
res+=a
a=i
return(res)
collections.Counteranditertools.groupby. Both are very effective ways to count repeats in sequences. - kojiro/05cbecause it has no concept of escaping input correctly. You either need to handle/especially, or compress every occurrence, not just runs of length > 4. - Konrad Rudolph