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"))

No comments:

Post a Comment

Author Details

Hi, I'm Prashant — a full-time software engineer with a passion for automation, DevOps, and sharing what I learn. I started Py-Bucket to document my journey through tools like Docker, Kubernetes, Azure DevOps, and PowerShell scripting — and to help others navigate the same path. When I’m not coding or writing, I’m experimenting with side projects, exploring productivity hacks, or learning how to build passive income streams online. This blog is my sandbox — and you're welcome to explore it with me. Get in touch or follow me for future updates!

About Me

About the Author

Author

Hi, I'm Prashant — a full-time software engineer with a passion for automation, DevOps, and sharing what I learn. I started Py-Bucket to document my journey through tools like Docker, Kubernetes, Azure DevOps, and PowerShell scripting — and to help others navigate the same path.

When I’m not coding or writing, I’m experimenting with side projects, exploring productivity hacks, or learning how to build passive income streams online. This blog is my sandbox — and you're welcome to explore it with me.

Get in touch or follow me for future updates!