[Tutor] Re: Tutor Digest, Vol 2, Issue 2
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Fri Sep 5 14:07:46 EDT 2003
On Tue, 2 Sep 2003, Brian Christopher Robinson wrote:
> Ok, this is what I put as a member of my TagSort class:
>
> def __iter__(self):
> return self.array.__iter__()
>
> Now, this is actually wrong since it doesn't take in to account the order
> of the TagArray. But this doesn't even work at all. Instead I get the
> message:
>
> AttributeError: 'list' object has no attribute '__iter__'
>
> What's that all about?
Hi Brian,
Odd; that should have worked... Ah. Lists do have an __iter__ attribute
in Python 2.3:
###
>>> l = []
>>> l.__iter__
<method-wrapper object at 0x400e53ec>
###
But they don't appear to have one in 2.2:
###
>>> l = []
>>> l.__iter__
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'list' object has no attribute '__iter__'
###
It looks like the implementers did more polishing up of the class/type
stuff in Python 2.3; I didn't expect this not to work in 2.2!
But there's a way of writing it so it works with both:
def __iter__(self):
return iter(self.array)
> def tagSort(array):
> copy = array[:] # copies the array
> copy.sort()
> indexes = []
> for number in copy:
> indexes.append(array.index(number))
> return indexes
>
> Which works great. My friend was opposed to the copy, though, so I
> wrote this:
There's a small bug here: it doesn't work if there are duplicates in our
original array:
###
>>> tagSort([1,1,1,1,1])
[0, 0, 0, 0, 0]
###
Instead of array.index(), we'd need to cook up our own function that uses
the 'is' operator instead of the '==' operator:
###
>>> "4" + "2" == "42"
1
>>> "4" + "2" is "42"
0
###
Talk to you later!
More information about the Tutor
mailing list