Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Interview coding exercise to parse and build strings based on the number of occurrences of 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