Skip to content

Instantly share code, notes, and snippets.

@kracekumar
Last active December 29, 2025 12:38
Show Gist options
  • Select an option

  • Save kracekumar/abe6463f57e9d8fd6271511628dff449 to your computer and use it in GitHub Desktop.

Select an option

Save kracekumar/abe6463f57e9d8fd6271511628dff449 to your computer and use it in GitHub Desktop.
Replace Repeats
"""
Given a string that contains only digits from 0 to 9 and a number `n`, replace each consecutive run of `n` with its length.
> replaceRepeats('1234500362000440', 0)
1234523623441
> replaceRepeats('000000000000', 0)
12
> replaceRepeats('123456789', 1)
123456789
Email: https://buttondown.com/cassidoo/archive/the-beginning-is-the-word-and-the-end-is-silence/
"""
def replace_repeats(word, number):
final_string, prev_char, count = "", "", 0
for char in word:
# keep counting when the characters match
if int(char) == number:
count += 1
else:
# when characters do not match, decide if it is a single match, more than one character match, or no match.
# depending on the condition, do operation.
if count > 1:
final_string += str(count)
final_string += char
elif count == 1:
final_string += prev_char
final_string += char
else:
final_string += char
count = 0
prev_char = char
# Make sure all the strinngs are appended before returning, no dangling characters
if count == 0:
return final_string
else:
return (final_string + str(count))
assert replace_repeats('1234500362000440', 0) == str(1234523623441)
assert replace_repeats('000000000000', 0) == str(12)
assert replace_repeats('123456789', 1) == str(123456789)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment