Remove duplicate letters in a word

Andy Jewell andy at wild-flower.co.uk
Sun Jun 22 21:10:05 CEST 2003


On Sunday 22 Jun 2003 7:11 pm, Eliran Gonen wrote:
> Hello !
>
> I'm new in this list.
>
> Anyway, I'm trying to write some sort of encryption program (pretty
> trivial and simple) that need to check for several occurences of a letter
> in a specific word.
>
> For example, in the word SECRET, E appears twice, I need to get rid of
> the second instance of E.
>
> I'm stuck here:
>
>     for i in range(len(key)):
>         for j in range(len(key)):
>             if key[i] == key[j] :
>                 key[j] = ""
>
> Hope you can help me,
>
> TIA, EG


I notice Steven Taschuk and Roman Suzi have jsut replied whilst I was testing 
out my answer... oh, well - I'll throw in my penny's worth anyway....

As steven says, because strings are immutable (meaning you can't change them 
once created) the code above can't work.  Here's a trace of waht I came up 
with (I've cut out the stuff that duplicates Steven's work):

>>> word=list("flibble dibble dee doo")
>>> n=0
>>> while n < len(word):
	while word[n] in word[n+1:]:
		sec=word[n+1:].index(word[n])
		del word[n+1+sec]
	n+=1

	
>>> word
['f', 'l', 'i', 'b', 'e', ' ', 'd', 'o']
>>> word="".join(word)
>>> word
'flibe do'
>>> word=list("secret")
>>> n=0
>>> while n < len(word):
	while word[n] in word[n+1:]:
		sec=word[n+1:].index(word[n])
		del word[n+1+sec]
	n+=1

	
>>> word="".join(word)
>>> word
'secrt'
>>> 

I wasn't sure you wanted to remove *all* subsequent occurrences, but that's 
what this code does.

The outer while loop iterates over each item in the list.  As we're changing 
the list, we have to use an index into it (that's 'n'). 

Next we have a loop which checks if the letter we're now looking at (word[n]) 
exists in the *rest* of the list (word[n+1:]).  

Inside the inner loop, we then pinpoint the *next* occurrence of the letter, 
the zap it (del word[n+1+sec]).

Now, again outside the inner loop, we increment to pointer (n) and have 
another go, until n is past the end of the list.

Outside the main loop, we join the list back together as a string and show it.

Hope that helps.

BTW if you only want to remove the second occurrence of each letter, just use 
an 'if' rather than a 'while', but beware that it'll remove every second 
occurrence, unless you use some way to remember which letters you've already 
zapped... maybe a further exercise.

good luck
-andyj






More information about the Python-list mailing list