Created
August 2, 2021 11:30
-
-
Save chetanmelkani/b2d5e68e77c5e079c9394a7bff8fd3bb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# string input | |
# function, short version | |
#aaaa: a4 | |
# aaaabbbcccaaaa | |
# a4b3c3a4 | |
def count_chars(str_: str): | |
if str_ == "": | |
return "" | |
response = [] | |
count = 0 | |
previous = '' | |
for s in str_: | |
if previous == '': | |
previous = s | |
count += 1 | |
else: | |
if previous != s: | |
if count == 1: | |
response.append(f"{previous}") | |
else: | |
response.append(f"{previous}{count}") | |
count = 1 | |
previous = s | |
else: | |
count += 1 | |
if count == 1: | |
response.append(f"{previous}") | |
else: | |
response.append(f"{previous}{count}") | |
return "".join(response) | |
assert count_chars("aaaabbbcccaaaa") == "a4b3c3a4" | |
assert count_chars("a") == "a" | |
assert count_chars("aabc") == "a2bc" | |
assert count_chars("") == "" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment