0

There are a lot of methods available online for doing this, what I am trying to do is just slicing the string and concatenating it leaving the duplicate character. It just fails to run for some cases, for e.g if there is more than one duplicate it just fails to delete it. I can't understand how to make my inner loop run again for the same index to check for other duplicates. I know that this is not the best solution but I just wanna know whether we can make this logic work or not.

s = input()
l = len(s)
for i in range(0, l-1):
    for j in range(i+1, l - 1):
        if s[i] == s[j]:
            s = s[:j] + s[j+1:]
print(s)

sample input: helllo

output: hello

expected output: helo

1
  • 2
    Don't use str as a variable name as it is predefined in python. Also, please keep in mind to use correct indentation when showing your code. Commented Jun 28, 2019 at 12:36

6 Answers 6

5

Try this :

str_ = input()
from collections import OrderedDict
str_ = ''.join(list(OrderedDict.fromkeys(str_)))
Sign up to request clarification or add additional context in comments.

2 Comments

I know about this, I am asking can we make changes to the current logic to make it work.
@NishantKehar If you want a solution without external module, create a new list to append characters or make a new vacant string to add new characters to it. Take a look at Alexandre 's answer. You tried to modify the string while looping through it. It's advised to not modify iterable while looping through it.
1

One way to solve this would be with groupby from itertools:

from itertools import groupby
a = 'helllo'
# convert into a list where every element represents a character in your string
b = [x for x in a]
print(b)
# ['h', 'e', 'l', 'l', 'l', 'o']

# group by a value within list comprehension
c = [x[0] for x in groupby(b)]
print(c)
# ['h', 'e', 'l', 'o']

# turn into string again
d = ''.join(c)
print(d)
# helo

This works for multiple consecutive duplicates as shown in my example but also singe consecutive duplicates (as in "hello"). For more information see the documentation on itertools.

Comments

1

Try this if you only want consecutive duplicated characters:

def remove_duplicates(s): 
    final = "" 
    for char in s: 
         if len(final): 
             if char == final[-1]: 
                 continue 
         final += char 
    return final

If you want only unique characters:

def remove_duplicates(s): 
    final = "" 
    for char in s: 
         if char in final: 
             continue 
         final += char 
    return final

or the other answers are pretty neat as well.

3 Comments

Doesn't work if you take letters surrounded by others: aba
As far as I understood OP's question it was only for duplicated characters i.e. for characters that are repeated consecutively. Otherwise you just need to take the 'unique' characters.
This works, but please note that the performance will be terrible (quadratic). So don't use it for large strings or if performance matters.
0

Another way to do: remove duplicates by keeping the order (duplicate ?)

def remove_duplicates_with_order(seq):
    seen = set()
    seen_add = seen.add
    return "".join([x for x in seq if not (x in seen or seen_add(x))])

print(remove_duplicates_with_order("hello"))
# helo

Comments

0

I don't know if it is possible to keep the nested loops, as you are modifying the string, so j may go beyond the length of the string.

I've changed your code a little, but this is what I came up to:

def remove_duplicates(s):
    cpy = ''
    for i in range(len(s)-1):
        j = i+1
        if s[i] == s[j]:
            continue
        cpy += s[i]
    else:
        cpy += s[-1]
    return cpy

I've used a new string, cpy, and it's not slicing, but I think your idea is there.

Comments

0

The solution:

s = "helllo"
l = len(s)
i=0
j=0
while (i<l-1):
    j=i+1
    while (j<l):
        if s[i] == s[j]:
          s = s[:j] + s[j+1:]
          l=len(s)
          j=j-1
        j=j+1
    i=i+1

print(s)

The problem with your code is that when you use s = s[:j] + s[j+1:] you change the len of the string but you don't update the values of i and j properly

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.