Skip to content

Instantly share code, notes, and snippets.

@hltbra
Created November 20, 2012 13:28
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hltbra/4117933 to your computer and use it in GitHub Desktop.
Save hltbra/4117933 to your computer and use it in GitHub Desktop.
run length encoding using recursion
def encode(text):
if not text:
return ""
else:
last_char = text[0]
max_index = len(text)
i = 1
while i < max_index and last_char == text[i]:
i += 1
return last_char + str(i) + encode(text[i:])
print(encode("abbccc"))
# a1b2c3
def decode(text):
if not text:
return ""
else:
char = text[0]
quantity = text[1]
return char * int(quantity) + decode(text[2:])
print(decode("a1b2c3"))
# abbccc
@MostafaMGomaa
Copy link

MostafaMGomaa commented Apr 22, 2022

what iftext = "a21b11"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment