Highly repetitive data can sometimes be compressed using something called run-length encoding: It is shorter to write "8o" instead of "oooooooo".
Each run is represented by a number n, followed by a single non-space character c. Each run is separated by a single space.
Below is a simple decode function:
def rl_decode(s):
return "".join(map(lambda s: int(s[:-1]) * s[-1], s.split()))
You must write the inverse function
rl_encode(s)
that consumes a space-less string s, and returns its run length encoding.
Examples:
rl_encode("CCCCCCAATTTT") => "6C 2A 4T" rl_encode("aa") => "2a"
Do not abstract list functions, map, and filter are not allowed. Recursion is also prohibited!
Python code:
# required function
def rl_encode(string):
#variable for storing output string
e_str=""
#Stores count
count=1
#looping to create encoded string
for i in range(1,len(string)):
#checking if adjacent characters are same
if(string[i]==string[i-1]):
#incrementing count
count+=1
else:
#adding to e_str count and the character
e_str=e_str+str(count)+string[i-1]+" "
#assigning count as 1
count=1
#adding count and final character
e_str=e_str+str(count)+string[i]
#returning e_str
return(e_str)
#checking and printing value returned by rl_encode
print(rl_encode("CCCCCCAATTTT"))
print(rl_encode("aa"))
Screenshot:
Output:
Get Answers For Free
Most questions answered within 1 hours.