Question & Answer: Implement run-length encoding on strings. Run-length encoding collapses consecutive instances of a single character into t…..

using python
☆ Run Length Encoding Implement run-length encoding on strings. Run-length encoding collapses consecutive instances of a single character into two pieces of information the number of instances and the charact Note that even single characters should be run length encoded. If the string is empty, return an empty string. Your implementation should work on all alphanumeric characters. Complete the runLengthEncode function which takes a string input as a parameter and returns the compressed string Sample Input Sample Output 5G14r1t Explanation There are 5 G·characters then there are 14 rs then there is 1 T. YOUR ANSWER

Implement run-length encoding on strings. Run-length encoding collapses consecutive instances of a single character into two pieces of information the number of instances and the Note that even single characters should be run length encoded. If the string is empty, return an empty string. Your implementation should work on all alphanumeric characters. Complete the runLengthEncode function which takes a string input as a parameter and returns the compressed string. GGGGGrrrrrrrrrrrrrrt 5G14r1t There are 5 ‘G’ characters then there are 14 ‘r’s then there is 1 ‘t’.

Expert Answer

 

#RunLentghencode() function takes plain text as input and returns compressed
# text as output as counting ordered characters
def runlengthencode(plainText) :
#declaring variables
res=”
a=”
b=”
c=1
k=0
for i in plainText:#for loop for all characters
a=i
if a==b:#for every second same character onwards counting starts
c+=1

else :
if k==0 :#escaping first time ,because
#b was not initialized at first time
k=1
else :#joining number of chracters and that chracter into
#res string
res+=str(c)+b
c=1
b=i
res+=str(c)+b #final character is appending into res string

return res#returning res to runlengthencode function

#plaintext initialization
plainText = ‘pgggggghhhhhhhhhhhhhhhhhhhht’
#calling to runlentghencode() function
compressedText=runlengthencode(plainText)
#displaying compressed text after encoding
print compressedText

#program and output screenshot is shown below

Still stressed from student homework?
Get quality assistance from academic writers!