Monday, 1 February 2021

String Compression

 Question) Compress the given string

Note- character count should be follow by the character

Test case 1:

Input- AAAABBBCCCKLDC

Output - A4B3C3K1L1D1C1

Test case 2:

Input-  AAABBCCCCC

Output - A3B2C5


Code:

def string_cm(s):
counter = 0 # to count the character initially set to 0
test_list = s[0] #taking only first char to compare initially
result =''
s= s + " " # giving extra space at end just to take whole list as input
for x in s:
if x == test_list:
counter+=1
#print(counter)
else:
result = result + str(test_list) + str(counter)
test_list = x #setting up new char for further check
counter=1 #setting counter to 1 again

return result


print(string_cm("AAABBCCCCC"))

Post Top Ad

Your Ad Spot

Pages

SoraTemplates

Best Free and Premium Blogger Templates Provider.

Buy This Template