Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all Adjacent duplicates using a loop

I'm trying to solve this problem. I have seen other solutions that involve lists and using recursion but I'm interested in learning how to solve this with loops and my problem is I can't get the last char to print out since it equals an empty variable.

input:abbabd
expected output:aabd

Code:

answer = input("enter a string: ")
new_answer = ""
p = ""
repeat = ""
len_answer = len(answer)
run = False

for c in answer:
    if c != p and run == False:
        new_answer += p
        p = c
        run = False

    elif c == p:
        p = c 
        run = True

    elif run == True and c != p:
        p = c 
        run = False 

    else: 
        new_answer += p


print(new_answer)
like image 748
Angel Valenzuela Avatar asked Aug 25 '26 17:08

Angel Valenzuela


1 Answers

All you need to fix your code is to add some extra code that runs after the end of the loop and adds p to the end of the result if necessary:

if not run:
    new_answer += p

You could simplify your loop a bit more though, if you combined some of the conditions. It can be pretty simple:

for c in answer:
    if c == p:
        loop = True          # no need for p = c in this case, they're already equal
    else:
        if not loop:
            new_answer += p
        loop = False
        p = c

You'll still need the lines from the first code block after this version of loop.

like image 106
Blckknght Avatar answered Aug 28 '26 08:08

Blckknght



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!