-1

I'm trying to solve this exercise using enumerate, but I don't have any idea how to implement the value. In a mathematical way I said if for index and index+1 letter is the same do nothing, if the upcoming letter is different write letter. But I have no idea how to do it in python Desired result aaabbbaas => abas.

def zad6(string):
    b =""
    for index,letter in enumerate(string):
        if letter[index] == letter[index+1]:
            b += None
        else:
            b += letter
    return b
print(zad6("aaabbbaas"))
martineau
  • 119,623
  • 25
  • 170
  • 301
  • Does this answer your question? [Removing elements that have consecutive duplicates](https://stackoverflow.com/questions/5738901/removing-elements-that-have-consecutive-duplicates) – Harshal Parekh Nov 07 '21 at 15:03
  • Welcome to SO. Please go through [this checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/) by Jon Skeet. Researching if the question is asked before is a very important aspect of asking a question. – Harshal Parekh Nov 07 '21 at 15:09

3 Answers3

2

Here is a fix of your code using enumerate, you can check if each previous letter was the same, except the first time (index == 0):

def zad6(string):
    for index, letter in enumerate(string):
        if index == 0:
            b = letter
        elif letter != string[index-1]:
            b += letter
    return b
print(zad6("Baabba"))

output: 'Baba'

NB. this considers case, 'B' and 'b' will be different, if you want to ignore case use letter.lower() != string[index-1].lower()

alternative

just for the sake of showing an efficient solution, in real life you could use itertools.groupby:

from itertools import groupby

string = "Baabba"
''.join(l for l,_ in groupby(string))
mozway
  • 194,879
  • 13
  • 39
  • 75
1

Only append when you have something to append, there's no need to append None (and in fact, it doesn't work). Also, you should check if there's a next character at all in the string, or it will fail at the last iteration

def zad6(string):
    b = ""
    for index,letter in enumerate(string):
        if index == len(string)-1 or letter != string[index+1]:
            b+=letter
    return b
print(zad6("Baabba"))
Dario Petrillo
  • 980
  • 7
  • 15
0

Here's an alternate approach without using a for loop, that seems a bit simpler:

from operator import itemgetter


def zad6(string):
    filt = filter(lambda x: x[1] != string[x[0] - 1], enumerate(string))
    return ''.join(map(itemgetter(1), filt))


assert zad6('aaabbbaas') == 'abas'
assert zad6('Baabba') == 'Baba'
rv.kvetch
  • 9,940
  • 3
  • 24
  • 53