Created
January 9, 2014 19:22
-
-
Save jakemmarsh/8340234 to your computer and use it in GitHub Desktop.
Interview coding exercise to parse and build strings based on the number of occurrences of characters.
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
# Take a string as input, such as "a3c4b2", and output a new string of the letters | |
# repeated the specified number of times i.e. "aaabbcccc" | |
def parse(string): | |
newString = "" | |
for i in range(0, len(string)): | |
if(string[i].isalpha()): | |
currentChar = string[i] | |
elif(string[i].isdigit()): | |
for j in range(0, int(string[i])): | |
newString += currentChar | |
return newString | |
print parse("a3b2c4") | |
# Take a string as input, such as "aaabbcccc", and output a new string of each letter | |
# and the number of times it occurred i.e. "a3c4b2" | |
def build(string): | |
newString = "" | |
occurrences = {} | |
for i in range(0, len(string)): | |
if(string[i] not in occurrences): | |
occurrences[string[i]] = 1 | |
else: | |
occurrences[string[i]] += 1 | |
for key in occurrences: | |
newString += str(key) | |
newString += str(occurrences[key]) | |
return newString | |
print build("aaabbcccc") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment