Re: [Tutor] role playing game - help needed

2010-12-06 Thread Alan Gauld


"Alan Stern"  wrote


Hi all.  My name is Al Stern.


Hi Al,


Chapter 5: Lists and Dictionaries.


Note Lists AND Dictionaries


I'm not sure exactly how this mailing list works but
was hoping someone here could give me some insight


You are doing just fine.
The only extra info we could find helpful; are the Python version you 
use

and the OS you run.

For now, I'll assume Python v3 and Windows...

I think I did ok setting up the variables but haven't figured out 
where to go from there.

...

Here is what I have (along with my latest error message).


I don;t see any error messages?
BTW. Please post complete error messages not just summaries.

Notice the topic. You have Lists but I see no dictionaries.
Think about how a dictionary works and how it could be useful here.


attributes = ["strength", "health", "wisdom", "dexterity"]
points = [0,0,0,0]


You ave a list of attributes and a separate list of points.
A dictionary holds a set of keys and associated values.
Can you see a connection?

MAX_POINTS = 30
available_points = MAX_POINTS - sum(points)

print ("You have", available_points, "points available to use.")

for x in range(len(attributes)):
 print ("\t",attributes[x], points[x])

for x in range(len(attributes)):
   point_choice = input("\n\nHow many points do you want to assign to 
" +  attributes[x]  + "?: ")



A start would be to convert the result to an integer and then assign 
that

to points[x]... Then modify available_points as needed.

However using a dictionary will simplify things considerably.

HTH,


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


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


[Tutor] modified dictionary class

2010-12-06 Thread John
Hello all,

I have been using this class extensively in my modules / scripts. It
provides the ability to .reference dictionary values. I find it handy,
but am afraid it may come back to haunt me at some point. Is there
anything wrong with using this?


class Structure(dict):
""" A 'fancy' dictionary. It provides 'MatLab' structure-like
referencing. Could also just define a generic class.
Caution: This may be deprecated in a future release.
"""
def __getattr__(self, attr):
# Fake a __getstate__ method that resturns None
if attr == "__getstate__":
return lambda: None
return self[attr]
def __setattr__(self, attr, value):
self[attr] = value

def set_with_dict(self,D):
""" set attributes with a dict """
for k in D.keys():
self.__setattr__(k,D[k])
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] modified dictionary class

2010-12-06 Thread Joel Goldstick
On Mon, Dec 6, 2010 at 7:34 AM, John  wrote:

> Hello all,
>
> I have been using this class extensively in my modules / scripts. It
> provides the ability to .reference dictionary values. I find it handy,
> but am afraid it may come back to haunt me at some point. Is there
> anything wrong with using this?
>
>
> class Structure(dict):
>""" A 'fancy' dictionary. It provides 'MatLab' structure-like
>referencing. Could also just define a generic class.
>Caution: This may be deprecated in a future release.
>"""
>def __getattr__(self, attr):
># Fake a __getstate__ method that resturns None
>if attr == "__getstate__":
>return lambda: None
>

why not "return None"?


>return self[attr]
>def __setattr__(self, attr, value):
>self[attr] = value
>
>def set_with_dict(self,D):
>""" set attributes with a dict """
>for k in D.keys():
>self.__setattr__(k,D[k])
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



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


Re: [Tutor] modified dictionary class

2010-12-06 Thread Alan Gauld


"Joel Goldstick"  wrote


   def __getattr__(self, attr):
   # Fake a __getstate__ method that resturns None
   if attr == "__getstate__":
   return lambda: None


why not "return None"?


Presumably the caller is expecting a function that he can call.
The lambda is such a function, but one which always returns 
None.


lambda: None 
is not the same as

None

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


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


[Tutor] Python vs. MATLAB

2010-12-06 Thread Jaidev Deshpande
Dear all

What advantages does Python have over MATLAB as a programming language, (not
the computing environment of MATLAB)?

Also, wikipedia says Python is an interpreted language, what does that mean?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] modified dictionary class

2010-12-06 Thread Alan Gauld


"Joel Goldstick"  wrote 


   def __getattr__(self, attr):
   # Fake a __getstate__ method that resturns None
   if attr == "__getstate__":
   return lambda: None



why not "return None"?



   return self[attr]


Oops, too quick. I neant to add:

But this line seems to return a value so the return values 
of this function seem to be incompatible which is not 
a good design pattern.


If attr is getstate it returns a function object.
Otherwise it returns whatever the dict holds 
- Unless the dict holds functions of course.


Alan G.

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


Re: [Tutor] role playing game - help needed

2010-12-06 Thread Robert Sjöblom
>I am starting with a book called Python Programming for the Absolute Beginner 
>by Michael Dawson.  The book has been >pretty good >and up to this point, I 
>have grasped all the concepts it has covered.  At the end of each chapter, 
>there are a number of challenges you >need to complete before moving on.  
>Problem is, I have gotten stumped on one in Chapter 5: Lists and Dictionaries.
[snip]
> attributes = ["strength", "health", "wisdom", "dexterity"]
> points = [0,0,0,0]
> MAX_POINTS = 30
> available_points = MAX_POINTS - sum(points)

Before anyone comments that you can write a function for the points
system, which was helpful to me when I asked a question regarding that
very chapter: The book doesn't deal with functions until Chapter 6.

As for your problem, Alan; I believe Alan already answered it -- you
have two different lists, attributes and points, but a dictionary
would be easier to handle. Not to say that it couldn't be done the way
you're doing it though. A dictionary is built with key:value pairs.
Then it's just about figuring out a way to change the value associated
with each key when the attribute changes. I don't want to spoil the
challenge of working it out yourself, but when I asked I was told to
check out how values() and sum() worked.

best regards,
Robert S.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python vs. MATLAB

2010-12-06 Thread Chris Fuller
1) Python is free!
2) Python indices start at 0!
3) Python has way better GUIs
4) Python can emulate a lot of Matlab functionality with matplotlib and numpy
5) Matlab has a rather limited number of data structures
6) Matlab doesn't have anything like the third party support for almost 
anything
7) Almost everything in Matlab is pass-by-value. This can get to be a bit of a
   pain at times.
8) Python is a general-purpose programming language, and as such, has a much
   wider set of features
9) There are a lot more Python developers to share code with and learn from

It's free! Install it on all your computers. Take it home to use for work or 
play. Show it to your friends. Keep using it after you leave your place of 
work/study!

The "interpreted" bit refers to the fact that the source code is not compiled 
before it is run. This is also true of Matlab.


Cheers


On Monday 06 December 2010, Jaidev Deshpande wrote:
> Dear all
> 
> What advantages does Python have over MATLAB as a programming language,
> (not the computing environment of MATLAB)?
> 
> Also, wikipedia says Python is an interpreted language, what does that
> mean?

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


Re: [Tutor] modified dictionary class

2010-12-06 Thread Hugo Arts
On Mon, Dec 6, 2010 at 2:47 PM, Alan Gauld  wrote:
> Oops, too quick. I neant to add:
>
> But this line seems to return a value so the return values of this function
> seem to be incompatible which is not a good design pattern.

I agree it's not the clearest way to do this, but not because of
incompatible return values. Attribute and Method access have the same
syntax on objects, and __getattr__ is only called if the attribute
isn't found "in the usual places," so it won't hide other methods. In
other words:

>>> a = Structure()
>>> a["spam"] = 5
>>> a.__getstate__()
None
>>> a.spam
5

Doesn't look that strange to me, interface-wise. Attribute access
sometimes returns a function and sometimes not. The comment
specifically states it's faking a method, so it's pretty clear.

I do have a few other gripes though:

* why not just define __getstate__ in the class? why return a new
lambda every time when you can just write "def __getstate__(self):
return None"  and be done with it? This also simplifies getattr.

* it's now impossible to have keys that collide with a method name:
dict, items, keys, clear, popitem, et cetera. You can set them without
error, but when you try to get them you'll get the old method, which
might cause hard-to-find bugs

* it's not much of an advantage over regular dicts, really. You limit
yourself to string keys, you make it very unclear that you're using a
dict, it's not as efficient, and really just unpythonic in general.
Why do this at all? To make python more Matlab-like?

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


Re: [Tutor] role playing game - help needed

2010-12-06 Thread Al Stern
Thanks for the advice.  I think I have the dictionary function set up right
now although I'm still not clear why it is better than the list.

attributes = {"strength": 0, "health": 0, "wisdom": 0, "dexterity": 0}

I think my next task is to set up a while function based on when
available_points drops below 0.  A little lost on how to do it though.

-Original Message-
From: tutor-bounces+alans=risingrealty@python.org
[mailto:tutor-bounces+alans=risingrealty@python.org] On Behalf Of Robert
Sjöblom
Sent: Monday, December 06, 2010 8:04 AM
To: tutor@python.org
Subject: Re: [Tutor] role playing game - help needed

>I am starting with a book called Python Programming for the Absolute
Beginner by Michael Dawson.  The book has been >pretty good >and up to this
point, I have grasped all the concepts it has covered.  At the end of each
chapter, there are a number of challenges you >need to complete before
moving on.  Problem is, I have gotten stumped on one in Chapter 5: Lists and
Dictionaries.
[snip]
> attributes = ["strength", "health", "wisdom", "dexterity"]
> points = [0,0,0,0]
> MAX_POINTS = 30
> available_points = MAX_POINTS - sum(points)

Before anyone comments that you can write a function for the points
system, which was helpful to me when I asked a question regarding that
very chapter: The book doesn't deal with functions until Chapter 6.

As for your problem, Alan; I believe Alan already answered it -- you
have two different lists, attributes and points, but a dictionary
would be easier to handle. Not to say that it couldn't be done the way
you're doing it though. A dictionary is built with key:value pairs.
Then it's just about figuring out a way to change the value associated
with each key when the attribute changes. I don't want to spoil the
challenge of working it out yourself, but when I asked I was told to
check out how values() and sum() worked.

best regards,
Robert S.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] modified dictionary class

2010-12-06 Thread John
Hugo,

Thank you for the response, it's very helpful. I posted a question
earlier to this list (or possibly numpy) about how to create a 'matlab
like structure'. This was early in my learning of Python, and yes, the
intention was to have something that was similar to a matlab
structure... now, I've been using Python much more, and I realize that
this may be in fact 'un-Pythonic'. The problem is, I've used it
extensively throughout my existing modules, and I have become somewhat
comfortable with it...

I guess an alternative would be to simply define a generic class, no?

class Structure(object):
pass

Then, you could easily say:

S = Structure()
S.this = ['my slice of cheese']

and perhaps I would be being more 'pythonic'?? This I could quite
easily do, as, where I have used this class, I almost never actually
use the 'dictionary' like referencing...

--john



On Mon, Dec 6, 2010 at 3:37 PM, Hugo Arts  wrote:
> On Mon, Dec 6, 2010 at 2:47 PM, Alan Gauld  wrote:
>> Oops, too quick. I neant to add:
>>
>> But this line seems to return a value so the return values of this function
>> seem to be incompatible which is not a good design pattern.
>
> I agree it's not the clearest way to do this, but not because of
> incompatible return values. Attribute and Method access have the same
> syntax on objects, and __getattr__ is only called if the attribute
> isn't found "in the usual places," so it won't hide other methods. In
> other words:
>
 a = Structure()
 a["spam"] = 5
 a.__getstate__()
> None
 a.spam
> 5
>
> Doesn't look that strange to me, interface-wise. Attribute access
> sometimes returns a function and sometimes not. The comment
> specifically states it's faking a method, so it's pretty clear.
>
> I do have a few other gripes though:
>
> * why not just define __getstate__ in the class? why return a new
> lambda every time when you can just write "def __getstate__(self):
> return None"  and be done with it? This also simplifies getattr.
>
> * it's now impossible to have keys that collide with a method name:
> dict, items, keys, clear, popitem, et cetera. You can set them without
> error, but when you try to get them you'll get the old method, which
> might cause hard-to-find bugs
>
> * it's not much of an advantage over regular dicts, really. You limit
> yourself to string keys, you make it very unclear that you're using a
> dict, it's not as efficient, and really just unpythonic in general.
> Why do this at all? To make python more Matlab-like?
>
> Hugo
> ___
> Tutor maillist  -  tu...@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Configuration
``
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Python 2.6
PIL 1.1.6
Mailman 2.1.9
Postfix 2.4.5
Procmail v3.22 2001/09/10
Basemap: 1.0
Matplotlib: 1.0.0
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] modified dictionary class

2010-12-06 Thread Hugo Arts
On Mon, Dec 6, 2010 at 4:32 PM, John  wrote:
> Hugo,
>
> Thank you for the response, it's very helpful. I posted a question
> earlier to this list (or possibly numpy) about how to create a 'matlab
> like structure'. This was early in my learning of Python, and yes, the
> intention was to have something that was similar to a matlab
> structure... now, I've been using Python much more, and I realize that
> this may be in fact 'un-Pythonic'. The problem is, I've used it
> extensively throughout my existing modules, and I have become somewhat
> comfortable with it...
>
> I guess an alternative would be to simply define a generic class, no?
>
> class Structure(object):
>    pass
>
> Then, you could easily say:
>
> S = Structure()
> S.this = ['my slice of cheese']
>
> and perhaps I would be being more 'pythonic'?? This I could quite
> easily do, as, where I have used this class, I almost never actually
> use the 'dictionary' like referencing...
>

This is better, and I believe it is even mentioned in the official
tutorial. A problem with this is that you don't get a lot of the nice
methods the dict class provides you with to iterate over its
keys/values, find keys, and more such things.

You *can* do it this way. But do you have a specific reason for *not*
using dicts? Because that would be the idiomatic way.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python vs. MATLAB

2010-12-06 Thread Joel Schwartz
Chris,

Can you say more about number (7) in your list? What does "pass by value"
mean and what are the alternatives?

Thanks,
Joel 

> -Original Message-
> From: tutor-bounces+joel=joelschwartz@python.org 
> [mailto:tutor-bounces+joel=joelschwartz@python.org] On 
> Behalf Of Chris Fuller
> Sent: Monday, December 06, 2010 6:22 AM
> To: tutor@python.org
> Subject: Re: [Tutor] Python vs. MATLAB
> 
> 1) Python is free!
> 2) Python indices start at 0!
> 3) Python has way better GUIs
> 4) Python can emulate a lot of Matlab functionality with 
> matplotlib and numpy
> 5) Matlab has a rather limited number of data structures
> 6) Matlab doesn't have anything like the third party support 
> for almost anything
> 7) Almost everything in Matlab is pass-by-value. This can get 
> to be a bit of a
>pain at times.
> 8) Python is a general-purpose programming language, and as 
> such, has a much
>wider set of features
> 9) There are a lot more Python developers to share code with 
> and learn from
> 
> It's free! Install it on all your computers. Take it home to 
> use for work or play. Show it to your friends. Keep using it 
> after you leave your place of work/study!
> 
> The "interpreted" bit refers to the fact that the source code 
> is not compiled before it is run. This is also true of Matlab.
> 
> 
> Cheers
> 
> 
> On Monday 06 December 2010, Jaidev Deshpande wrote:
> > Dear all
> > 
> > What advantages does Python have over MATLAB as a 
> programming language,
> > (not the computing environment of MATLAB)?
> > 
> > Also, wikipedia says Python is an interpreted language, 
> what does that
> > mean?
> 
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


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


Re: [Tutor] Python vs. MATLAB

2010-12-06 Thread Wayne Werner
On Mon, Dec 6, 2010 at 11:09 AM, Joel Schwartz wrote:

> Chris,
>
> Can you say more about number (7) in your list? What does "pass by value"
> mean and what are the alternatives?
>

Pass by value is exactly what it sounds like - you pass the value (a copy of
everything in the memory). This is bad when you're passing a 10,000 item
list to a function - because you now have *two* 10,000 item lists. It's even
worse when you have many times that amount of data.

Python, OTOH passes by reference - instead of copying the list, a pointer to
the list is passed, so when you see something like this:

def do_something(a_list):
a_list[2] = 4

mylist = [1,2,3,4]
do_something(mylist)

now mylist is:

[1,2,4,4].

This is much more efficient (although it tends to bite novice programmers!).

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


Re: [Tutor] Python vs. MATLAB

2010-12-06 Thread Hugo Arts
On Mon, Dec 6, 2010 at 6:09 PM, Joel Schwartz  wrote:
> Chris,
>
> Can you say more about number (7) in your list? What does "pass by value"
> mean and what are the alternatives?
>
> Thanks,
> Joel
>

Generally, pass-by-* refers to how the arguments to functions are treated.
* In call-by-value, the value of the arguments are copied into the
function. There is no way to modify variables outside of the function
since you don't have access to them, only to copies. C uses this,
among many others:

int a = 5
void func(int b) { b = 6; }
func(a);
a == 5; /* evaluates to true, variable outside function scope remains
unchanged */

The value b, inside the function, contains a copy of a. So when it is
modified, the original a remains unchanged.

* in call-by-reference, the function is given implicit *references* to
its arguments. When modifying the variables inside of the function,
the variable outside is also changed. you can simulate it in many
languages by passing an expicit reference rather than an implicit one
(such as C's pointers):

int a = 5
void func(int * b) { *b = 6; }
func(&a);
a == 6; /* evaluates to true. the function was able to modify a
variable outside of its scope */

* python uses something that wikipedia calls "call-by-sharing." It is
not call-by-value, nor is it call-by-reference. It means, in short,
that while the function has access to the callers, *values*, it does
NOT have access to the callers *variables*. To demonstrate:

a = []
def f(b):
b.append(1)
b = [2]
f(a)
print a # prints "[1]"

As in pass-by-reference, the function f could modify it's callers
values by appending 1 to the list. However, unlike *real*
pass-by-reference, when trying to *re-assign* the variable into
something entirely different, there was no effect (a did not become
equal to [2]).


Many people call python pass-by-reference, even though this is
technically incorrect. The difference comes from the semantics of
variables and values. In languages such as C, a variable is an area of
memory that contains something. An assignment then, copies the value
on the right into the variable (memory) on the left.

python doesn't have variables, but names. a name is essentially itself
a reference to some *object* that lives somewhere in memory. An
assignment is something completely different in this context, it
merely sets the reference (variable) on the left to *point to* the
object on the right. So, when evaluating function arguments, names
inside the function are set to point to the *objects* supplied as
arguments, (not to names!). Since we don't have access to the caller's
names, python is not a true pass-by-reference language.

for more on why python is neither call-by-value nor call-by-reference:
http://effbot.org/zone/call-by-object.htm

for more on python's variable semantics and how it differs from
languages like C:
http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables

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


Re: [Tutor] role playing game - help needed

2010-12-06 Thread Alan Gauld


"Al Stern"  wrote

Thanks for the advice.  I think I have the dictionary function set 
up right

now although I'm still not clear why it is better than the list.

attributes = {"strength": 0, "health": 0, "wisdom": 0, "dexterity": 
0}


Consider where you want to update the points for "health"

Using two lists you need to loop over the keys list to find the index
of "health" then access the values list to set the points. Something
like this:

for x in range(len(keys)):
   if keys[x] == "health":
   values[x] = newValue

With a dictionary you just need to do

attributes["health"] = newValue

That's a lot less typing and will be faster performance too.
I'd also say its a lot easier to see whats happening - its more 
readable.


HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



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


Re: [Tutor] Python vs. MATLAB

2010-12-06 Thread Alan Gauld


"Jaidev Deshpande"  wrote

What advantages does Python have over MATLAB as a programming 
language,


Python is a general purpose programming language.
Matlab is a mathematical modelling toool that happens to be 
programmable.


You wouldn't sensibly use Matlab to create a web site, or an action 
game

or a network analyzer, or a graphics editor, or

You could use Python for any of these.

But Matlab beats Python if you want to build standard math models.
You can do those in Python, and arguably for very complex models
Python is better. But for "simple" models as found in most engineering
and science experiments Matlab will be easier to use. IMHO


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


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


Re: [Tutor] Python vs. MATLAB

2010-12-06 Thread Chris Fuller

It also makes it hard to modify some data structure you are working with.  I 
was experimenting with some object-oriented programming in Matlab, and you 
actually have to explicitly inherit from "handle" if you have any methods that 
modify internal state.  That was a surprise!

If you've got a data structure built out of arrays or cell arrays and you want 
to not make copies everytime you pass it into or out of a function, you pretty 
much have to wrap it in one of these classes.  Another option is to use 
closures, with function handles, but that's pretty clunky also.

Cheers


On Monday 06 December 2010, Wayne Werner wrote:
> On Mon, Dec 6, 2010 at 11:09 AM, Joel Schwartz wrote:
> > Chris,
> > 
> > Can you say more about number (7) in your list? What does "pass by value"
> > mean and what are the alternatives?
> 
> Pass by value is exactly what it sounds like - you pass the value (a copy
> of everything in the memory). This is bad when you're passing a 10,000
> item list to a function - because you now have *two* 10,000 item lists.
> It's even worse when you have many times that amount of data.
> 
> Python, OTOH passes by reference - instead of copying the list, a pointer
> to the list is passed, so when you see something like this:
> 
> def do_something(a_list):
> a_list[2] = 4
> 
> mylist = [1,2,3,4]
> do_something(mylist)
> 
> now mylist is:
> 
> [1,2,4,4].
> 
> This is much more efficient (although it tends to bite novice
> programmers!).
> 
> HTH,
> Wayne

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


[Tutor] SAVE FILE IN A SPECIFIC DIRECTORY

2010-12-06 Thread Susana Iraiis Delgado Rodriguez
I'm trying to save files into a specific directory, the file will be
generated from a python script. The script will look for some data stored in
a directory which only allows to read files, it doesn't let the user write
or modify information. But when I run the script I got the next error:
Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)]
on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import crawler_shp
Traceback (most recent call last):
  File "", line 1, in 
  File "crawler_shp.py", line 103, in 
a = open (filepath +t,"w+")
IOError: [Errno 2] No such file or directory:
'C\\Python26\\BUFFER1000_bd.txt'
>>>
My script is:
import os, time, socket, pylab,fnmatch
from xlwt import Workbook
from osgeo import ogr,gdal,osr
from dbf import *

gdal.AllRegister()
file_list = []
folders = None
for root, folders, files in os.walk( "R:\\" ):
 for filename in fnmatch.filter(files, '*.shp'):
  file_list.append(os.path.join(root, filename))
wrkbk = Workbook()
wksht = wrkbk.add_sheet('shp')
wksht.row(0).write(0,'ruta')
wksht.row(0).write(1,'archivo')
wksht.row(0).write(2,'estructura bd')
for row, filepath in enumerate(file_list, start=1):
 wksht.row(row).write(0, filepath)
 (ruta, filename) = os.path.split(filepath)
 wksht.row(row).write(1, filename)
  f = os.path.splitext(filename)
  t = f[0]+'_bd.txt'
  d = n[0]+'.dbf'
  if os.path.lexists(d):
  filepath = "C\\Python26\\"
   a = open (filepath +t,"w+")
   dbf = Dbf(d,new=False)


   for fldName in dbf.fieldDefs:
a.write(fldName.name)
a.write(" || ")
a.write(fldName.typeCode)
a.write("\n")
   dbf.close()
   a.close()
wksht.row(row).write(2, t)
   else:
   print "El archivo " +n[0]+".shp" " no tiene dbf"
   wksht.row(row).write(10, "Sin bd")


wrkbk.save('C\\Python26\\biblio_shp.xls')
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python vs. MATLAB

2010-12-06 Thread Steven D'Aprano

Chris Fuller wrote:

On Monday 06 December 2010, Jaidev Deshpande wrote:



Also, wikipedia says Python is an interpreted language, what does that
mean?


The "interpreted" bit refers to the fact that the source code is not compiled 
before it is run. This is also true of Matlab.


That's not completely correct. What do you think the compile() function 
in Python does, or what the "c" in .pyc files stands for?


Strictly speaking, languages are neither interpreted or compiled, they 
just *are*. Implementations of languages are either interpreted or compiled.


In Python's case, the three major implementations (CPython, Jython and 
IronPython) take the source code and compile it to byte-code rather than 
native machine code. Then the byte-code is executed by a virtual 
machine, rather than machine code executed directly by your CPU.


This use of a virtual machine is much the same as what (e.g.) Java does. 
However, Java many years ago developed the ability to compile direct to 
native machine code, which is much faster to run. That step is 
considerably harder for Python. However, there is good progress in that 
direction:


* Psyco is an old but still serviceable Just In Time compiler for 32-bit 
versions of CPython which can speed many (but not all) operations up 
greatly, by compiling them to native machine code at runtime.


* Berp and HoPe are experimental implementations of Python written in 
Haskell instead of C. Berp translates the Python source code into 
Haskell, which can then be compiled to machine code. I'm not sure about 
HoPe.


* UnPython is an experimental attempt to translate Python into C, which 
can then be compiled to machine code.


* PyPy is an optimizing Python virtual machine written in Python itself, 
using JIT technology to produce faster code. PyPy now is about twice as 
fast as CPython, for typical programs, and the ambitious aim is to 
become an general-purpose optimizing engine that can produce code that 
runs faster than the equivalent written in C.




--
Steven


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


Re: [Tutor] SAVE FILE IN A SPECIFIC DIRECTORY

2010-12-06 Thread Peter Otten
Susana Iraiis Delgado Rodriguez wrote:

[UPPER CASE text is interpreted as shouting in emails and usenet posts. 
Please don't shout. Because spammers do it all the time it's more likely to 
make potential readers turn away from your writ rather than pay extra 
attention.]

> I'm trying to save files into a specific directory, the file will be
> generated from a python script. The script will look for some data stored
> in a directory which only allows to read files, it doesn't let the user
> write or modify information. But when I run the script I got the next
> error: Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit
> (Intel)] on
> win32
> Type "help", "copyright", "credits" or "license" for more information.
 import crawler_shp
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "crawler_shp.py", line 103, in 
> a = open (filepath +t,"w+")
> IOError: [Errno 2] No such file or directory:
> 'C\\Python26\\BUFFER1000_bd.txt'

Looks like you forgot a colon after the "C". Also note that C:\\Python26 is 
a bad place to store your own stuff.

A general remark on your code: it looks like you spend quite some time on 
it, and the up-front time it takes to make it reader-friendly will save you 
and others a multiple in debugging cost. So please

- Use 4-space indents
- Choose descriptive names, not a, t, f, that even if understood in the 
context of an expression will be forgotten three lines below. Also 'wrksht' 
or 'wrkSht' have no advantage over 'worksheet'. Vowels are your friend ;)
- Cut dead wood. Remove variables or imports that aren't currently used. You 
can always reintroduce them later on.
- Bonus: split your code into functions. It may seem like extra work at 
first, but it makes it easy to test small chunks of simple code and then to 
build more complex scripts by combining these "known good" pieces.

Peter

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


Re: [Tutor] Python vs. MATLAB

2010-12-06 Thread Steven D'Aprano

Joel Schwartz wrote:

Chris,

Can you say more about number (7) in your list? What does "pass by value"
mean and what are the alternatives?


Oh boy, is that a can of worms... and this is going to be a long post. 
You might want to go make yourself a coffee first :)


Pass by whatever (also written as "call by ...") is one of those 
frustrating topics where people have added vast amounts of confusion 
where no confusion need exist.


Take a variable, "x", and give it a value, say, 42. When you pass that 
variable to a function, func(x), what happens?


Such a simple question, but you wouldn't believe how many angry words 
have been written about it.


The problem is that there are a whole lot of answers to that question, 
used by many different programming languages, but most people are only 
familiar with *two*: pass by value, and pass by reference. This is 
particularly strange since most popular modern languages, like Ruby, 
Python and Java, don't use either of those! Nevertheless, people have 
got it in their head that there are only two calling conventions, and so 
they hammer the square peg of the language's actual behaviour until it 
will fit one or the other of the round holes in their mind.


So there are huge flame wars about whether Python is pass by value or 
pass by reference, with some people wrongly claiming that Python is 
p-b-v for "simple" objects like numbers and strings and p-b-r for 
"complicated" objected like lists. This is nonsense.


But that pales before the craziness of the Java community, that claims 
that Java is pass by value so long as you understand that that values 
being passed are references and not the value of the variable. But don't 
make the mistake of thinking that makes Java pass by reference! Pass by 
value-which-is-actually-a-reference is completely different from pass by 
reference. Only the Java people don't call it that, they just call it 
pass by value, even though Java's behaviour is different from pass by 
value in common languages like C, Pascal and Visual Basic.


How is this helpful? Even if *technically* true, for some definition of 
"reference" and "value", it is gobbledygook. It's as helpful as claiming 
that every language ever written, without exception, is actually pass by 
flipping bits. No values are actually passed anywhere, it's all just 
flipping bits in memory.


100% true, and 100% useless.

Translated into Python terms, the Java argument is this:

Take a variable, call it "x". When you say x = 42, the value of x is not 
actually the number 42, like naive non-Java programmers might think, but 
some invisible reference to 42. Then when you call function(x), what 
gets passed to the function is not 42 itself (what Pascal or C 
programmers call "pass by value"), nor is it a reference to the 
*variable* "x" (which would be "pass by reference"), but the invisible 
reference to 42. Since this is the "true" value of x, Java is pass by value.


(The situation is made more complicated because Java actually does pass 
ints like 5 by value, in the C or Pascal sense. The above description 
should be understood as referring to "boxed" integers, rather than 
unboxed. If this means nothing to you, be glad. All you need know is 
that in Java terms, all Python integers are boxed.)


And note that in the Ruby community, they call the exact same behaviour 
"pass by reference". And then folks wonder why people get confused.


All this because people insist on the false dichotomy that there are 
only two argument passing conventions, pass by value and pass by 
reference. But as this Wikipedia page shows, there are actually many 
more than that:


http://en.wikipedia.org/wiki/Evaluation_strategy


Let's go back to my earlier question. You have a variable x = 42, and 
you pass it to a function. What happens?


In Pascal, or C, the compiler keeps a table mapping variable names to 
fixed memory addresses, like this:


Variable  Address
  ===
x 10234
y 10238
z 10242

The command "x = 42" stuffs the value 42 into memory address 10234. 
Then, when you call func(x), the compiler looks up memory address 10234 
and copies whatever it finds (in this case, 42) into another memory 
address (say, 27548), where func can see it. This is pass by value.


What this means is the the variable x *inside* the function is not the 
same as the variable x *outside* the function. Inside the function, x 
has the address 27548, and the command "x = x + 1" will store 43 there, 
leaving the outside x at 10234 unchanged. This is normally a good thing.


The classic test of pass by value is, does the value get copied when you 
pass it to a function? We can test Python to see if it copies values:


>>> def func(arg):
... print(id(arg))
...
>>> x = 42
>>> print(id(x))
135996112
>>> func(x)
135996112

The local variable arg and the global variable x have the same ID, which 
means they are the same object. This is conclusive proof that Python 
does not make 

Re: [Tutor] role playing game - help needed

2010-12-06 Thread Al Stern
Ok.  I think I am starting to get it but still not sure how to separate the
value from the key.  Once I have this...

attributes = {"strength": 0, "health": 0, "wisdom": 0, "dexterity": 0}
MAX_POINTS = 30

How do I set the variable for available_points?

available_points = MAX_POINTS - (not sure what goes here)

I am pretty sure I will change the values by something like this...

attributes["strength"] = input("\nHow many points do you want to assign to
strength?: ")

Please let me know if this isn't advisable.  It seems to work on the
surface.

On Mon, Dec 6, 2010 at 1:16 PM, Alan Gauld wrote:

>
> "Al Stern"  wrote
>
>
> Thanks for the advice.  I think I have the dictionary function set up right
>> now although I'm still not clear why it is better than the list.
>>
>> attributes = {"strength": 0, "health": 0, "wisdom": 0, "dexterity": 0}
>>
>
> Consider where you want to update the points for "health"
>
> Using two lists you need to loop over the keys list to find the index
> of "health" then access the values list to set the points. Something
> like this:
>
> for x in range(len(keys)):
>   if keys[x] == "health":
>   values[x] = newValue
>
> With a dictionary you just need to do
>
> attributes["health"] = newValue
>
> That's a lot less typing and will be faster performance too.
> I'd also say its a lot easier to see whats happening - its more readable.
>
> HTH,
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor