If you're using a list
to accumulate results, the only good way to turn it back into a str
is with ''.join
. But since this is a class assignment, you can be bad, and just do repeated str
concatenation to avoid a list
entirely:
def remove_repeat(msg):
newmsg = ''
for let in msg:
if let not in newmsg:
newmsg += let
return newmsg
That follows your logic and the rules, but it still gets the logic wrong, since the goal is to remove consecutive repeats, not all duplicates of the same latter. To fix, you'd track only the last letter:
def remove_repeat(msg):
newmsg = ''
for let in msg:
# Only append if last letter of the string to date differs from this letter
if let != newmsg[-1:]: # Use slice to avoid special casing first letter
newmsg += let
return newmsg
let != newmsg[-1:]
can also be done as not newmsg.endswith(let)
, not sure if you're allowed to use str
methods, so I stuck with the slice test.
Just for the record, if I were implementing this outside a class, and inputs might be large (and I had some strong need to optimize it, who knows why) I'd do:
from operator import itemgetter
from itertools import groupby
def remove_repeat(msg):
return ''.join(map(itemgetter(0), groupby(msg)))
but that's probably being a little too clever. groupby
is grouping consecutive repeated letters into groups, map(itemgetter(0),
keeps on the group key (the single letter of the repeated group), and ''.join
stitches it all back together.