Solution to removeConsecutiveRepeatedCharacters
This is the problem that was posted as a Do Now on (I believe) Tuesday 04/26.
removeConsecutiveRepeatedCharacters(text):
# rcrc("bookkeeper") should return "bokeper"
# rcrc("eeeecccchhhh") should return "ech"
# rcrc("eve") should return "eve"
Here are two solutions that approach it in different ways:
#-----------------------
# We'll be looking at pairs, i and i+1
# if the pair is the same, we're looking at consec. rep. chars and can ignore them
# if it's different, then we're encountering that second character for the first time,
# and should make sure to record it now
# With this method, we must be very careful about our ranges and off by 1 errors
def rcrc1(text):
result = ""
for i in range(len(text)-1):
if text[i] != text[i+1]: # if not duplicate, i.e. "ok", should record the k
result += text[i+1] #record the next char, since it's new
# else, it's a duplicate like "oo", so we've already added it before
#we never added text[0], add it now
return text[0] + result;
#-----------------------
# This second method requires us to remember what the last
# character was, but now we don't have to think about pairs
# or index out of range errors.
# However, we must be careful to be consistent with updating lastSeenChar each time
def rcrc2(text):
result = ""
lastSeenChar = "" #first time, we haven't seen a char
for i in range(len(text)):
if text[i] != lastSeenChar: #found a non-duplicate
result += text[i]
#Then, update lastSeenChar so it stays up-to-date
lastSeenChar = text[i]
return result