Re: Feedback on Until recipe



Thomas Nelson wrote:
Occasionally someone posts to this group complaining about the lack of
"repeat ... until" in python. I too have occasionally wished for such
a construct, and after some thinking, I came up with the class below.
I'm hoping to get some feedback here, and if people besides me think
they might use it someday, I can put it on the python cookbook. I'm
pretty happy with it, the only ugly thing is you have to use a
lambda. Ideally i'd like to just see
while Until(i<3)
but that doesn't work.
Please tell me what you think, and thanks for your time.

Tom

class Until:
"""
>>> i = 0
>>> while Until(lambda: i<3):
... print "hello"
... i += 1
hello
hello
hello
>>> while Until(lambda: i<2): #note i still equals 3 here
... print "hello"
hello
"""
yet = True
def __init__(self, mybool):
if self.__class__.yet or mybool():
self.__class__.yet = False
self.ans = True
else:
self.__class__.yet = True
self.ans = False

def __nonzero__(self):
return self.ans

First of all, I have to say it reads horribly. "while Until(...)" is supposed to remind us of a *repeat* loop?

Secondly it isn't really what you want because the condition is still being evaluated before the loop body is executed, when the idea of a repeat loop is to terminate the loop after at least one iteration once the condition is true. This is not strictly equivalent to your conditions. Temporal logic is tricky.

By the way, isn't it always true that self.ans == not self.__class__.yet (and why use a class variable, by the way, doesn't this stop you from using nested loops)?

That's about all I can think of offhand. Sorry if it seems a bit negative. I'm hoping it will spur you on to a better solution.

regards
Steve
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Recent Ramblings http://holdenweb.blogspot.com

.



Relevant Pages

  • Re: limited noof times execution
    ... You can put command line argument and inside your program, you can repeat ... the functionality required by a loop which has number of iterations=command ... Regards, ...
    (comp.lang.c)
  • Re: Newbie question
    ... > variable within a for loop in Python. ... > should be appended by the index of the loop. ... I think exec is what you want: ... Regards ...
    (comp.lang.python)
  • Re: Primality Testing
    ... d:= d shr 1; ... in the last loop ... Regards ...
    (borland.public.delphi.language.basm)
  • A query about list
    ... I am very new to python. ... I have a query about ... I know I can do that with a typeand a for/while loop, ... Regards, ...
    (comp.lang.python)
  • Can you introduce some book about python?
    ... appending key-value pairs to a dict (Peter ... Is Python suitable for a huge, ... >> to the list on each loop... ...
    (comp.lang.python)