Home > Software engineering >  How to remove neighbouring letter if they are the same using enumerate?
How to remove neighbouring letter if they are the same using enumerate?

Time:11-08

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"))

CodePudding user response:

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))

CodePudding user response:

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"))

CodePudding user response:

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'
  • Related