2
def remove_duplicates(s):
    t=0
    a=s[0]
    while t <= len(s):
        x=0
        while x <= len(a):
            if s[t] != a[x]:
                a+=s[t]
            x+=1
        t+=1
    return a

print(remove_duplicates("zeebra")) #=zebra
print(remove_duplicates("aaaaaa")) #=a

The goal of this code is to remove the duplicates in any string

instead, I'm getting the output:

line 7, in remove_duplicates if s[t] != a[x]:
IndexError: string index out of range
2
  • Remove = from t &lt;= Len(s) and also from x <= Len(a) Commented Oct 18, 2018 at 3:14
  • I think this code would be much easier to read if you looked up for loops, and named your variables... Commented Oct 18, 2018 at 3:28

2 Answers 2

2

The upper bound of a list lindex is the length of the list minus one since the index starts from 0. So change:

while t <= len(s):
    x=0
    while x <= len(a):

to:

while t < len(s):
    x=0
    while x < len(a):

Or to do it in a more Pythonic way, you can avoid using indices by simply iterating over the string as a sequence:

def remove_duplicates(s):
    a = ''
    for t in s:
        if t not in a:
            a += t
    return a

To do it in the most efficient way possible if you're using Python 3.7, where dict entries are ordered, you can load the string sequence as dict keys:

def remove_duplicates(s):
    return ''.join(dict.fromkeys(s))

or if you're using earlier Python versions, you can use collections.OrderedDict instead:

from collections import OrderedDict
def remove_duplicates(s):
    return ''.join(OrderedDict.fromkeys(s))
Sign up to request clarification or add additional context in comments.

Comments

0

Your mistake is the <= condition. However, you can get rid of it by making your code more pythonic with for loop:

def remove_duplicates(s):
    a=s[0]
    for c in enumerate(s): # c is the character
        if c not in a: # look up c in a
            a += c
    return a

remove_duplicates("zeebra") # 'zebra'
remove_duplicates("aaaaaa") # 'a'

2 Comments

There's no need to enumerate as you aren't using the index t.
@blhsing ah yeah I was trying to adapt from OP's original solution and totally forget it!

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.