[Tutor] Program

Wayne Werner waynejwerner at gmail.com
Wed May 18 15:19:13 CEST 2011


On Wed, May 18, 2011 at 7:26 AM, Johnson Tran <aznjonn at me.com> wrote:

> Hi Again All,
>
> I had a couple questions about my program:
>

Corey gave you some good pointers already, but let me add a few...


>
> def CollectNames():
>
>    answer_set=set([])
>    sorted_list = sorted(answer_set)
>

This won't do what you think it does (I use IPython so my prompt looks
different than the >>> you should be used to):

In [5]: answer_set = set([])

In [6]: sorted_list = sorted(answer_set)

In [7]: sorted_list.append(3)

In [8]: sorted_list.append(1)

In [9]: sorted_list
Out[9]: [3, 1]

You can find out why this happens by checking the documentation:

In [10]: help(sorted)
Help on built-in function sorted in module __builtin__:

sorted(...)
    sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list

so sorted returns a list - and if you aren't familiar with lists yet, they
are simple collections - un-sorted until you sort them. Instead what you
might want to do is add your items to the list (or the set) and then once
you have all your items, /then/ return the sorted list (Although, there is
another solution to your problem using a set and the size of it... I'll
leave that exercise to you)

HTH,
Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110518/3712406a/attachment.html>


More information about the Tutor mailing list