[Tutor] Set changing order of items?
Kent Johnson
kent37 at tds.net
Sat Jan 20 01:10:39 CET 2007
Adam Cripps wrote:
> On 1/19/07, Simon Brunning <simon at brunningonline.net> wrote:
>> On 1/19/07, Adam Cripps <kabads at gmail.com> wrote:
>>> I'm adding strings to a Set to prevent duplicates. However, the
>>> strings are meant to be in the correct order. When I add the string to
>>> the Set, the order seems to change (and I don't seem to be able to
>>> predict what order they are in).
>> Sets, like dictionaries, hold their items in an arbitrary order - see
>> <http://tinyurl.com/a2nkg>.
>
> OK - thanks for that - so it seems that using a Set will complicate
> the matter more.
>
> Really, I want to have a set of sets which won't have any duplicates.
> An example might look something ilke this:
>
> sums = [['1) 10 + 2 =', '12'], ['2) 13 + 4 =', '17']]
> return sums
>
> How might I achieve this list, without the duplicates (the duplicate
> bit is the bit I'm stuck on).
What is your criterion for uniqueness? Are you looking at just the sum,
as you mentioned earlier, or the whole problem? Why is the order
important, since the problems are randomly generated?
You should think about a more abstract way of representing a problem.
For example, the two problems above could be represented as the tuples
(10, 2, 12) and (13, 4, 17). If you want the whole problems to be
unique, then creating a set of tuples like this should do what you want.
(I used tuples instead of lists because you can't make a set of lists.)
If you want only one problem with a given sum, then I would represent a
problem as an entry in a dictionary where the sum is the key and the
value is a tuple containing the two addends. Then you can keep putting
problems in the dictionary until it is the size you want.
Once you have the final set (or dict) of problems, then you can convert
them to a string representation and print them.
Kent
More information about the Tutor
mailing list