Skip to content

Instantly share code, notes, and snippets.

@joelgrus
Created February 1, 2018 05:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joelgrus/a88fd090639e5c6739fbe77f0b3210ec to your computer and use it in GitHub Desktop.
Save joelgrus/a88fd090639e5c6739fbe77f0b3210ec to your computer and use it in GitHub Desktop.
I get daily interview coding problems in the mail, this was the jerkiest way I could think of to do run length encoding
"""
Run-length encoding is a fast and simple method of encoding strings.
The basic idea is to represent repeated successive characters
as a single count and character. For example, the string
"AAAABBBCCDAA" would be encoded as "4A3B2C1D2A".
Implement run-length encoding and decoding. You can assume
the string to be encoded has no digits and consists solely of alphabetic
characters. You can assume the string to be decoded is valid.
"""
import itertools
import re
def encode(s: str) -> str:
return ''.join(str(len(list(group))) + c
for c, group in itertools.groupby(s))
assert encode("AAAABBBCCDAA") == "4A3B2C1D2A"
REGEX = "([0-9]+)([A-Za-z]+)"
def decode(s: str) -> str:
return ''.join(int(count) * char
for count, char in re.findall(REGEX, s))
assert decode("4A3B2C1D2A") == "AAAABBBCCDAA"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment