[Tutor] Chutes & Ladders

Steven D'Aprano steve at pearwood.info
Mon Dec 23 12:18:56 CET 2013


On Mon, Dec 23, 2013 at 01:07:15AM -0500, Keith Winston wrote:
> On Sun, Dec 22, 2013 at 3:04 PM, <tutor-request at python.org> wrote:
> 
> >
> > games = [p1.gameset(gamecount) for _ in range(multicount)]
[...]
> But in my haste I included the line above, cut & pasted from his
> suggestion, without understanding what the underscore is doing in there.

It's just a name. Names in Python can include alphanumeric characters 
and the underscore, and they can start with an underscore.

There is a convention to use _ as a "don't care" name for variables 
which aren't used. Some languages have a loop like:

repeat 5 times:
    ...

where there is no loop variable. Python isn't one of those languages, so 
the closest is to flag the loop variable as something we don't care 
about.


> I think I understand that at the prompt of the interpreter the underscore
> returns the last value returned... 

Correct. That's another convention for the single underscore. There's a 
third: _() as a function is used for translating strings from one 
language (say, English) to another language (say, German).



> but I can't really figure out what it's
> doing here.
> 
> Also: this statement worked fine:
> 
> for tmulti in games:
>     print("{moves:9.2f} {chutes:12.2f} {ladders:13.2f}".format(
>             moves=mean(tgset[1] for tgset in tmulti),
>             chutes=mean(tgset[2] for tgset in tmulti),
>             ladders=mean(tgset[3] for tgset in tmulti)
>             ))
> 
> Which is sort of awesome to me, but in my efforts to riff on it I've been
> stumped: 

Break it up into pieces:

template = "{moves:9.2f} {chutes:12.2f} {ladders:13.2f}"
m = mean(tgset[1] for tgset in tmulti)
c = mean(tgset[2] for tgset in tmulti)
l = mean(tgset[3] for tgset in tmulti)
message = template.format(moves=m, chutes=c, ladders=l)
print(message)


> if I want to further process the arrays/lists my list
> comprehensions are generating, I sort of can't, since they're gone: that
> is, if I wanted to use the entire len(tmulti) of them to determine grand
> total averages and variances, I can't. 

I'm not entirely sure I understand what you are trying to say, but you 
can always save your list comprehension, then calculate with it:

moves = [tgset[1] for tgset in tmulti]
average_moves = mean(moves)
variance_moves = variance(moves)


> And if my array is large, I woudn't
> want to iterate over it over and over to do each of these steps, I think.

True, but I think that your idea of "large" is probably not so very 
large compared to what the computer considers large.

If speed is an issue, you can calculate both the mean and variance with 
a single pass over the data (although potentially with a loss of 
accuracy).


-- 
Steven


More information about the Tutor mailing list