Skip to content

Instantly share code, notes, and snippets.

@eykd
Last active August 29, 2015 13:57
Show Gist options
  • Save eykd/9533711 to your computer and use it in GitHub Desktop.
Save eykd/9533711 to your computer and use it in GitHub Desktop.
String compression interview question.
Feature: String Transformation Puzzles
In order to get a job,
As an interviewee,
I need to be able to implement stupid, meaningless string transformations.
Scenario: Compress consecutive characters to a number and the character itself.
Write a function that takes in a char *string and converts series of
consecutive identical characters to the number of consecutive characters and
the character itself.
E.g. (aaabbbbcccccdde => 3a4b5c2de)
Given the string "aaabbbbcccccdde"
When I compress the string
Then I get the string "3a4b5c2de"
Given the string "aaabbbbcccccddeaaa"
When I compress the string
Then I get the string "3a4b5c2de3a"
def compress(subject):
"""Compress consecutive characters to a number and the character itself.
"""
def gen():
count = 0
last_char = None
out = lambda: str(count) + last_char if count > 1 else last_char
for char in subject:
if char != last_char and last_char is not None:
yield out()
count = 0
last_char = char
count += 1
yield out()
return ''.join(gen())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment