Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to allow duplicates in a set?

I ran into a problem regarding set in Python 2.7.

Here's the appropriate example code block:

letters = set(str(raw_input("Type letters: ")))

As you can see, the point is to write some letters to assign to "letters" for later use. But if I type "aaabbcdd", the output of "letters" returns

set(['a', 'c', 'b', 'd'])

My question is how to write the code, so that the output will allow duplicates like this:

set(['a','a','a','b','b','c','d','d'])

?

like image 450
Alex Avatar asked Feb 26 '12 18:02

Alex


People also ask

How do you make a set allow duplicates in Python?

Python set doesn't have duplicate elements. We can use the built-in set() function to convert the list to a set, then use the list() function to convert it back to the list.

How do I allow duplicates in set?

You can't. That's the point of Set. Sets, by their mathematical definition, can't have duplicates.

Why set does not allow duplicates in Python?

Why set does not allowed duplicates,How it will work internally. The meaning of "sets do not allow duplicate values" is that when you add a duplicate to a set, the duplicate is ignored, and the set remains unchanged.

Can you have repetition in a set?

Sets does not have repeated elements.


2 Answers

set doesn't store duplicates, which is why it's called a set. You should use an ordinary str or list and sort it if necessary.

>>> sorted(raw_input("Type letters: "))
Type letters: foobar
['a', 'b', 'f', 'o', 'o', 'r']

An alternative (but overkill for your example) is the multiset container collections.Counter, available from Python 2.7.

>>> from collections import Counter
>>> c = Counter(raw_input("Type letters: "))
>>> c
Counter({'o': 2, 'a': 1, 'r': 1, 'b': 1, 'f': 1})
>>> sorted(c.elements())
['a', 'b', 'f', 'o', 'o', 'r']
like image 88
Fred Foo Avatar answered Oct 21 '22 08:10

Fred Foo


A set does not allow duplicates by definition. Use a simple list.

In your case:

letters = list(str(raw_input("Type letters: ")))
print sorted(letters)
like image 29
Michele Spagnuolo Avatar answered Oct 21 '22 06:10

Michele Spagnuolo