Avoiding local variable declarations?

Paul McGuire ptmcg at austin.rr.com
Thu Nov 13 20:56:07 EST 2008


On Nov 13, 6:47 pm, bearophileH... at lycos.com wrote:
> Paul McGuire:
>
> > coinflip = lambda : int(random.random()*2)
>
> I warmly suggest you to use this instead:
> randrange(2)
>
> Bye,
> bearophile

Really?  Looking at randrange, it sure seems to do a lot of work in
pursuit of handling all possible cases for specifying range
boundaries, step values, etc.  In fact, I think flipping a coin is a
common enough task that it might even merit an addition to the random
module API.  It certainly would allow us to get rid of all of these
variations on the theme, such as "if randrange(100) > 50", or
"random.choice([True,False])".  For that matter, my own obscure int
(random.random() * 2) is better implemented using a direct comparison
to random.random(), no need for multiplication, or int calls or
anything else.  Having an explicit method would also help prevent
minor erroneous bugs like "if random.random() > 0.5", given that the
range of random.random() is (0.0, 1.0] (that is, the lower half would
be 0 inclusive to 0.5 exclusive, and the upper half 0.5 inclusive to
1.0 exclusive).

If I would change anything, I think I prefer the name coin_toss over
coinflip.

So:

coin_toss = lambda : random.random() >= 0.5

-- Paul



More information about the Python-list mailing list