How to write this iterator?
Cyril Bazin
cyril.bazin at gmail.com
Tue Sep 20 06:04:42 EDT 2005
Ok!
Now, you wrote your expected results I understand better what you want to
do...
Your solution seems fine except the "except IndexError:" part.
I would have wrote:
------------------------------------------
...
except IndexError:
if self.iters:
self.i=0
else:
raise StopIteration
...
-------------------------------------------
- Use the operator "==" if you want to compare values
- if you want to test if a list is empty, test the list itself not the
length
- Also, prefer to use "while 1:" in place of "while True:" it's more
optimised since 1 is a constant and True is not a constant (but using True
works fine too)
Anyway, if you are really a python beginner, I should say your program is
very good.
Cyril
On 9/20/05, severa at sophia.dtp.fmph.uniba.sk <severa at sophia.dtp.fmph.uniba.sk>
wrote:
>
> >> Sorry, my description was not very good, I meant something behaving as:
> >>
> >> >>>example=Liter("abc","12345","XY")
> >> >>>for x in example: print x,
> >>
> >> a 1 X b 2 Y c 3 4 5
> >>
> >> or for that append() method,
> >>
> >> >>>example=Liter("abc", "12345")
> >> >>>for i in range(3): print example.next(),
> >>
> >> a 1 b
> >>
> >> >>>example.append("XY")
> >> >>>for x in example: print x,
> >>
> >> 2 c X 3 Y 4 5
>
> >Check the module I posted on
> >http://rafb.net/paste/results/CRT7bS68.html. append() makes things more
> >complicated -- mainly because generators don't accept attributes, so it
> >has to be wrapped in a class -- but the simple generator (without
> >append) is more manageable
>
> Thank you very much for your solution. Actually I needed that append()
> method quite a lot, so maybe my solution (posted at the beginning of this
> thread) was not that stupid :) (to inflate my ego a bit)
>
> Anyway, this is roughly what I used it for; is it a sane use of iterators?
>
> I was looking for the Holy Grail. I had an iterator 'quest' that produced
> either junk that was to be thrown away, or the Holy Grail itself, or
> another iterator of the same kind (that had to be searched for the Holy
> Grail as well). The iterators were potentially infinite. The code was
> rougly:
>
> quest=Liter(quest)
> for x in quest:
> if is_Holy_Grail(x):
> share_and_enjoy(x)
> break
> elif is_another_iterator(x):
> quest.append(x)
>
>
> Best regards
> P.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20050920/be021771/attachment.html>
More information about the Python-list
mailing list