user1248367
user1248367

Reputation: 27

Removing duplicates in Python

My program so far

def RemoveDuplicates(text):
    result=[]
    used=set()
    for char in text:
        if char not in used:
            used.add(char)
            result.append(char)
    return ''.join(result)

text=input('Enter some text: ')
print(join(result))

I'm a beginner to Python so this is a quite difficult task for me. I know this doesn't add up, but where have I made the mistake?

Upvotes: 1

Views: 186

Answers (5)

fraxel
fraxel

Reputation: 35269

One small problem is that you forgot to call your function! Additionally, if you're using Python 2.x the user input needs to be collected using raw_input.

Two small fixes and your code works fine:

def RemoveDuplicates(text):
    result=[]
    used=set()
    for char in text:
        if char not in used:
            used.add(char)
            result.append(char)
    return ''.join(result)

text = raw_input('Enter some text: ')
print(RemoveDuplicates(text))

Upvotes: 0

Thomas
Thomas

Reputation: 181725

In addition to the other answers: if you're using Python 2, you need to use raw_input instead of input.

Upvotes: 1

Elliot Bonneville
Elliot Bonneville

Reputation: 53291

Your function looks okay to me, although I'm no expert. I think the problem lies in the fact that you're not actually calling it anywhere. Try calling it like this: print(RemoveDuplicates(text)).

Upvotes: 0

kindall
kindall

Reputation: 184091

You've never actually called your RemoveDuplicates() function.

Replace:

text=input('Enter some text: ')
print(join(result))

with:

print(RemoveDuplicates(input("Enter some text:" )))

Upvotes: 1

jwd
jwd

Reputation: 11114

A few things here:

  1. You defined the function RemoveDuplicates, but never actually call it.

  2. You use a set(), but then check for duplicates manually. A set, by definition, will get rid of duplicates automatically.

  3. You haven't told us what you are actually trying to accomplish. Do that, then we can help you more.

Upvotes: 0

Related Questions