[Tutor] Chutes & Ladders
Peter Otten
__peter__ at web.de
Mon Dec 23 10:40:56 CET 2013
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)]
>
>
> So Peter gave me a list of suggesttions, all of which I've incorporated
> and gotten running, and it's been instructive.
>
> But in my haste I included the line above, cut & pasted from his
> suggestion, without understanding what the underscore is doing in there. I
> think I understand that at the prompt of the interpreter the underscore
> returns the last value returned... but I can't really figure out what it's
> doing here.
There is a convention (recognized by pylint) to have unused variables start
with an underscore. The shortest of these names is just the underscore. I
used it to indicate that the important thing is that gameset() is called,
not whether it is the seventh or 42nd call. Following that convention a line
counting script could look
linecount = 0
for _line in sys.stdin:
linecount += 1
print(linecount, "lines")
while a script for adding line numbers would be
lineno = 1
for line in sys.stdin
print("{:5}:".format(lineno), line, end="")
lineno += 1
> 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: 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. 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.
> Anyway, I'm just goofing on all this, for the learning value, but I'll
> appreciate any thoughts. Thanks.
You can modify the loop to
for tmulti in games:
moves = [tgset[1] for tgset in tmulti]
chutes = ...
ladders = ...
print("...".format(
moves=mean(moves),
chutes=mean(chutes),
ladders=mean(ladders)
))
> I'm also trying to speed up the program at this point: the way I've set it
> up now it builds a list of lists (of lists) of all the stats of all the
> games of all the gamesets of all the multisets. I've visually streamlined
> it some, without any effect on performance I can detect. Would using
> arrays, or tuples, or something else be likely to be faster? It's
> interesting that running it on my 8 y.o. Core 2 Duo and my 2 y.o. Core I5
> result in virtually exactly the same speed. Weird. Obviously, it's just
> doing simple math, pretty much
"Simple math" is where the overhead of CPython over languages like C is most
significant.
More information about the Tutor
mailing list