"do" as a keyword
BJörn Lindqvist
bjourne at gmail.com
Thu Dec 13 07:29:16 EST 2007
On Dec 11, 2007 4:06 PM, Neil Cerutti <horpner at yahoo.com> wrote:
>
> However, did you have an specific need for a do-while construct?
> Perhaps we could show you the alternatives.
I have wanted do-while loops in exactly one kind of algorithms, when
you generate something and you have to keep trying until it gets
right. For example, generating random and non-overlapping points on a
grid:
import random
grid = dict()
for i in range(10):
while True:
x = random.randint(0, 4)
y = random.randint(0, 4)
if not (x, y) in grid:
break
grid[x, y] = 1
The loop runs one or more times until a vacant spot in the grid is
found. This type problem would be better expressed using a do-while:
import random
grid = dict()
for i in range(10):
do:
x = random.randint(0, 4)
y = random.randint(0, 4)
while (x, y) in grid
grid[x, y] = 1
--
mvh Björn
More information about the Python-list
mailing list