Re: [Tutor] What's in a name?

2014-01-03 Thread Keith Winston
Below you will find the full current version of my Chutes or Snakes &
Ladders game. I tried to reorganize it into a more OOP structure, and I
think I started succeeding, and then something might have gone wrong. There
is also something somewhat seriously wrong with it: if I run it as
__main__, it works fine, but if I run it after I've loaded it (by
candl(100) at the prompt, for example), it is way off: something isn't
being reset, and I'm sure it'd be obvious to someone, and I'm going to look
back at it, but I can't figure it out yet. Anyway, thanks for all the help
so far, I'll probably add persistence, maybe trivial GUI, and definitely
more stats/analysis (well, almost definitely)...


""" Chutes & Ladders Simulation
Simulates a number of games of Chutes & Ladders (Snakes & Ladders).
Chutes & Ladders are separate dictionaries to allow tracking of
separate stats.

Gathers the results into a list of lists of individual game results
in the form (per game) of [game_no, moves, len(chutes), len(ladders),
[chutes], [ladders]]

There is some info redundancy in the list with the len members:
[chutes] and [ladders]
are lists of the actual chutes and ladders encountered in each game
(named by key)
"""

import random
from timer2 import timer
from statistics import * # from whence comes mean, variance, stdev


# Landing on a chute causes one to slide down to the corresponding value.
chutes = {16: 6, 47: 26, 49: 11, 56: 53, 62: 19, 64: 60, 87: 24, 93: 73,
95: 75, 98:78}

# Landing on a ladder (key) causes one to climb up to the corresponding
value.
ladders = {1: 38, 4: 14, 9: 31, 21: 42, 28: 84, 36: 44, 51: 67, 71: 91,
80:100}

class games:
"""Game class for Chutes & Ladders."""

def __init__(self):
self.reset()

def reset(self):
self.move_count = 0
self.num_chutes = 0
self.num_ladders = 0
self.chutes_list = []
self.ladders_list = []

#@timer
def move(self):
"""Single move, with chutes, ladders, & out of bounds.
Primary action is to move self.position, but returns a list
that consists of either the chute or ladder if landed on, if either
"""

roll = random.randint(1,6)
tchutes = 0
tladders = 0
self.move_count += 1
self.position += roll
if self.position in chutes:
tchutes = self.position
self.position = chutes[self.position]
self.num_chutes += 1
elif self.position in ladders:
tladders = self.position
self.position = ladders[self.position]
self.num_ladders += 1
elif self.position > 100:  # move doesn't count, have to land
exactly
self.position -= roll
return [tchutes, tladders]  # only one will be != 0

#@timer
def play_game(self, step):
"""Single game"""

self.position = 0
self.reset()
while self.position < 100:
gamecandl = self.move()  # [chute, ladder] or [0, 0]
if gamecandl[0] != 0: # populate chutes list
self.chutes_list.append(gamecandl[0])
if gamecandl[1] != 0:  # populate ladders list
self.ladders_list.append(gamecandl[1])
return [step, self.move_count, self.num_chutes, self.num_ladders,
self.chutes_list, self.ladders_list]

#@timer
def play_gameset(self, gamecount1):
"""A set of games, returning associated stats array"""

return [self.play_game(i) for i in range(gamecount1)]


def candl(gamecount2):
""" play a mess of games, return the results array """

gname = games()
game_array = gname.play_gameset(gamecount2)
print_gameset_stats(game_array)
print_candl_info(game_array)
#print(game_array)

def print_gameset_stats(garray):

print("Total number of games: ", len(garray))
print("   MovesChutesLadders")
for func in [mean, max, min, variance, stdev]:
print("{moves:9.2f} {chutes:12.2f} {ladders:13.2f}
{stype}".format(
moves=func(tgset[1] for tgset in garray),
chutes=func(tgset[2] for tgset in garray),
ladders=func(tgset[3] for tgset in garray),
stype=func.__name__
))

def timing_report():

print("game.total, count = ", p1.game.total, p1.game.count)
print("move.total, count = ", p1.move.total, p1.move.count)

def print_candl_info(garray):
""" Create two dictionaries with the same keys as chutes & ladders,
but with the total number of times each c or l is traversed (in the
entire gameset)
as the values. Then, print them. """

chute_nums, ladder_nums = chutes, ladders
summarize_game("chutes", chutes, 4, garray)
summarize_game("ladders", ladders, 5, garray)

def summarize_game(game_name, game_nums, game_index, garray):
for i in game_nums.keys(): game_nums[i] = 0

for corl in game_nums:
for game in garray:
i

Re: [Tutor] What's in a name?

2014-01-03 Thread Keith Winston
On Fri, Jan 3, 2014 at 2:42 AM, Danny Yoo  wrote:

>
> I hope you don't take offense.  But I actually do not understand
> print_candl_info().  I thought I did!  But then I realized I was
> deluding myself.  I don't not understand it after all, and that's
> after staring at it for more than about thirty minutes.
>
>
I dare you to try to offend me, while offering helpful comments! Okay, I
take that back. Anyway, no I don't.


> Take that a "canary in the coalmine" kind of comment.  eval() can
> encourages habits that hurt program readability in a deep way.
>
> Fair enough.


> where we first unroll the original's outer loop out so that there are
> no eval()s anywhere.  This hurts program length a little, but we can
> deal with that.  Do you agree so far that the program above preserves
> the meaning of what you had before?
>
>
Ha ha, you must understand, because you recreated the original form of the
code. First, realize that this is all a learning exercise for me, I am not
actually obsessed by Chutes & Ladders. So I was trying to figure out if I
could do this thing of iterating over a list of (functions, lists,
dictionaries) and print both some output related to the object, and the
objects name. But I think you now understand that. In this _particular_
case, I've got that little list_index kluge, which is probably good, since
it sort of forces me to try to solve a more general case (or get other
people to!... er, thanks!)


>
> If we can assume that the rewritten code "means" the same thing, then
> we can eliminate the duplication by doing something like this:
>
> 
> def print_candl_info(garray):
> game_array, chute_nums, ladder_nums = {}, chutes, ladders
> for i in chute_nums.keys(): chute_nums[i] = 0
> for i in ladder_nums.keys(): ladder_nums[i] = 0
>
> summarize_game("chutes", chute_nums, 4, garray)
> summarize_game("ladders", ladder_nums, 5, garray)
>
>
I see what you did there.


> Hmmm.  I don't understand why chute_nums is assigned to chutes, nor
> ladder_nums to ladders, and I don't see game_array being used here
> yet.  We can absorb that:
>
>
>
Yes, game_array was left over, sorry. But chutes and ladders are
dictionaries that should remain unchanged, for the purpose of future games.
chute_nums = chutes only b/c that was an easy way to fill in all the keys:
I then zero out the values, and increment the values for every time any
given chute or ladder is traversed during a game (this information is in
game[4] and game[5], each of which are lists of the chutes or ladders
traversed in each given game). I hope that's clear. So I think you can't
lose that, or you'd have to fill in those keys differently (which is how I
did it at first, but this approach seemed cleaner).


> def print_candl_info(garray):
> summarize_game("chutes", chutes, 4, garray)
> summarize_game("ladders", ladders, 5, garray)
>
> def summarize_game(game_name, game_nums, game_index, garray):
> for i in game_nums.keys(): game_nums[i] = 0
>
> for corl in game_nums:
> for game in garray:
> if corl in game[game_index]:
> game_nums[corl] += 1
> print("total ", game_name, "= ", sum(game_nums.values()))
> 
>
>
This is definitely an improvement, IMO. Summarize_game is _almost_ a really
good name, but it isn't really summarizing a single game: it's iterating
over all the games in garray (the array of games), and adding up all the
particular chutes and ladders occurrences, if I haven't already made that
clear... It's sneaky like that. I'm tempted to say summarize_candl, but
candl is getting boring... I'll leave it for now.



> As a side note: the code above has more latitude than the original
> because it can print out a friendlier game name.  That is, for
> example, you can do this:
>
> ##
> summarize_game(" Chutes! ", chutes, 4, garray)
> summarize_game(" Ladders! ", ladders, 5, garray)
> ##
>


Yep, true that.

Thanks Danny, this was instructive. Very kind of you.
-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: What's in a name?

2014-01-03 Thread Asokan Pichai
On Fri, Jan 03, 2014 at 02:45:04AM -0500, Keith Winston wrote:
> And to beat that poor horse in the same example, my current way of doing
> that would be:
> 
> for alist in "lista", "listb":
> print(alist, eval(alist))

Since you know both pieces, namely the name of the entity "alist" and its 
actual symbol aka alist, why not do something like:

Lists = {"lista": lista, "listb": lisb}

and use
Lists[x] ...

HTH

Asokan Pichai

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What's in a name?

2014-01-03 Thread Danny Yoo
> it works fine, but if I run it after I've loaded it (by candl(100) at the
> prompt, for example), it is way off: something isn't being reset, and I'm
> sure it'd be obvious to someone,

It's due to global variable mutation.  Note that summarize_game()
mutates game_nums, which is either chutes or ladders.  Basically, it
writes all over the structure of the game board, which means
subsequent play throughs are a wash.  :P

And you know this, from your comment:

> Yes, game_array was left over, sorry. But chutes and ladders are
> dictionaries that should remain unchanged, for the purpose of
> future games.

But to be fair, this problem was also present in the original version
of the code, before my meddling.


This is relatively straightforward to fix: just modify summarize_game
so it creates a fresh dictionary mimicking the key structure of the
entry points.  That way, it doesn't mess with chutes and ladders.

##
def summarize_game(game_name, game_map, game_index, garray):
game_nums = {}
for i in game_map.keys(): game_nums[i] = 0
for corl in game_nums:
for game in garray:
if corl in game[game_index]:
game_nums[corl] += 1
print("total ", game_name, "= ", sum(game_nums.values()))
##


In the context of the full program, I now understand why you have "4"
and "5" as mysterious constants now.  Good.  It's due to the structure
of the return value of games.play_game().

#
return [step, self.move_count, self.num_chutes, self.num_ladders,
self.chutes_list, self.ladders_list]
#

That is, this awkwardness of indexing by number to get at chutes_list
and ladders_list is due to that result wanting not to be in a
homogenous list or sequence.  The return value there *really* wants to
be something more like a dictionary or object instead.


Don't have time at the moment to sketch more than that; must sleep so
I can work tomorrow.  :P
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What's in a name?

2014-01-03 Thread Danny Yoo
Quick thing.  Please look at the following small program:

#
d1 = {1 : 'one'}
d2 = d1
d2[2] = 'two'
print(d1)
print(d2)
#

Predict what this prints out.  Write your prediction on a piece of paper.

Then run the program.  Does it match what you wrote?

If not, start asking questions.  If so, then I'm puzzled.  :P



The reason I ask is because of the comment:

> But chutes and ladders are dictionaries that should remain
> unchanged, for the purpose of future games.

which has several meanings that I did not anticipate.  So I need to
make sure you're ok on all those things.  :P
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Mastering the fundamentals

2014-01-03 Thread Christian Alexander
Hello Tutorians,

I've just recently acquired "Learning Python", and I must state that it is
a fairly thorough book.  However it seems as if I am learning at a very
slow pace, so my question is, as far as setting a goal to master the
basics, where should I be within a years time?  Assuming I spend at least 2
hours of actual coding time per day.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] sqlite3 import problem

2014-01-03 Thread Alan Gauld

On 03/01/14 02:17, Matthew Ngaha wrote:

im having problems importing sqlite3 on ubuntu python3.

   File "/usr/local/lib/python3.3/sqlite3/__init__.py", line 23, in 
 from sqlite3.dbapi2 import *
   File "/usr/local/lib/python3.3/sqlite3/dbapi2.py", line 26, in 
 from _sqlite3 import *
ImportError: No module named '_sqlite3'


As a matter of interest why do you have the underscore in front of 
sqlite3? Is that deliberate?


I normally import it with just

import sqlite3
or
from sqlite3 import ...



--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What's in a name?

2014-01-03 Thread Alan Gauld

On 03/01/14 08:37, Keith Winston wrote:

Below you will find the full current version of my Chutes or Snakes &
Ladders game. I tried to reorganize it into a more OOP structure,


This is off topic but a couple of points about the OOP stuff...

Its normal style to name classes with a capital letter so it
would be Games not games.

It's also better to name classes as a singular. They create
a single object not many so it would really be Game not Games.

Finally the class name should be specific to what the class
is. You class is not a generic game class its very specifically
a ChutesAndLadders game class.

So a better name is

class ChutesAndLadders:...

Finally, one comment that is more apropos to the current thread.
You started by saying:

"If I'm iterating a variable through a series of list names,
for future processing, I would like to print the name of the
list the variable is set to in a given moment... "

Remember that variables in Python are just names.
So we can rewrite your statement as

"If I'm iterating a name through a series of list names, for future 
processing, I would like to print the name of the list the name is set 
to in a given moment... "


And since the list names are just strings we can write:

"If I'm iterating a name through a list of strings, for future 
processing, I would like to print the name in a given moment...


So the answer to your question is just to print the string.
The real challenge, as we have discovered, is how to access
the list that is named by the string. And the usual way to
map strings to objects is via a dictionary not by using eval().

Which kind of takes us back to where we were...



class games:
 """Game class for Chutes & Ladders."""

 def __init__(self):
 self.reset()

 def reset(self):
 self.move_count = 0
 self.num_chutes = 0
 self.num_ladders = 0
 self.chutes_list = []
 self.ladders_list = []


Do you really need the num_xxx variables?
Using len(xxx_list) is more reliable that depending on your
code to maintain the values. It may be that you need them
for a performance optimisation but given that games are
not normally CPU bound that seems unlikely.

Or does num_xxx indicate something different?
Looking briefly at the move()  code it may be they
represent the number of xxx encountered during the game?


 def move(self):
 """Single move, with chutes, ladders, & out of bounds.
 Primary action is to move self.position, but returns a list
 that consists of either the chute or ladder if landed on, if either
 """

 roll = random.randint(1,6)
 tchutes = 0
 tladders = 0
 self.move_count += 1
 self.position += roll
 if self.position in chutes:
 tchutes = self.position
 self.position = chutes[self.position]
 self.num_chutes += 1
 elif self.position in ladders:
 tladders = self.position
 self.position = ladders[self.position]
 self.num_ladders += 1
 elif self.position > 100:  # move doesn't count, have to land
exactly
 self.position -= roll
 return [tchutes, tladders]  # only one will be != 0


I don't understand the tchutes/tladders stuff? They hold the
target position or zero (the return comment is wrong BTW since both
could be zero). Why not just have a single variable called target
or somesuch? Also if you must return two values its probably better to 
use a tuple rather than a list.



 def play_game(self, step):
 """Single game"""


Since this is part of a games/Game/ChutesAndLadders class you probably 
don't need the '_game' bit of the name, it doesn't convey any extra 
information. Just a thought...



 self.position = 0
 self.reset()


Shouldn't the self.position assignment be part of reset()?


 while self.position < 100:
 gamecandl = self.move()  # [chute, ladder] or [0, 0]
 if gamecandl[0] != 0: # populate chutes list
 self.chutes_list.append(gamecandl[0])
 if gamecandl[1] != 0:  # populate ladders list
 self.ladders_list.append(gamecandl[1])


Why don't you do this update of the lists in the move() code.
It's where it logically happens and saves passing back the
list/tuple and then having to test it here.  This just adds
extra work.


 return [step, self.move_count, self.num_chutes,
self.num_ladders, self.chutes_list, self.ladders_list]


In OOP you rarely have to return attributes. And since step
is passed in as an argument the caller already knows. So I
don't think you really need to return anything here.


#@timer
 def play_gameset(self, gamecount1):
 """A set of games, returning associated stats array"""

 return [self.play_game(i) for i in range(gamecount1)]


OK, I see now, you are storing the current state values
after each game. Personally I'd probably create

Re: [Tutor] Mastering the fundamentals

2014-01-03 Thread Alan Gauld

On 03/01/14 08:30, Christian Alexander wrote:


I've just recently acquired "Learning Python", and I must state that it
is a fairly thorough book.  However it seems as if I am learning at a
very slow pace, so my question is, as far as setting a goal to master
the basics, where should I be within a years time?


It depends on where you start from. Can you program in other languages?
If so you should be very comfortable with Python programming in a year
(probably much less).

If you have never programmed before then Learning Python may not be the 
best tutorial since it assumes quite a lot of programming jargon etc is 
understood but if you persevere you should know the language well enough 
to write moderate sized programs (a few hundred lines say).


Is that meaningful? Maybe not.
To try a musical analogy, after a year you should be able to play 
simplified versions of popular tunes well enough that your friends 
recognize them and sing along. You could probably even try busking
in the street for pennies. But you probably aren't going to be getting 
signed by Simon Cowell anytime soon.


hth
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] sqlite3 import problem

2014-01-03 Thread Matthew Ngaha
On Fri, Jan 3, 2014 at 10:36 AM, Alan Gauld  wrote:
> On 03/01/14 02:17, Matthew Ngaha wrote:
>>
>> im having problems importing sqlite3 on ubuntu python3.
>>
>>File "/usr/local/lib/python3.3/sqlite3/__init__.py", line 23, in
>> 
>>  from sqlite3.dbapi2 import *
>>File "/usr/local/lib/python3.3/sqlite3/dbapi2.py", line 26, in 
>>  from _sqlite3 import *
>> ImportError: No module named '_sqlite3'
>
>
> As a matter of interest why do you have the underscore in front of sqlite3?
> Is that deliberate?
>
> I normally import it with just
>
> import sqlite3
> or
> from sqlite3 import ...

Hi Alan. The code in the traceback is being done internally. my code
has "import sqlite3". Python finds it in this directory:

/usr/local/lib/python3.3/sqlite3/

and runs the code from the traceback. I have no idea why it's using _sqlite3:(

On Fri, Jan 3, 2014 at 6:12 AM, Kushal Kumaran
 wrote:
> The /usr/local heirarchy is not used by official debian/ubuntu packages,
> so other people will not have the same contents in there as you.  You
> must have a locally built python in /usr/local.  Check the build logs if
> it has complained about not being able to build the sqlite3 module.  If
> so, you can install all build dependencies for the offical python3
> package by running this command:
>
> # apt-get build-dep python3
>
> And then rebuilding your local python3 installation.
>

On Fri, Jan 3, 2014 at 3:00 AM, Danny Yoo  wrote:
> This might be an Ubuntu bug or deficiency.

Hi, Danny & Kushal.
Originally i only had python 2.7 and 3.2 as default for Ubuntu. Kushal
you're right my 3.2 has a different path to sqlite3 than

/usr/local/lib/python3.3/sqlite3/

Infact i haven't been able to find its location. 3.2 imports sqlite3
with no errors. I'm currently not on ubuntu to try your instruction.
Will the build logs be inside the python3.3 directory? I'm still new
to linux so sorry for newbie questions. it took me a very long time to
get it right when building python3.3. When you say rebuild, is there a
command for doing that or do you mean simply uninstall python then
build it again?

On Fri, Jan 3, 2014 at 10:36 AM, Alan Gauld  wrote:
> On 03/01/14 02:17, Matthew Ngaha wrote:
>>
>> im having problems importing sqlite3 on ubuntu python3.
>>
>>File "/usr/local/lib/python3.3/sqlite3/__init__.py", line 23, in
>> 
>>  from sqlite3.dbapi2 import *
>>File "/usr/local/lib/python3.3/sqlite3/dbapi2.py", line 26, in 
>>  from _sqlite3 import *
>> ImportError: No module named '_sqlite3'
>
>
> As a matter of interest why do you have the underscore in front of sqlite3?
> Is that deliberate?
>
> I normally import it with just
>
> import sqlite3
> or
> from sqlite3 import ...
>
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.flickr.com/photos/alangauldphotos
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] sqlite3 import problem

2014-01-03 Thread Mark Lawrence

On 03/01/2014 10:36, Alan Gauld wrote:

On 03/01/14 02:17, Matthew Ngaha wrote:

im having problems importing sqlite3 on ubuntu python3.

   File "/usr/local/lib/python3.3/sqlite3/__init__.py", line 23, in

 from sqlite3.dbapi2 import *
   File "/usr/local/lib/python3.3/sqlite3/dbapi2.py", line 26, in

 from _sqlite3 import *
ImportError: No module named '_sqlite3'


As a matter of interest why do you have the underscore in front of
sqlite3? Is that deliberate?

I normally import it with just

import sqlite3
or
from sqlite3 import ...



You surprise me Alan, this is an oft used idiom in Python.  A typical 
example would be having a fast C module but if this can't be imported 
fall back to a Python implementation.


--
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.


Mark Lawrence

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Mastering the fundamentals

2014-01-03 Thread Al-Sahaf, Ahmed H.
Hi Christian,

You can start with Google Python Class

https://developers.google.com/edu/python/

Best regards,
Ahmed
On Jan 3, 2014 1:29 PM, "Christian Alexander" <
christian.h.alexan...@gmail.com> wrote:

> Hello Tutorians,
>
> I've just recently acquired "Learning Python", and I must state that it is
> a fairly thorough book.  However it seems as if I am learning at a very
> slow pace, so my question is, as far as setting a goal to master the
> basics, where should I be within a years time?  Assuming I spend at least 2
> hours of actual coding time per day.
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] sqlite3 import problem

2014-01-03 Thread Alan Gauld

On 03/01/14 13:36, Mark Lawrence wrote:


   File "/usr/local/lib/python3.3/sqlite3/dbapi2.py", line 26, in

 from _sqlite3 import *
ImportError: No module named '_sqlite3'


As a matter of interest why do you have the underscore in front of
sqlite3? Is that deliberate?


You surprise me Alan, this is an oft used idiom in Python.  A typical
example would be having a fast C module but if this can't be imported
fall back to a Python implementation.


Yes, but that's usually hidden from the user...
I didn't look closely enough at the file names in the traceback
and assumed the OP was explicitly importing using the underscore.


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What's in a name?

2014-01-03 Thread spir

On 01/03/2014 12:41 PM, Alan Gauld wrote:



 return [step, self.move_count, self.num_chutes,
self.num_ladders, self.chutes_list, self.ladders_list]


In OOP you rarely have to return attributes. And since step
is passed in as an argument the caller already knows [it]. So I
don't think you really need to return anything here.


Maybe the intent here (except from the case of step) is to conceptually isolate 
another part of code from the current object (here a 'game'), or from this 
method (play_game). So that don't they interact in a hidden way (that one cannot 
guess from the outside, without reading code in detail). In other words, to make 
code _transparent_, which is indeed a common advice (and one I approve).


In this, to have the caller explicitely, obviously read information about the 
'game' object, one could just:

return self

However, this makes no sense if the caller the cirrent method, play_game, is 
another method of the 'game' ;-). In this case, indeed return nothing.


(All this, if I correctly understand and interpret.)

Denis
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Mastering the fundamentals

2014-01-03 Thread spir

On 01/03/2014 09:30 AM, Christian Alexander wrote:

Hello Tutorians,

I've just recently acquired "Learning Python", and I must state that it is
a fairly thorough book.  However it seems as if I am learning at a very
slow pace, so my question is, as far as setting a goal to master the
basics, where should I be within a years time?  Assuming I spend at least 2
hours of actual coding time per day.


I'd say there is no common pace. Differences between (future) programmers are 
huge. Also faster pace at a given period does not mean higher quality or 
competence eventually, and lower pace at a given period does not mean lower 
quality or competence eventually.


(This applies to any complex or creative domain.)

(I'd also say: do as you feel it; listen to, be confident in, follow your 
intuition; who alse can know what's good [pace] for you.)


Denis

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] ValueError: could not convert string to float: '13,2'

2014-01-03 Thread emile

On 12/31/2013 12:56 PM, Mark Lawrence wrote:

import locale

# Set to users preferred locale:
locale.setlocale(locale.LC_ALL, '')
# Or a specific locale:
locale.setlocale(locale.LC_NUMERIC, "en_DK.UTF-8")
print(locale.atof("3,14"))



This is a good solution, but be aware that it could impact other parts 
of your porgram as well, particularly if this is a read in data set from 
a non-local region.  Also, in places where commas are used as decimal 
points, it's also common to use periods as commas:


>>> print(locale.atof("123.456,14"))
123456.14

Emile





___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] ValueError: could not convert string to float: '13,2'

2014-01-03 Thread eryksun
On Fri, Jan 3, 2014 at 11:53 AM, emile  wrote:
> On 12/31/2013 12:56 PM, Mark Lawrence wrote:
>>
>> import locale
>>
>> # Set to users preferred locale:
>> locale.setlocale(locale.LC_ALL, '')
>> # Or a specific locale:
>> locale.setlocale(locale.LC_NUMERIC, "en_DK.UTF-8")
>> print(locale.atof("3,14"))
>
> This is a good solution, but be aware that it could impact other parts of
> your porgram as well, particularly if this is a read in data set from a
> non-local region.  Also, in places where commas are used as decimal points,
> it's also common to use periods as commas:
>
 print(locale.atof("123.456,14"))
> 123456.14

If you're writing a library, don't modify the process locale. That's
for an application to set, preferably only once at startup. Use some
other library such as ICU:

>>> import icu

>>> lc = icu.Locale.createCanonical('da_DK.utf-8')
>>> lc.getDisplayLanguage()
'Danish'
>>> lc.getDisplayCountry()
'Denmark'

>>> nf = icu.NumberFormat.createInstance(lc)
>>> nf.parse('123.456,14').getDouble()
123456.14

http://userguide.icu-project.org/locale
http://userguide.icu-project.org/formatparse/numbers
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What's in a name?

2014-01-03 Thread Keith Winston
On Fri, Jan 3, 2014 at 4:50 AM, Danny Yoo  wrote:

> Quick thing.  Please look at the following small program:
>
> #
> d1 = {1 : 'one'}
> d2 = d1
> d2[2] = 'two'
> print(d1)
> print(d2)
> #
>
> Predict what this prints out.  Write your prediction on a piece of paper.
>
> Then run the program.  Does it match what you wrote?
>
> If not, start asking questions.  If so, then I'm puzzled.  :P
>
>
> Thanks Danny: I understand this issue when I'm looking right at it, but it
can still slip past me with a moments inattention... as soon as you pointed
it out, I bruised my forehead by slapping it so hard. Thanks.

Actually, it's funnier than that: I now notice that the code I swiped from
you passes the original arrays, not even the "copies" which aren't copies.
That's what I meant to do: make a copy when I wrote chute_nums = chutes. So
I should have passed chute_nums to summarize_game, but it still wouldn't
work (because it's not a copy). More below.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What's in a name?

2014-01-03 Thread Keith Winston
On Fri, Jan 3, 2014 at 9:03 AM, spir  wrote:

> On 01/03/2014 12:41 PM, Alan Gauld wrote:
>
>>
>>   return [step, self.move_count, self.num_chutes,
>>> self.num_ladders, self.chutes_list, self.ladders_list]
>>>
>>
>> In OOP you rarely have to return attributes. And since step
>> is passed in as an argument the caller already knows [it]. So I
>>
>> don't think you really need to return anything here.
>>
>
Alas, it's uglier than all that, and probably inherently non-OOP organized.
The calling method DOES know the step variable (attribute? it's not part of
a class, is it still an attribute?), since it's using it to iterate through
a list: but that variable is gone by the time the play_game returns, and
yet I want to ensconce it in the data structure to keep track of the
different games... And so I pass it in to save it to the data structure.
It's ugly, and probably not the right way to do that (post script: I think
I figured this out below).

Calling method:
return [self.play_game(i) for i in range(gamecount1)]

   def play_game(self, step):
# various stuff happens, but step is just passed through to be
stored in the structure that the calling method is contributing to
return [step, self.move_count, self.num_chutes, self.num_ladders,
self.chutes_list, self.ladders_list]



> Maybe the intent here (except from the case of step) is to conceptually
> isolate another part of code from the current object (here a 'game'), or
> from this method (play_game). So that don't they interact in a hidden way
> (that one cannot guess from the outside, without reading code in detail).
> In other words, to make code _transparent_, which is indeed a common advice
> (and one I approve).
>
> In this, to have the caller explicitely, obviously read information about
> the 'game' object, one could just:
> return self
>
> However, this makes no sense if the caller the cirrent method, play_game,
> is another method of the 'game' ;-). In this case, indeed return nothing.
>
> (All this, if I correctly understand and interpret.)
>
> Denis


Well, I sort of mangle OOP still. Here's the issue: I have this play_game
method of Game, which returns/fills in the "results" of a game in the form
of a list of ints & lists. What I though I want is to play lots of games,
gather all those game "results" into a big array (just another list really,
of course), and then do stats/analsis on that array. But I think my
thinking is broken here: I am trying to create a list of game results,
whereas I should be creating a list of games (with their corresponding
attributes)... And that should happen altogether outside the Game glass. I
imagine I should have another class for that, say GameArray... but that's
just a first thought on the next reorganization...

So I guess my Game class should have an attribute like game_number,
corresponding to step variable above, and GameArray should do something
like...

game1 = Game() # instance of Game
for i in range(gamecount): game_array[i] = game1.play_game(i)

(inside play_game: self.game_number = i)

And I guess GameArray can hold all the stats/analysis/printing functions,
since that's the object they operate on...

This sounds like the right direction here, but I don't completely trust my
own thinking yet on this stuff. In retrospect, my need for a reset method
probably indicated I was going the wrong direction, and probably popped up
as soon as I tried to deal with a multitude of games within the Game class
itself.

thanks as always!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] idle problem

2014-01-03 Thread I. Alejandro Fleischer
Hello to everyone,

Sudenly Im having troubles opening files with the idle editor. When I open
a file it appears in blank, and can not close it anymore.

My OS is ubuntu 13.10 (64 bits) and my python version is 2.7.5.

Regards,

Igor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] idle problem

2014-01-03 Thread eryksun
On Fri, Jan 3, 2014 at 2:35 PM, I. Alejandro Fleischer
 wrote:
>
> Sudenly Im having troubles opening files with the idle editor. When I open a
> file it appears in blank, and can not close it anymore.
>
> My OS is ubuntu 13.10 (64 bits) and my python version is 2.7.5.

Maybe something is wrong with a configuration file. Try renaming the
.idlerc directory:

mv ~/.idlerc ~/.idlerc.bak
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What's in a name?

2014-01-03 Thread Keith Winston
On Fri, Jan 3, 2014 at 6:41 AM, Alan Gauld wrote:

> This is off topic but a couple of points about the OOP stuff...
>
>
thanks Alan, this was helpful.



> "If I'm iterating a variable through a series of list names,
> for future processing, I would like to print the name of the
> list the variable is set to in a given moment... "
>
> Remember that variables in Python are just names.
> So we can rewrite your statement as
>
> "If I'm iterating a name through a series of list names, for future
> processing, I would like to print the name of the list the name is set to
> in a given moment... "
>
> And since the list names are just strings we can write:
>
> "If I'm iterating a name through a list of strings, for future processing,
> I would like to print the name in a given moment...
>
> So the answer to your question is just to print the string.
> The real challenge, as we have discovered, is how to access
> the list that is named by the string. And the usual way to
> map strings to objects is via a dictionary not by using eval().
>
>
Here's the thing: I think most of my "problems" go away with better design.
But in case I'm wrong, what I was trying to do, which I would think could
sometimes be helpful, is printing the name of an object along with it's
output/results... I don't think there's any way to do the opposite of
eval(), that is, create a string from an object name. Or am I just missing
something here (I THINK the right way to do this is add, if necessary, and
__name__ method, or at least a .name attribute, to the class... though now
that I think about it I think that still doesn't solve the problem, it
names the class not the instance.

Do you really need the num_xxx variables?
> Using len(xxx_list) is more reliable that depending on your
> code to maintain the values. It may be that you need them
> for a performance optimisation but given that games are
> not normally CPU bound that seems unlikely.
>
>
It was something between performance optimization and historical artifact.
I'm pretty sure the effect of it's optimization was to slow the program
down. It/they are redundant.


>
>  return [tchutes, tladders]  # only one will be != 0
>>
>
> I don't understand the tchutes/tladders stuff? They hold the
> target position or zero (the return comment is wrong BTW since both
> could be zero). Why not just have a single variable called target
> or somesuch? Also if you must return two values its probably better to use
> a tuple rather than a list.
>
>
Oh god, you are airing all my dirty laundry. On each move, the position
might be a chute, or a ladder, or neither. After I use that position to
determine if it's a chute or ladder, it seems like it makes sense to store
that info explicitly, to avoid another dictionary lookup. Probably another
optimization mistake. So if the first returned list entry has a number in
it, it's a chute, and add it to the list of chutes this game traversed, and
same with the second entry and ladder... I suspect I should do this
entirely differently.


>
> Shouldn't the self.position assignment be part of reset()?
>
>
It used to be, but then I realized it's not a state I need to save: I meant
to change it to a local variable.


>
>   while self.position < 100:
>>  gamecandl = self.move()  # [chute, ladder] or [0, 0]
>>  if gamecandl[0] != 0: # populate chutes list
>>  self.chutes_list.append(gamecandl[0])
>>  if gamecandl[1] != 0:  # populate ladders list
>>  self.ladders_list.append(gamecandl[1])
>>
>
> Why don't you do this update of the lists in the move() code.
> It's where it logically happens and saves passing back the
> list/tuple and then having to test it here.  This just adds
> extra work.
>
>
Hmm. That seems like a good point. I think it all shifts when I properly
implement the Game() class. Next draft.


>
>   return [step, self.move_count, self.num_chutes,
>> self.num_ladders, self.chutes_list, self.ladders_list]
>>
>
> In OOP you rarely have to return attributes. And since step
> is passed in as an argument the caller already knows. So I
> don't think you really need to return anything here.


Yes, reading this is what helped me see the direction of the next rewrite.
Thanks.


>
> OK, I see now, you are storing the current state values
> after each game. Personally I'd probably create another
> method called (get_stats() or similar and have play() return
> success/failure.
>
>
o success or failure. You're edging me towards exception handling.

Then your line above would be:
>
> return [self.get_stats() for i in range(gamecount) if self.play()]
>
> It keeps the purpose of the methods explicit. play() plays the game,
> get_stats() returns the data.
>
> But there is another more OOP approach.
> Create a game instance for each iteration.
> Then collect the instances which then hold the data.
> No need for all the extra arrays, return values, etc.
> It's by using and passing

[Tutor] python, speed, game programming

2014-01-03 Thread Keith Winston
-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python, speed, game programming

2014-01-03 Thread Keith Winston
Shoot, sorry for the empty message. Here's what I was going to say:

I am gearing up for the next project (yeah, an eventual end to Chutes &
Ladders!). It is a typing tutor, I am inclined to use it to learn Dvorak
but I would expect it easily adapted to QWERTY or anything else.

The basic idea is build a database of the key and response time of every
keystroke, with simultaneous background processing going on, based on a
customizable set of parameters to select the test text in more or less real
time. So for example, I might wish to adjust the interval at which I
revisit old material, to be sure I "get" it without becoming bored by it:
we could call this the repetition interval, and it might well be a function
that increases with time, though it might also be keyed to the speed of
recall... all responses are to be saved long-term for subsequent analysis.

My concern is with speed. This will have to keep up with (somewhat
arbitrarily) fast typing, while doing background processing, with a GUI of
course. This illustrates why I was concerned about the fact that my Chutes
& Ladders game seems to run at the same speed on my 8 y.o. Core 2 Duo and
my 2 y.o. Core I7 with 3-4x as much memory. This WILL require a faster
machine and a more significant share of it's resources, if I develop it in
the direction I am thinking.

I hope Python is a good choice here, though I suppose some modules or
classes or parts will have to be recoded into something faster... Any
thoughts on this will be appreciated, including how to structure it in such
a manner that it might be more portably applied to future versions in
entirely different knowledge realms (music/midi input,
language/vocabulary/audio output, etc).

-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python, speed, game programming

2014-01-03 Thread Keith Winston
Just to be clear: this is equal parts learning Python project, prototype
tutorial software project, OOP practice, and the beginning of a more
general inquiry into learning styles/paradigms/parameters... I'm (slowly)
writing some of these ideas up in a separate doc.


On Fri, Jan 3, 2014 at 4:53 PM, Keith Winston  wrote:

> Shoot, sorry for the empty message. Here's what I was going to say:
>
> I am gearing up for the next project (yeah, an eventual end to Chutes &
> Ladders!). It is a typing tutor, I am inclined to use it to learn Dvorak
> but I would expect it easily adapted to QWERTY or anything else.
>
> The basic idea is build a database of the key and response time of every
> keystroke, with simultaneous background processing going on, based on a
> customizable set of parameters to select the test text in more or less real
> time. So for example, I might wish to adjust the interval at which I
> revisit old material, to be sure I "get" it without becoming bored by it:
> we could call this the repetition interval, and it might well be a function
> that increases with time, though it might also be keyed to the speed of
> recall... all responses are to be saved long-term for subsequent analysis.
>
> My concern is with speed. This will have to keep up with (somewhat
> arbitrarily) fast typing, while doing background processing, with a GUI of
> course. This illustrates why I was concerned about the fact that my Chutes
> & Ladders game seems to run at the same speed on my 8 y.o. Core 2 Duo and
> my 2 y.o. Core I7 with 3-4x as much memory. This WILL require a faster
> machine and a more significant share of it's resources, if I develop it in
> the direction I am thinking.
>
> I hope Python is a good choice here, though I suppose some modules or
> classes or parts will have to be recoded into something faster... Any
> thoughts on this will be appreciated, including how to structure it in such
> a manner that it might be more portably applied to future versions in
> entirely different knowledge realms (music/midi input,
> language/vocabulary/audio output, etc).
>
> --
> Keith
>



-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python, speed, game programming

2014-01-03 Thread Devin Jeanpierre
On Fri, Jan 3, 2014 at 1:53 PM, Keith Winston  wrote:
> I am gearing up for the next project (yeah, an eventual end to Chutes &
> Ladders!). It is a typing tutor, I am inclined to use it to learn Dvorak but
> I would expect it easily adapted to QWERTY or anything else.
>
[snip]
>
> I hope Python is a good choice here, though I suppose some modules or
> classes or parts will have to be recoded into something faster... Any
> thoughts on this will be appreciated, including how to structure it in such
> a manner that it might be more portably applied to future versions in
> entirely different knowledge realms (music/midi input,
> language/vocabulary/audio output, etc).

Modern computers are just so absurdly fast that the overhead Python
has compared to other languages just doesn't matter for the kind of
work you are doing. If you typed at a hundred characters per second
Python could still keep up, unless there's something about your
problem you aren't describing.

-- Devin
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] python problems on android

2014-01-03 Thread blechnum



Hi. I wrote a few python programs and had them running on my phone up 
to last september.

Haven't had time to work on them again till now.
Only now, they... don't work !
Not sure why and its very frustrating.

one of the errors is in response to an input request like this

g = input ("type h to use last settings ")

stops the program with this

File , line1, in 
NameError: name 'h' is not defined

after I entered h

Will I have to abandon using SL4A and Python and switch to using 
android/java ?



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python problems on android

2014-01-03 Thread Dave Angel

On Fri, 03 Jan 2014 22:18:00 +, blech...@fireflyuk.net wrote:

one of the errors is in response to an input request like this




g = input ("type h to use last settings ")




stops the program with this




File , line1, in 
NameError: name 'h' is not defined




after I entered h


Looks to me like you were previously running python 3.x and somehow 
have reverted to 2.x


Add two lines before the input ()

import sys
print (sys.version)

to see what you're using.

--
DaveA

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python, speed, game programming

2014-01-03 Thread spir

On 01/03/2014 10:53 PM, Keith Winston wrote:

My concern is with speed. This will have to keep up with (somewhat
arbitrarily) fast typing, while doing background processing, with a GUI of
course.


I wouldn't even bother. Try & see, you may be surprised. There are several 
factors at play:
* The core processing in dealing with user input (read, decode, store, queue key 
strokes, etc) will be done by low-level (OS) routines written in C, with only 
thin Python wrappers (which essentially translate from/to python data types).
* Similar point for GUI and/or other user interface layer (less so if you'd use 
a pure python GUI framework, but in general they're also just wrappers over C code).
* The ratio between such low-level processing and actual processing code written 
and executed in python for your application logic is certainly high (as is 
usually the case), unless there is much realtime computation you did not speak 
about.

Anyway, just try and see.

This is similar to how & why python is reputed to be good (read: fast) at 
"number crunching": they are standard libs for that just link to low-level C 
routines which do about all computation, behind the stage, and very few 
application logic remains written *and actually executed* in python (search 
"numpy").


Denis
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What's in a name?

2014-01-03 Thread Walter Prins
Hi Keith,

On 3 January 2014 20:03, Keith Winston  wrote:
>> So the answer to your question is just to print the string.
>> The real challenge, as we have discovered, is how to access
>> the list that is named by the string. And the usual way to
>> map strings to objects is via a dictionary not by using eval().
>
> Here's the thing: I think most of my "problems" go away with better design.
> But in case I'm wrong, what I was trying to do, which I would think could
> sometimes be helpful, is printing the name of an object along with it's
> output/results... I don't think there's any way to do the opposite of
> eval(), that is, create a string from an object name. Or am I just missing
> something here (I THINK the right way to do this is add, if necessary, and
> __name__ method, or at least a .name attribute, to the class... though now
> that I think about it I think that still doesn't solve the problem, it names
> the class not the instance.

Firstly a caveat/disclaimer/apology:  I've not read every post in this
thread in detail, so apologies if some of my comments miss the point
or has otherwise been already made to death.

Secondly, it seems to me you seem perhaps to think of an object's name
as something intrinsic, e.g. an attribute that is (or should be) part
of every object.  Note you should view objects as not having intrinsic
names unless *you* make it so via code.  The names that you associate
to your objects in your program however, are not part of your objects,
instead they live separately in namespaces and do not form part of the
objects themselves.

To belabor the point:  You should distinguish between a) references to
your objects that are "name references" that live in a namespace
somewhere (which some people call variables) and b) other anonymous
references, e.g. just non-name references held by another object (for
example such as that which is held by a list that contains your
object), and c) a potential name attribute or property you might add
to your objects to store some custom name that you'd like to give your
object at runtime (and again, which is therefore quite separate from
and distinct to any variable/namespace references that might also be
referring to your object.).

Generally, if you want an object to have a name, then make an
attribute to represent the name and use that, as you've indeed alluded
to above.  It's not usually the right idea to try and introspect back
to the (possibly many, or none) namespace references referring to your
objects.

Now, having said all that, and though I'm hesitant to even mention
this in fear of muddying the waters and confusing matters by doing so,
it is in fact possible (and with some caveats), to query for and
retrieve all the name references for an object with a bit of querying
of the Python runtime environment (specifically the garbage
collector).  Try this:

---
import gc, itertools

def names_of(obj):
"""Try to find the names associated to a given object."""
#Find dict objects from the garbase collector:
refs_dicts = (ref for ref in gc.get_referrers(obj) if isinstance(ref, dict))
#Get a single chained generator for all the iteritems() iterators
in all the dicts
keyvalue_pairs = itertools.chain.from_iterable(refd.iteritems()
for refd in refs_dicts)
#Return a list of keys (names) where the value (obj) is the one
we're looking for:
return [k for k, v in keyvalue_pairs if v is obj]

x = []
y = x
z = [x]

print names_of(z[0])
---

As you might expect, the last line outputs the 2 names for the list
initially named "x" above, e.g. ['x', 'y']

As for generating a string representation of an object, by convention
the output of the repr() function is usually supposed to give you a
string _repr_esentation (geddit) that should, if submitted to the
Python interpreter (or eval), give you back an equivalent object to
the one that was passed to repr().  This however is not guaranteed and
you should _NOT_ rely on repr()/eval() if you're trying to
serialise/deserialize your objects, not least due to the security
dangers implied by eval.  Instead, use the pickle module:
http://docs.python.org/2/library/pickle.html

HTH,

Walter
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What's in a name?

2014-01-03 Thread Walter Prins
Hi,

The code in my last post got line wrapped which will break if directly
tried out.  To avoid possible confusion I paste a version below with
shorter lines which should avoid the problem:


import gc, itertools

def names_of(obj):
"""Try to find the names associated to a given object."""
#Find dict objects from the garbage collector:
refs_dicts = (ref for ref in gc.get_referrers(obj)
  if isinstance(ref, dict))
#Get a single chained generator for all the iteritems() iterators
#in all the dicts
keyvalue_pairs = itertools.chain.from_iterable(
refd.iteritems() for refd in refs_dicts)
#Return a list of keys (names) where the value (obj) is the one
#we're looking for:
return [k for k, v in keyvalue_pairs if v is obj]

x = []
y = x
z = [x]

print names_of(z[0])
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] python problems on android

2014-01-03 Thread blechnum


Thanks Dave.

I was using 3.2.2 and uninstalled it earlier as it was giving me 
strange messages.

Just reinstalled to remind myself what these were.

here goes,

WARNING: linker: libpython3.2m.so has text relocations this is wasting 
memory and is a security risk. Please fix


the warning message repeats replacing the module name with several 
others like array.cpython-32m.so
It ran my program with the same Name Error:name l is not defined 
problem as before


The error I posted was using 2.6.2

So my program crashes on both 2 and 3

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python, speed, game programming

2014-01-03 Thread Keith Winston
Okay, thanks, I'll probably be proceeding over the next few weeks, as I
finish up my Chutes & Ladders project... I think I have to do a bit more
code/manual reading in proportion to my coding for a bit, also. Thanks for
the insights.

K


On Fri, Jan 3, 2014 at 6:12 PM, spir  wrote:

> On 01/03/2014 10:53 PM, Keith Winston wrote:
>
>> My concern is with speed. This will have to keep up with (somewhat
>> arbitrarily) fast typing, while doing background processing, with a GUI of
>> course.
>>
>
> I wouldn't even bother. Try & see, you may be surprised. There are several
> factors at play:
> * The core processing in dealing with user input (read, decode, store,
> queue key strokes, etc) will be done by low-level (OS) routines written in
> C, with only thin Python wrappers (which essentially translate from/to
> python data types).
> * Similar point for GUI and/or other user interface layer (less so if
> you'd use a pure python GUI framework, but in general they're also just
> wrappers over C code).
> * The ratio between such low-level processing and actual processing code
> written and executed in python for your application logic is certainly high
> (as is usually the case), unless there is much realtime computation you did
> not speak about.
> Anyway, just try and see.
>
> This is similar to how & why python is reputed to be good (read: fast) at
> "number crunching": they are standard libs for that just link to low-level
> C routines which do about all computation, behind the stage, and very few
> application logic remains written *and actually executed* in python (search
> "numpy").
>
> Denis
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What's in a name?

2014-01-03 Thread Keith Winston
Thanks Walter, I think I've got the lay of the land roughly, but my grasp
is still light and imperfect. I'm pretty confident I shouldn't be doing
anything like what you're describing for the level of coding I'm doing, but
it's interesting to see the approach.

Keith



On Fri, Jan 3, 2014 at 6:56 PM, Walter Prins  wrote:

> Hi,
>
> The code in my last post got line wrapped which will break if directly
> tried out.  To avoid possible confusion I paste a version below with
> shorter lines which should avoid the problem:
>
>
> import gc, itertools
>
> def names_of(obj):
> """Try to find the names associated to a given object."""
> #Find dict objects from the garbage collector:
> refs_dicts = (ref for ref in gc.get_referrers(obj)
>   if isinstance(ref, dict))
> #Get a single chained generator for all the iteritems() iterators
> #in all the dicts
> keyvalue_pairs = itertools.chain.from_iterable(
> refd.iteritems() for refd in refs_dicts)
> #Return a list of keys (names) where the value (obj) is the one
> #we're looking for:
> return [k for k, v in keyvalue_pairs if v is obj]
>
> x = []
> y = x
> z = [x]
>
> print names_of(z[0])
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python problems on android

2014-01-03 Thread Devin Jeanpierre
On Fri, Jan 3, 2014 at 4:26 PM,   wrote:
> Thanks Dave.

Your email doesn't appear to be in response to anything. I think your
email client is broken, and you should switch to a different one.

-- Devin
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] idle problem

2014-01-03 Thread Kodiak Firesmith
Hello Alejandro!

Try running idle via a terminal and see if it's throwing out any error
information.  (-d switch for dubug)

I've moved on to a mix between PyCharm and Vim depending on how big of a
"project" I'm working on, but I still have idle installed so I can probably
help a bit more if there's more details to be had.

 - Kodiak


On Fri, Jan 3, 2014 at 2:35 PM, I. Alejandro Fleischer <
iafleisc...@gmail.com> wrote:

> Hello to everyone,
>
> Sudenly Im having troubles opening files with the idle editor. When I open
> a file it appears in blank, and can not close it anymore.
>
> My OS is ubuntu 13.10 (64 bits) and my python version is 2.7.5.
>
> Regards,
>
> Igor
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] python problems on android

2014-01-03 Thread Roger
Hi. I wrote a few python programs and had them running on my phone up to last 
september.
Haven't had time to work on them again till now.
Only now, they... don't work !
Not sure why and its very frustrating.

one of the errors is in response to an input request like this

g = input ("type h to use last settings ") 

stops the program with this

File , line1, in 
NameError: name 'h' is not defined

after I entered h

Will I have to abandon using SL4A and Python and switch to using android/java ? 





___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python problems on android

2014-01-03 Thread Danny Yoo
Hi Roger,

Check whether or not you are running Python 3 or Python 2.  I strongly
suspect you should be using 3, but have run it as a Python 2 program by
accident.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] idle problem

2014-01-03 Thread Alan Gauld

On 03/01/14 19:35, I. Alejandro Fleischer wrote:


Sudenly Im having troubles opening files with the idle editor. When I
open a file it appears in blank, and can not close it anymore.


How are you opening it?

How do you run IDLE?
How do you open a file?
What does the 'blank' window display as a title?


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python, speed, game programming

2014-01-03 Thread Alan Gauld

On 03/01/14 21:53, Keith Winston wrote:


Ladders!). It is a typing tutor, I am inclined to use it to learn Dvorak
but I would expect it easily adapted to QWERTY or anything else.
...

My concern is with speed. This will have to keep up with (somewhat
arbitrarily) fast typing,


Lets see. The speed record for touch typing is around 150 wpm with 
average word being about 5 chars, so a speed of about 750 cpm

or 12.5cps That's about 80ms between letters.

Python on a modern PC can probably execute around 100k lines
of code(*) per second or 100 per millisecond. That's 8k lines
executed between each keypress for the worlds fastest typist.

I used  to use a typing tutor that was written in old GW Basic
on the original IBM PC (speed 4.7MHz) and it had no problem
analyzing my stats (albeit at a modest 40-50 wpm).

I'd worry about speed after you find you need to.

(*)Caveat: I haven't tried any kind of objective test and
of course some Python 'lines' are equal to many
lines of simpler languages - think list comprehensions.
But in practice I still don't think you will have a
big problem.


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python, speed, game programming

2014-01-03 Thread Keith Winston
Just to be clear, what I'm asking this typing tutor to do is vastly more
than normal, albeit still not seemingly very much. In most programs, they
give you a sentence or paragraph to type, and then time how long it takes.
I'm talking about timing every keypress, and modifying the text stream
based on that. The thing that put me on edge was noticing that my simple
Chutes & Ladders game doesn't go ANY faster on a machine that benchmarks
perhaps 1000 times faster than another...

Keith


On Fri, Jan 3, 2014 at 8:17 PM, Alan Gauld wrote:

> On 03/01/14 21:53, Keith Winston wrote:
>
>  Ladders!). It is a typing tutor, I am inclined to use it to learn Dvorak
>> but I would expect it easily adapted to QWERTY or anything else.
>> ...
>>
>>
>> My concern is with speed. This will have to keep up with (somewhat
>> arbitrarily) fast typing,
>>
>
> Lets see. The speed record for touch typing is around 150 wpm with average
> word being about 5 chars, so a speed of about 750 cpm
> or 12.5cps That's about 80ms between letters.
>
> Python on a modern PC can probably execute around 100k lines
> of code(*) per second or 100 per millisecond. That's 8k lines
> executed between each keypress for the worlds fastest typist.
>
> I used  to use a typing tutor that was written in old GW Basic
> on the original IBM PC (speed 4.7MHz) and it had no problem
> analyzing my stats (albeit at a modest 40-50 wpm).
>
> I'd worry about speed after you find you need to.
>
> (*)Caveat: I haven't tried any kind of objective test and
> of course some Python 'lines' are equal to many
> lines of simpler languages - think list comprehensions.
> But in practice I still don't think you will have a
> big problem.
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.flickr.com/photos/alangauldphotos
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python, speed, game programming

2014-01-03 Thread Keith Winston
Truth in advertising: I just realized a Core I7 only benchmarks about 10x
faster than a Core 2 Duo, using Passmark. Wow, something like 6 years newer
and only 10 times? Anyway, I'd STILL expect to see some of that in the
program performance, though maybe once I get it ironed out it will be a
little sleeker...

Keith


On Fri, Jan 3, 2014 at 8:38 PM, Keith Winston  wrote:

> Just to be clear, what I'm asking this typing tutor to do is vastly more
> than normal, albeit still not seemingly very much. In most programs, they
> give you a sentence or paragraph to type, and then time how long it takes.
> I'm talking about timing every keypress, and modifying the text stream
> based on that. The thing that put me on edge was noticing that my simple
> Chutes & Ladders game doesn't go ANY faster on a machine that benchmarks
> perhaps 1000 times faster than another...
>
> Keith
>
>
> On Fri, Jan 3, 2014 at 8:17 PM, Alan Gauld wrote:
>
>> On 03/01/14 21:53, Keith Winston wrote:
>>
>>  Ladders!). It is a typing tutor, I am inclined to use it to learn Dvorak
>>> but I would expect it easily adapted to QWERTY or anything else.
>>> ...
>>>
>>>
>>> My concern is with speed. This will have to keep up with (somewhat
>>> arbitrarily) fast typing,
>>>
>>
>> Lets see. The speed record for touch typing is around 150 wpm with
>> average word being about 5 chars, so a speed of about 750 cpm
>> or 12.5cps That's about 80ms between letters.
>>
>> Python on a modern PC can probably execute around 100k lines
>> of code(*) per second or 100 per millisecond. That's 8k lines
>> executed between each keypress for the worlds fastest typist.
>>
>> I used  to use a typing tutor that was written in old GW Basic
>> on the original IBM PC (speed 4.7MHz) and it had no problem
>> analyzing my stats (albeit at a modest 40-50 wpm).
>>
>> I'd worry about speed after you find you need to.
>>
>> (*)Caveat: I haven't tried any kind of objective test and
>> of course some Python 'lines' are equal to many
>> lines of simpler languages - think list comprehensions.
>> But in practice I still don't think you will have a
>> big problem.
>>
>>
>> --
>> Alan G
>> Author of the Learn to Program web site
>> http://www.alan-g.me.uk/
>> http://www.flickr.com/photos/alangauldphotos
>>
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
>>
>
>
>
> --
> Keith
>



-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] simple arg problem

2014-01-03 Thread Keith Winston
I'm trying to rewrite/reshuffle my Chutes & Ladders code, which I generally
find more confusing than writing anew.

Anyway, I've got a method that seems like it calls for one argument but...

def populate(self, gamecount1):
"""populate candl_array with a set of games"""

(method of a new class CandL_Array, which contains a list called
candl_array)

Every time I run it with


-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] simple arg problem

2014-01-03 Thread Keith Winston
gmail is driving me crazy. Anyway, every time I run it with:

if __name__ == "__main__":
tarray = CandL_Array
tarray.populate(100)

I get an error

Traceback (most recent call last):
  File "/home/keithwins/Dropbox/Python/CandL8.py", line 127, in 
tarray.populate(100)
TypeError: populate() missing 1 required positional argument: 'gamecount1'
>>>

Which seems to say it wants another argument, but I am in the habit of not
counting the self argument... I thought I understood that. I'm sure it's
something obvious, but I've been staring at it for hours. This is going to
be embarrassing...



On Fri, Jan 3, 2014 at 9:53 PM, Keith Winston  wrote:

> I'm trying to rewrite/reshuffle my Chutes & Ladders code, which I
> generally find more confusing than writing anew.
>
> Anyway, I've got a method that seems like it calls for one argument but...
>
> def populate(self, gamecount1):
> """populate candl_array with a set of games"""
>
> (method of a new class CandL_Array, which contains a list called
> candl_array)
>
> Every time I run it with
>
>
> --
> Keith
>



-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] simple arg problem

2014-01-03 Thread eryksun
On Fri, Jan 3, 2014 at 9:56 PM, Keith Winston  wrote:
>
> if __name__ == "__main__":
> tarray = CandL_Array
> tarray.populate(100)
>
> I get an error
>
> Traceback (most recent call last):
>   File "/home/keithwins/Dropbox/Python/CandL8.py", line 127, in 
> tarray.populate(100)
> TypeError: populate() missing 1 required positional argument: 'gamecount1'

>
> Which seems to say it wants another argument, but I am in the habit of not
> counting the self argument... I thought I understood that. I'm sure it's
> something obvious, but I've been staring at it for hours. This is going to
> be embarrassing...

You've assigned the class to `tarray` instead of assigning an instance
of the class. Forgetting to call() is a common mistake.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] simple arg problem

2014-01-03 Thread Keith Winston
Ah, more briefly: parens. Wow, okay then. Thanks.


On Fri, Jan 3, 2014 at 10:14 PM, eryksun  wrote:

> On Fri, Jan 3, 2014 at 9:56 PM, Keith Winston  wrote:
> >
> > if __name__ == "__main__":
> > tarray = CandL_Array
> > tarray.populate(100)
> >
> > I get an error
> >
> > Traceback (most recent call last):
> >   File "/home/keithwins/Dropbox/Python/CandL8.py", line 127, in 
> > tarray.populate(100)
> > TypeError: populate() missing 1 required positional argument:
> 'gamecount1'
> 
> >
> > Which seems to say it wants another argument, but I am in the habit of
> not
> > counting the self argument... I thought I understood that. I'm sure it's
> > something obvious, but I've been staring at it for hours. This is going
> to
> > be embarrassing...
>
> You've assigned the class to `tarray` instead of assigning an instance
> of the class. Forgetting to call() is a common mistake.
>



-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python, speed, game programming

2014-01-03 Thread Mark Lawrence

On 03/01/2014 21:41, Keith Winston wrote:

--
Keith



Frankly I think you're lining up to jump fences when you're actually 
riding on the flat :)


--
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.


Mark Lawrence

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python, speed, game programming

2014-01-03 Thread Keith Winston
On Fri, Jan 3, 2014 at 11:14 PM, Mark Lawrence wrote:

> On 03/01/2014 21:41, Keith Winston wrote:
>
>> --
>> Keith
>>
>>
> Frankly I think you're lining up to jump fences when you're actually
> riding on the flat :)
>

Fair enough,  but I am thinking of the next project as a long-term
dabbling: hopefully my abilities will rise to my  concept... I guess I'm
about 3 weeks into Python (and OOP) so far, of course my ability to focus
on it will depend on work and other pressures, but I'm amazed at how
accessible this language is. Anyway, thanks to you and everyone who've
helped me as I crawl on the flat... this group has been way more than
invaluable.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] simple arg problem

2014-01-03 Thread Steven D'Aprano
On Fri, Jan 03, 2014 at 09:56:25PM -0500, Keith Winston wrote:
> gmail is driving me crazy. Anyway, every time I run it with:
> 
> if __name__ == "__main__":
> tarray = CandL_Array
> tarray.populate(100)
> 
> I get an error
> 
> Traceback (most recent call last):
>   File "/home/keithwins/Dropbox/Python/CandL8.py", line 127, in 
> tarray.populate(100)
> TypeError: populate() missing 1 required positional argument: 'gamecount1'
> >>>

Eryksun has already solved your immediate problem, but I'd like to point 
out that the above has a couple of code smells.

Are you familiar with the concept of a code smell? Code which smells 
wrong might not be wrong, but it's worth giving it a good hard long look 
just to be sure. Like Grandma used to say about your nappies, "If it 
stinks, change it", code smells usually suggest there's a problem with 
the code.

http://www.codinghorror.com/blog/2006/05/code-smells.html

Like parmesan and blue cheeses, or durian fruit, there are a few 
exceptions, but normally code is like food: it only smells bad when it 
has gone off. You should never write smelly code without giving it a 
good, hard look.

Anyway, back to your code... you have a class CandL_Array which 
apparently you call with no arguments. If it needed arguments, you 
wouldn't have made the error you did, which is to forget to include 
parentheses:

# No
tarray = CandL_Array  # makes tarray an alias to the class

# Yes
tarray = CandL_Array()  # makes tarray an instance of the class


If CandL_Array() needed arguments, you wouldn't have forgotten the round 
brackets, and wouldn't have got the error you did. So there's a little 
whiff of a smell right there... why does the class not take any 
arguments? That suggests that every instance it creates is exactly the 
same as every other instance. That's not necessarily wrong, but it is a 
little bit whiffy.

But then there's the next line:

tarray.populate(100)

Apparently, and I'm reading between the lines here, once you create the 
CandL_Array instance, you can't use it until you populate it. If I'm 
right, that's pretty smelly. That means you have errors like this:

tarray = CandL_Array()  # Initialise an instance.
tarray.play_game()  # or something, you don't show that part of the code


which blows up in your face because you forgot to call populate first. 
That's ugly, stinking code. Imagine if you had to write code like this:

x = float("12.345")
x.prepare()  # Make the float ready to use
y = x + 1.0  # Now we can use it!

Yuck.

Most of the time, creating an instance should do everything needed to 
prepare it for use. I suspect that your game is no exception. If you 
need to call some method to make the instance ready to use, then the 
constructor __new__ or initialiser __init__ should do so.

You don't even have to get rid of the populate method. You just need 
to change this:

class CandL_Array:
def __init__(self):
...
def populate(self, size):
...


to this:

class CandL_Array:
def __init__(self, size):
...
self.populate(size)
def populate(self, size):
...


and change this:

tarray = CandL_Array()
tarray.populate(100)


to this:

tarray = CandL_Array(100)



-- 
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] More or less final Chutes & Ladders

2014-01-03 Thread Keith Winston
Here is what I think will be about the final version of C and L. I
rearranged it quite a bit (into 2 classes), fixed a bug or two, and
generally cleaned it up a bit. I haven't really polished it, but hopefully
it will be less difficult to read... which is to say, if anyone wants to go
through it AGAIN (at your leisure) I would appreciate comments on style,
etc.

Probably the biggest change is that I added a result() method to the
ChutesAndLadders class, that returns a list of the pertinent attributes of
each game (to be compiled into the array of games results that CandL_Array
class is all about).

Anyway, I sort of need to get off this since I need to do a lot more
reading on this language, though I may be back with early drafts of my
typing tutor before long... we'll see how that goes.

-- 
Keith

""" Chutes & Ladders Simulation
Simulates a number of games of Chutes & Ladders (Snakes & Ladders).
Chutes & Ladders are separate dictionaries to allow tracking of
separate stats.

Gathers the results into a list of lists of individual game results
in the form (per game) of [game_no, moves, [chutes], [ladders]]

"""

import random
from timer2 import timer
from statistics import * # from whence comes mean, variance, stdev


# Landing on a chute causes one to slide down to the corresponding value.
chutes = {16: 6, 47: 26, 49: 11, 56: 53, 62: 19, 64: 60, 87: 24, 93: 73,
95: 75, 98:78}

# Landing on a ladder (key) causes one to climb up to the corresponding
value.
ladders = {1: 38, 4: 14, 9: 31, 21: 42, 28: 84, 36: 44, 51: 67, 71: 91,
80:100}

class ChutesAndLadders:
"""Game class for Chutes & Ladders."""

def __init__(self):
self.reset()

def reset(self):
self.position = 0
self.game_number = 0
self.move_count = 0
self.chutes_list = []
self.ladders_list = []

def results(self):
return [self.game_number, self.move_count, self.chutes_list,
self.ladders_list]

#@timer
def move(self):
"""Single move, with chutes, ladders, & out of bounds.
Primary action is to move self.position, but returns a list
that consists of either the chute or ladder if landed on, if either
"""

roll = random.randint(1,6)
self.move_count += 1
self.position += roll
if self.position in chutes:
self.chutes_list.append(self.position)
self.position = chutes[self.position]
elif self.position in ladders:
self.ladders_list.append(self.position)
self.position = ladders[self.position]
elif self.position > 100:  # move doesn't count, have to land
exactly
self.position -= roll
return

#@timer
def play(self, game_no):
"""Single game"""

self.reset()
self.game_number = game_no
while self.position < 100:
self.move()
return

class CandL_Array:
""" Create & analyze an array of CandL games """

candl_array = []
def __init__(self):
self.candl_array = []

#@timer
def populate(self, gamecount1):
"""populate candl_array with a set of games"""

tgame = ChutesAndLadders()
for i in range(gamecount1):
tgame.play(i)
self.candl_array.append(tgame.results())

def print_stuff(self):
self.print_gameset_stats(self.candl_array)
self.print_candl_info(self.candl_array)

def print_gameset_stats(self, garray):
print("Total number of games: ", len(garray))
print("   MovesChutesLadders")
for func in [mean, max, min, stdev]:
print("{moves:9.2f} {chutes:12.2f} {ladders:13.2f}
{fname}".format(
moves=func(tgset[1] for tgset in garray),
chutes=func(len(tgset[2]) for tgset in garray),
ladders=func(len(tgset[3]) for tgset in garray),
fname=func.__name__
))

def print_candl_info(self, garray):
""" Create two dictionaries with the same keys as chutes & ladders,
but with the total number of times each c or l is traversed (in the
entire gameset)
as the values. Then, print them. """

self.chute_nums, self.ladder_nums = dict(chutes), dict(ladders)
self.summarize_game("chutes", self.chute_nums, 2, garray)
self.summarize_game("ladders", self.ladder_nums, 3, garray)

def summarize_game(self, game_name, game_nums, game_index, garray):

tgame_nums = game_nums
for i in tgame_nums.keys(): game_nums[i] = 0

for corl in tgame_nums:
for game in garray:
tgame_nums[corl] += game[game_index].count(corl)
print("total ", game_name, "= ", sum(tgame_nums.values()))

"""   def timing_report():

print("game.total, count = ", p1.game.total, p1.game.count)
print("move.total, count = ", p1.move.total, p1.move.count)
"""

def run_CandL(gamecount):
tarray = CandL_Array

Re: [Tutor] simple arg problem

2014-01-03 Thread Keith Winston
Hi Steven,

tarray = CandL_Array(100)

Yes, that's definitely better. I'll make that change. Thanks, makes sense.
I'd already posted my "finished" version, so I probably won't repost with
this small change right now.

Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What's in a name?

2014-01-03 Thread Steven D'Aprano
On Fri, Jan 03, 2014 at 12:29:34AM -0500, Keith Winston wrote:
> Hmm, maybe I stumbled upon at least one approach, turning the problem
> around. Make it something like:
> 
> for i in ["alist", "blist", "clist"]
> i[3] = "okey dokey "
> print(eval(i)[3], i)
> 
> Of course I've been staring at this for a while, but as soon as I post I
> find a way... this is my first use of eval()

And now that you've discovered eval(), do yourself a favour and forget 
all about it.

- eval is dangerous. The number one cause of software vulnerabilities 
  (i.e. bugs which can be used by viruses and malware) today is code 
  ejection, which is a fancy way of saying "somebody screwed up with
  eval or the equivalent".

- eval is slow. In Python, at least, using eval("something()") is
  about ten times slower than just calling something(). That's because
  the slow process of parsing and compiling the text into executable
  code takes place at run-time instead of compile-time.

- eval is confusing. While it's possible to use eval in simple, easy
  to understand ways, there's (usually) not much point in that. So 
  eval normally only gets used in ways which are tricky to write and
  tricky to understand.

- There is very little that cannot be done without eval. It is rarely 
  the best solution, and even more rarely the only solution.


My recommendation is, any time you get the urge to use eval in code, 
go take a cold shower until the urge goes away. Exceptions can be made 
for experts and for interactive use at the REPL.

Your code above is probably better written something like this:

for name in ["alist", "blist", "clist"]:
thelist = vars()[name]
thelist[3] = "okey dokey "
print(name, "=", thelist)



-- 
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What's in a name?

2014-01-03 Thread Keith Winston
On Fri, Jan 3, 2014 at 11:59 PM, Steven D'Aprano wrote:

> thelist = vars()[name]



I see: vars() certainly looks less dangerous than eval(), but I'm guessing
that's still smelly code? I hadn't known about vars() or I probably would
have used it.

-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: What's in a name?

2014-01-03 Thread Steven D'Aprano
On Fri, Jan 03, 2014 at 01:55:29AM -0500, Keith Winston wrote:
[...]
> I want to iterate through a bunch of lists, subsequently printing both list
> members (via indexing, for example) and the name of the list I'm on.

Why? What does this gain you?

Now, it's true that when *debugging code*, being able to see the name of 
the variable and the contents of the variable is useful. But in ordinary 
code, why would you care to print the name of the variable and its 
contents. Who cares what the variable is named?

Debuggers stick all sorts of nasty hooks into the running interpreter in 
order to do this (and much more), and we should all be thankful that (1) 
debuggers exist, (2) that they aren't running by default, and most 
importantly (3) that we don't have to write code like them.

In addition to powerful debuggers, we also have fantastic poor-man's 
debugger called "print":

for name, value in zip(
'alist blist clist'.split(), [alist, blist, clist]):
print(name, "=", value)


Yes, it's a little bit messy code. We have to repeat the name of the 
variable twice. But this isn't code that will hang around in the 
finished program. It only need exist for just long enough to debug the 
problem we're having (you are having a problem, I presume?), then, it's 
job done, it's gone. (Be ruthless at deleting code that isn't pulling 
its weight.) And in the meantime, the rest of our code doesn't need to 
use any nasty indirect code, it can just use (say) alist.append(42) 
instead of eval('alist').append(42).

For longer-lasting indirect code, rather than use eval, its better to do 
something like this:

namespace = {
'alist': [1, 2, 4, 8, 16, 32],
'blist': ['fe', 'fi', 'fo', 'fum'],
'clist': [1.5, 2.5, 3.5, 4.5, 5.5, 6.5]
}

for name, value in namespace.items():
print(name, "=", value)


eval is a nuclear-powered bulldozer. Don't use it for cracking nuts.


-- 
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Copying [was Re: What's in a name?]

2014-01-03 Thread Steven D'Aprano
On Fri, Jan 03, 2014 at 01:53:42PM -0500, Keith Winston wrote:

> That's what I meant to do: make a copy when I wrote chute_nums = chutes. So
> I should have passed chute_nums to summarize_game, but it still wouldn't
> work (because it's not a copy).

Python never makes a copy of objects when you pass them to a function or 
assign them to a name. If you want a copy, you have to copy them 
yourself:

import copy

acopy = copy.copy(something)


ought to work for just about anything. (Python reserves the right to not 
actually make a copy in cases where it actually doesn't matter.)

There are a couple of shortcuts for this:

# copy a dictionary
new = old.copy()

# copy a list, or tuple
new = old[:]  # make a slice from the start to the end


-- 
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What's in a name?

2014-01-03 Thread Steven D'Aprano
On Sat, Jan 04, 2014 at 03:59:19PM +1100, Steven D'Aprano wrote:

> - eval is dangerous. The number one cause of software vulnerabilities 
>   (i.e. bugs which can be used by viruses and malware) today is code 
>   ejection, which is a fancy way of saying "somebody screwed up with
>   eval or the equivalent".

Sigh. It's spelled code *injection*.


-- 
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Copying [was Re: What's in a name?]

2014-01-03 Thread Mark Lawrence

On 04/01/2014 05:44, Steven D'Aprano wrote:

On Fri, Jan 03, 2014 at 01:53:42PM -0500, Keith Winston wrote:


That's what I meant to do: make a copy when I wrote chute_nums = chutes. So
I should have passed chute_nums to summarize_game, but it still wouldn't
work (because it's not a copy).


Python never makes a copy of objects when you pass them to a function or
assign them to a name. If you want a copy, you have to copy them
yourself:

import copy

acopy = copy.copy(something)


ought to work for just about anything. (Python reserves the right to not
actually make a copy in cases where it actually doesn't matter.)

There are a couple of shortcuts for this:

# copy a dictionary
new = old.copy()

# copy a list, or tuple
new = old[:]  # make a slice from the start to the end




Please be aware of the difference between deep and shallow copies see 
http://docs.python.org/3/library/copy.html


--
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.


Mark Lawrence

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What's in a name?

2014-01-03 Thread Steven D'Aprano
On Sat, Jan 04, 2014 at 12:32:19AM -0500, Keith Winston wrote:
> On Fri, Jan 3, 2014 at 11:59 PM, Steven D'Aprano wrote:
> 
> > thelist = vars()[name]
>
> 
> I see: vars() certainly looks less dangerous than eval(), but I'm guessing
> that's still smelly code? I hadn't known about vars() or I probably would
> have used it.

Yes, it's still a bit smelly: but only a bit, since while "direct" code 
is the idea, sometimes the only way to do things is with one (or two) 
layers of indirection.

Code should (as a general rule) not rely on, or be affected by, the name 
of the variable. Functions which inspect the running environment (i.e. 
peek deep inside the interpreter) or use eval or other techniques to 
operate "behind the scenes" on *names* rather than values can often lead 
to confusing code. As debugging tools, they're useful. Putting such 
functionality inside normal everyday programs is a code smell.


-- 
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Copying [was Re: What's in a name?]

2014-01-03 Thread Keith Winston
Thanks for all this. I ended up using

newdict = dict(olddict), which seemed to work fine. I hadn't heard about
the copy module until now. I had heard about deep/shallow copies, though in
this particular example (all int dicts), I don't think there's a
difference...?


On Sat, Jan 4, 2014 at 12:50 AM, Mark Lawrence wrote:

> On 04/01/2014 05:44, Steven D'Aprano wrote:
>
>> On Fri, Jan 03, 2014 at 01:53:42PM -0500, Keith Winston wrote:
>>
>>  That's what I meant to do: make a copy when I wrote chute_nums = chutes.
>>> So
>>> I should have passed chute_nums to summarize_game, but it still wouldn't
>>> work (because it's not a copy).
>>>
>>
>> Python never makes a copy of objects when you pass them to a function or
>> assign them to a name. If you want a copy, you have to copy them
>> yourself:
>>
>> import copy
>>
>> acopy = copy.copy(something)
>>
>>
>> ought to work for just about anything. (Python reserves the right to not
>> actually make a copy in cases where it actually doesn't matter.)
>>
>> There are a couple of shortcuts for this:
>>
>> # copy a dictionary
>> new = old.copy()
>>
>> # copy a list, or tuple
>> new = old[:]  # make a slice from the start to the end
>>
>>
>>
> Please be aware of the difference between deep and shallow copies see
> http://docs.python.org/3/library/copy.html
>
> --
> My fellow Pythonistas, ask not what our language can do for you, ask what
> you can do for our language.
>
> Mark Lawrence
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
Keith
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor