Reputation: 51
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
Upvotes: 0
Views: 308
Reputation: 68
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
Upvotes: 0
Reputation: 363
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.
Upvotes: 0
Reputation: 861
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.
Upvotes: 1
Reputation: 5502
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
Upvotes: 0
Reputation: 1226
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
.
Upvotes: 1
Reputation: 6920
Try this :
str_ = input()
from collections import OrderedDict
str_ = ''.join(list(OrderedDict.fromkeys(str_)))
Upvotes: 5