[Tutor] quick speed question

2010-09-16 Thread C.T. Matsumoto

Hello Tutors,

I was just wondering if you have a dictionary key is it faster to do:

if dict['key'] == 'foo':
...

or is this faster:

if 'foo' in dict['key']:
...

Or is there any difference and I'm chasing ghosts?

Thanks,

T
--
C.T. Matsumoto
Claes de Vrieselaan 60a III
3021 JR Rotterdam
The Netherlands

tel.: +31 (0)6 41 45 08 54
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] quick speed question

2010-09-16 Thread Evert Rol
> Hello Tutors,
> 
> I was just wondering if you have a dictionary key is it faster to do:
> 
> if dict['key'] == 'foo':
>...
> 
> or is this faster:
> 
> if 'foo' in dict['key']:
>...
> 
> Or is there any difference and I'm chasing ghosts?

The latter: they are not the same:

>>> d = {'key': 'food'}
>>> d['key'] == 'foo'
False
>>> 'foo' in d['key']
True


Btw, generally don't use a reserved Python word for a variable, such as dict in 
this case (I know it's an example, but it's still unsafe practice).

Cheers,

  Evert

> 
> Thanks,
> 
> T
> -- 
> C.T. Matsumoto
> Claes de Vrieselaan 60a III
> 3021 JR Rotterdam
> The Netherlands
> 
> tel.: +31 (0)6 41 45 08 54
> ___
> 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] working with empty lists

2010-09-16 Thread Timo

On 16-09-10 06:05, Rance Hall wrote:

Im working on a little piece of test code to test an idea for a larger script.

Here is what I've got so far:

l = []

for i in range(0,10)
 l.append(i)

for i in range(0,10)
 print('%s. %s' % (i, l[i])


This gives me:

0. 0
1. 1
2. 2  etc

which is what I expect, but what I want is to get something like

0. 1
1. 2
2. 3 .

so that the output is clearly different on either side of the "."
   

You could do this:
>>> l = []
>>> for i in range(1, 11):
...   l.append(i)
...
>>> for index, i in enumerate(l):
...   print('%s. %s' %(index, i))
...
0. 1
1. 2
2. 3
3. 4
etc.

Cheers,
Timo


I tried changing the append to l.append(i+1)

which almost worked but the output started with 1. 2  I was curious
what happend to the 0. 1 line

I know this means that I'm not understanding exactly what append actually does.

I know that my ide shows that the list as other functions like insert, etc.

Can someone explain to me whats the best way to add a value to a list
that is not long enough to accept it, without playing with the
indexes, it appears I currently am playing with them.

I know generally that we aren't supposed to care about the indexes but
this is eventually going to be part of a menuing system that displays
the index, so I do have a legit need to care about what is happening
to the list index.
___
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] working with empty lists

2010-09-16 Thread Alan Gauld


"Rance Hall"  wrote


Here is what I've got so far:

l = []
for i in range(0,10)
   l.append(i)

for i in range(0,10)
   print('%s. %s' % (i, l[i])

I tried changing the append to l.append(i+1)

which almost worked but the output started with 1. 2  I was curious
what happend to the 0. 1 line


You made a mistake somewhere, it works as you expected
if you only make that one change.

I know generally that we aren't supposed to care about the indexes 
but
this is eventually going to be part of a menuing system that 
displays

the index, so I do have a legit need to care about what is happening
to the list index.


That's probably a bad idea. It's confusing for users if the number of 
their

favourite command changes, as it would if you added a new command
into the list etc. (One of the big advantages of menu driven CLIs is 
that

users learn the sequences they use regularly and start to "type ahead"
which makes for a very efficient operation.) It's usually better to 
keep

the command number as part of the menu data and then sort the
command in order based on that.

Just a thought,


--
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] intercepting and recored I/O function calls

2010-09-16 Thread Jojo Mwebaze
On Wed, Sep 15, 2010 at 11:37 PM, Alan Gauld wrote:

>
> "Jojo Mwebaze"  wrote
>
>
>  I would like to intercept and record I/O function calls to a file.. (later
>> to a database) with probably the names of the files that have been
>> created,
>> accessed / deleted in my program. I  have not done something like this
>> before.. Some Guidance is highly appreciated
>>
>
> Are you talking about I/O calls in your own app? If so thats fairly
> straightforward to do. OTOH If you are talking about capturing all
> I/O calls that's a lot harder and if it's a multi-user OS will need
> administrator privileges.
>

I could begin with tracing I/O calls in my App.. if its sufficient enough i
may not need i/o calls for the OS.

>
> But this is extremely dependant on the Operating System - you will
> basically
> have to intercept the system calls. So, which OS are you using?
> And how familiar are you with its API?
>

I am using centos, however i don't even have admin privileges.   Which API
are you referring to?

 Al;so, While you can probably do this in Python but its likely to have
> a serious impact on the OS performance, it will slow down the performamce
> quite noticeably. I'd normally recommend using C for something like this.
>
> 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


Re: [Tutor] How to get both 2.6 scripts as well as 3.1 scripts to run at command line?

2010-09-16 Thread Alan Gauld


"Richard D. Moores"  wrote

Some of the scripts written for 2.6 use libraries not yet available 
for 3.x.
So I want to know not how to modify them, but how to run them at the 
command

line.


Install 2.x.
This is why we keep recommending that beginners stick with 2.x.
Its why the 2.x line has not died out and still gets new releases.

Eventually the library owners will port their code but until then
you need to use the version of python they are written for.
You cannot mix them reliably.


--
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] How to get both 2.6 scripts as well as 3.1 scripts to runat command line?

2010-09-16 Thread Alan Gauld


"Richard D. Moores"  wrote

I have no problem running 3.1 scripts at the command line. However 
2.6
scripts seems to require 2.x. For example, I get this error showing 
that the

old 2.x print won't do:


Thats correct, there are several big changes between V2 and V3.
They are not compatible. You can do some things to make a script
compatible but in the general case you cannot run 2.x scripts in 3.x

If you have the latest 2.x release you can run some 3.x code in
them by importing from future but its not fullproof. Similarly there 
is

a convertion script from 2 to 3 but again its not follprooof, it just
handles the most common cases. See the documentation for v3
for more details.


--
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] quick speed question

2010-09-16 Thread Modulok
This is faster:

if dict['key'] == 'foo':
pass

...But just slightly. (About 9% faster on my machine. This may differ
depending on the implementation, but I doubt it. See the 'timeit'
module.) Whether it's a big deal depends on what you're doing.
Accessing the dict - a million times - with either method took less
than a second. Visually, this makes more sense to me:

if dict['key'] == 'foo':
pass

Regardless, you should be aware that while they look similar, they
differ in their semantics:

# Something to work with:
dic = {'a': "Big", 'b': "Bigger"}

# This is true:
if dic['a'] == "Big":
print True

# And this is true:
if "Big" in dic['a']:
print True

# But this is also true!
if "Big" in dic['b']:
print True

As far as speed is concerned: Don't worry about it unless has already
become a problem. Premature optimization wastes time you should be
spending solving the actual problem. For example, if you wrote an MP3
player that sorted playlists in 0.1 seconds instead of 0.2
seconds (100% faster!), but you wasted 3 days doing it - you haven't
accomplished much.

When you're done and you find you need a faster solution, optimize
your algorithms. If that still isn't enough, ask somebody smarter than
yourself to look at it. (This list is great for that!) If that too
fails, start think about writing a few critical bits in C, but only as
a last resort.

"We should forget about small efficiencies, say about 97% of the time:
premature optimization is the root of all evil" -Donald knuth-

-Modulok-

On 9/16/10, C.T. Matsumoto  wrote:
> Hello Tutors,
>
> I was just wondering if you have a dictionary key is it faster to do:
>
> if dict['key'] == 'foo':
>  ...
>
> or is this faster:
>
> if 'foo' in dict['key']:
>  ...
>
> Or is there any difference and I'm chasing ghosts?
>
> Thanks,
>
> T
> --
> C.T. Matsumoto
> Claes de Vrieselaan 60a III
> 3021 JR Rotterdam
> The Netherlands
>
> tel.: +31 (0)6 41 45 08 54
> ___
> 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] quick speed question

2010-09-16 Thread Dave Angel



On 2:59 PM, C.T. Matsumoto wrote:

Hello Tutors,

I was just wondering if you have a dictionary key is it faster to do:

if dict['key'] == 'foo':
...

or is this faster:

if 'foo' in dict['key']:
...

Or is there any difference and I'm chasing ghosts?

Thanks,

T
dict is not a good name for a dictionary, since it's a built-in name.  
But ignoring that,


The two lines you show do different things

Both of them look up a single item in the dictionary, so that part takes 
the same time.  But then the first compares the resulting string to 
exactly 'foo', while the second searches in the string to see if 'foo' 
is a substring.


If you need one of them, the other will get the wrong answer.  So 
knowing that the first is faster is irrelevant.


DaveA

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


Re: [Tutor] How to get both 2.6 scripts as well as 3.1 scripts to run at command line?

2010-09-16 Thread Richard D. Moores
On Thu, Sep 16, 2010 at 00:54, Alan Gauld  wrote:
>
> "Richard D. Moores"  wrote
>
>> Some of the scripts written for 2.6 use libraries not yet available for 3.x.
>> So I want to know not how to modify them, but how to run them at the command
>> line.
>
> Install 2.x.
> This is why we keep recommending that beginners stick with 2.x.
> Its why the 2.x line has not died out and still gets new releases.
>
> Eventually the library owners will port their code but until then
> you need to use the version of python they are written for.
> You cannot mix them reliably.

I should have stated that I have 2.6, 2.7, and 3.1  installed. The
scripts are in 2 groups. One written in 2.6, the other in 3.1. Most
run fine in the appropriate version of IDLE, or in Wing when I change
between c:\Python31\pythonw31.exe and c:\Python26\python.exe .  But
some 2.6 scripts must be run at the command line. All the 3.1 scripts
do, but not the 2.6's.

So my problem and question is how to set up a command line that will
run not just the 2.6 scripts that must be run there, but all of them.

And you know what? In thinking through again what my problem was, I
got the idea to try this, and it worked:

==
C:\P26Working\Finished>c:\Python26\python.exe solveCubicEquation.py
Enter real coefficients a,b,c: 3,2,1
a is 3.0
b is 2.0
c is 1.0
equation is (x**3) + (3.00*x**2) + (2.00*x) + (1.00) = 0

roots: [(-2.3247179572447463+0j),
(-0.33764102137762697+0.56227951206230142j),
(-0.33764102137762697-0.56227951206230142j)]

After ignoring very small root.real and root.imag,
and rounding to 4 significant figures:

root1 is -2.325
root2 is -0.3376+0.5623j
root3 is -0.3376-0.5623j

Press Enter to solve another; n to close:
==

So thanks to all for trying to help. Without your tries I wouldn't
have figured it out!

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


Re: [Tutor] How to get both 2.6 scripts as well as 3.1 scripts to run at command line?

2010-09-16 Thread Richard D. Moores
I forgot to mention that I didn't write that solveCubicEquation.py
script. I paid a pittance to mathtalk-ga at the old Google Answers to
not only write it, but to explain it. I recommend these 2 pages to
those with a mathematical bent:




And here's "my" solveCubicEquation.py script:



On Thu, Sep 16, 2010 at 02:28, Richard D. Moores  wrote:
> On Thu, Sep 16, 2010 at 00:54, Alan Gauld  wrote:
>>
>> "Richard D. Moores"  wrote
>>
>>> Some of the scripts written for 2.6 use libraries not yet available for 3.x.
>>> So I want to know not how to modify them, but how to run them at the command
>>> line.
>>
>> Install 2.x.
>> This is why we keep recommending that beginners stick with 2.x.
>> Its why the 2.x line has not died out and still gets new releases.
>>
>> Eventually the library owners will port their code but until then
>> you need to use the version of python they are written for.
>> You cannot mix them reliably.
>
> I should have stated that I have 2.6, 2.7, and 3.1  installed. The
> scripts are in 2 groups. One written in 2.6 (or 2.5), the other in 3.1. Most
> run fine in the appropriate version of IDLE, or in Wing when I change
> between c:\Python31\pythonw31.exe and c:\Python26\python.exe .  But
> some 2.6 scripts must be run at the command line. All the 3.1 scripts
> do, but not the 2.6's.
>
> So my problem and question is how to set up a command line that will
> run not just the 2.6 scripts that must be run there, but all of them.
>
> And you know what? In thinking through again what my problem was, I
> got the idea to try this, and it worked:
>
> ==
> C:\P26Working\Finished>c:\Python26\python.exe solveCubicEquation.py
> Enter real coefficients a,b,c: 3,2,1
> a is 3.0
> b is 2.0
> c is 1.0
> equation is (x**3) + (3.00*x**2) + (2.00*x) + (1.00) = 0
>
> roots: [(-2.3247179572447463+0j),
> (-0.33764102137762697+0.56227951206230142j),
> (-0.33764102137762697-0.56227951206230142j)]
>
>    After ignoring very small root.real and root.imag,
>    and rounding to 4 significant figures:
>
> root1 is -2.325
> root2 is -0.3376+0.5623j
> root3 is -0.3376-0.5623j
>
> Press Enter to solve another; n to close:
> ==
>
> So thanks to all for trying to help. Without your tries I wouldn't
> have figured it out!
>
> Dick


I forgot to mention that I didn't write that solveCubicEquation.py
script. I paid a pittance to mathtalk-ga at the old Google Answers to
not only write it, but to explain it. I recommend these 2 pages to
those with a mathematical bent:




And here's "my" solveCubicEquation.py script:


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


[Tutor] Regex comments

2010-09-16 Thread Michael Powe
 Hello,

The re module includes the option to comment a regular expression with
the syntax (?#comment).  e.g.

p=r'(.*) (?PWT.dl)(?#parameter)=(?P[^&]+)(?#value).*'

Is there a mechanism for extracting these values from the match, in
the way that group names are extracted?

I don't see one.

The point would be that in my processing of the match, I could
implement the comments as identifiers for the matched value.

Thanks.

mp

-- 
Michael Powemich...@trollope.orgNaugatuck CT USA
"The most likely way for the world to be destroyed, most experts
agree, is by accident.  That's where we come in. We're computer
professionals. We cause accidents."  -- Nathaniel Borenstein, inventor
of MIME


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


Re: [Tutor] Regex comments

2010-09-16 Thread Peter Otten
Michael Powe wrote:

> The re module includes the option to comment a regular expression with
> the syntax (?#comment).  e.g.
> 
> p=r'(.*) (?PWT.dl)(?#parameter)=(?P[^&]+)(?#value).*'
> 
> Is there a mechanism for extracting these values from the match, in
> the way that group names are extracted?
> 
> I don't see one.

You could write a regular expression to extract them ;)

> The point would be that in my processing of the match, I could
> implement the comments as identifiers for the matched value.

But that's what the names are for, e. g.:

>>> re.compile(r'(.*) (?PWT.dl)=(?P[^&]+).*').search(
" WTxdl=yadda&ignored").groupdict()
{'parameter': 'WTxdl', 'value': 'yadda'}

Or am I missing something?

Peter

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


Re: [Tutor] Regex comments

2010-09-16 Thread Michael Powe
On Thu, Sep 16, 2010 at 01:31:09PM +0200, Peter Otten wrote:
> Michael Powe wrote:
 
> > The re module includes the option to comment a regular expression with
> > the syntax (?#comment).  e.g.

> > Is there a mechanism for extracting these values from the match, in
> > the way that group names are extracted?

> > I don't see one.
 
> You could write a regular expression to extract them ;)

;-)
 
> > The point would be that in my processing of the match, I could
> > implement the comments as identifiers for the matched value.
> 
> But that's what the names are for, e. g.:
> 
> >>> re.compile(r'(.*) (?PWT.dl)=(?P[^&]+).*').search(
> " WTxdl=yadda&ignored").groupdict()
> {'parameter': 'WTxdl', 'value': 'yadda'}

That's right, I forgot about the dictionary.  Thanks!

mp

-- 
Michael Powemich...@trollope.orgNaugatuck CT USA
"No provision in our Constitution ought to be dearer to man than that
which protects the rights of conscience against the enterprises of the
civil authority." -- Thomas Jefferson to New London Methodists,
1809. ME 16:332


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


[Tutor] "Overloading" methods

2010-09-16 Thread Michael Powe
Hello,

Strictly speaking, this isn't overloading a method in the way we do it
in Java.  But similar.  Maybe.

I am writing a module for processing web server log files and one of
the methods I provide is to extract a given query parameter and its
value. Because there are several types of log files with different
line structures, I had the thought to write methods with descriptive
names that simply returned a generic method that processed the method
arguments. e.g.,

def setpattern_iis(self,pattern,parameter) :
type='iis'
return pattern_generator(self,type,pattern,parameter)

In this case, creating a regular expression to parse the log lines for
a query parameter.

This is just a bit more "self documenting" than using the generic
method with the 'type' argument and requiring the user to enter the
type.  At the same time, it allows me to put all the parsing code in
one method.

My question is, is this a bad thing to do in python?

Thanks.

mp

-- 
Michael Powemich...@trollope.orgNaugatuck CT USA
War is a sociological safety valve that cleverly diverts popular
hatred for the ruling classes into a happy occasion to mutilate or
kill foreign enemies. - Ernest Becker


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


[Tutor] Function behavior

2010-09-16 Thread Ken Green
I am unclear on the behavior of using a function.  Below is a short code 
I wrote to print an amount out after inputting the number of match.


# TEST Function.py

def change(amount):
if match == 1:
amount = 0
if match == 2:
amount = 0
if match == 3:
amount = 3

match = raw_input("How many matches?: ")
change(match)
print amount

ERROR Message:

How many matches?: 2
Traceback (most recent call last):
  File "/home/ken/Python262/TEST Function.py", line 13, in 
print amount
NameError: name 'amount' is not defined

How do I print out the amount of 0 if I input 2?

Should it be def change(match) instead of def change(amount)?

Perhaps, change(amount) instead of change(match)?

Perhaps, I need to add return somewhere?

Thanking you all in advance for your assistance.

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


Re: [Tutor] working with empty lists

2010-09-16 Thread Rance Hall
On Wed, Sep 15, 2010 at 11:33 PM, bob gailer  wrote:
>  On 9/16/2010 12:05 AM, Rance Hall wrote:
>>


Thanks guys for replying, looks like I do have a bug in my code, but
its not where I thought it was.  Must have been up too late last
night.

The code I provided in my OP does work (with typos corrected) but this
code with one layer of complexity does not.

def paginate_stuff(list,start):
pagesize = 2
for i in list[start:start+pagesize]:
print('%s. %s' % (i,list[i]))
return

l = []
for i in range(0,10):
l.append(i+1)

paginate_stuff(l,0)



Idea here is to be able to take N things Y at a time sequentially from
anywhere in the middle of the list.

every time I run this code I start the output one list item in the
sequence ahead of where I want to.

I can change the functional call to paginate_stuff(l,3)

and it will start where the above one leaves off

But I keep losing list[0]

Im reasonably sure that it has something to do with my for loop, but I
don't understand how
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Function behavior

2010-09-16 Thread Viacheslav Chumushuk
On Thu, Sep 16, 2010 at 08:18:45AM -0400, Ken Green  
wrote:
> I am unclear on the behavior of using a function.  Below is a short
> code I wrote to print an amount out after inputting the number of
> match.
> 
> # TEST Function.py
> 
> def change(amount):
> if match == 1:
> amount = 0
> if match == 2:
> amount = 0
> if match == 3:
> amount = 3
> 
> match = raw_input("How many matches?: ")
> change(match)
> print amount
> 
> ERROR Message:
> 
> How many matches?: 2
> Traceback (most recent call last):
>   File "/home/ken/Python262/TEST Function.py", line 13, in 
> print amount
> NameError: name 'amount' is not defined
> 
> How do I print out the amount of 0 if I input 2?
> 
> Should it be def change(match) instead of def change(amount)?
> 
> Perhaps, change(amount) instead of change(match)?
> 
> Perhaps, I need to add return somewhere?
> 
> Thanking you all in advance for your assistance.
> 
> Ken
If you want to get value from a function you whould return it, from that
function. So, you should use something like next code:

def change(amount):
 amount = -1 #

 if match == 1:
 amount = 0
 if match == 2:
 amount = 0
 if match == 3:
 amount = 3
 
 return amount
 
match = raw_input("How many matches?: ")
amount = change(match)
print amount

And please note next thing. amount variable inside function's body is not the 
same as amount outside.
You should read about variable scope (local/global variables).

-- 
Please, use plain text message format contacting me, and
don't use proprietary formats for attachments (such as DOC, XLS)
use PDF, TXT, ODT, HTML instead. Thanks.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Function behavior

2010-09-16 Thread Evert Rol
> I am unclear on the behavior of using a function.  Below is a short code I 
> wrote to print an amount out after inputting the number of match.
> 
> # TEST Function.py
> 
> def change(amount):
>if match == 1:
>amount = 0
>if match == 2:
>amount = 0
>if match == 3:
>amount = 3
> 
> match = raw_input("How many matches?: ")
> change(match)
> print amount
> 
> ERROR Message:
> 
> How many matches?: 2
> Traceback (most recent call last):
>  File "/home/ken/Python262/TEST Function.py", line 13, in 
>print amount
> NameError: name 'amount' is not defined

Variables are only local to the their direct surroundings: in this case, amount 
is only local to the 'change' function, not outside it.

You might want to read through 
http://docs.python.org/tutorial/controlflow.html#defining-functions first.


  Evert


> How do I print out the amount of 0 if I input 2?
> 
> Should it be def change(match) instead of def change(amount)?
> 
> Perhaps, change(amount) instead of change(match)?
> 
> Perhaps, I need to add return somewhere?
> 
> Thanking you all in advance for your assistance.
> 
> Ken
> ___
> 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] "Overloading" methods

2010-09-16 Thread Vince Spicer
On Thu, Sep 16, 2010 at 6:02 AM, Michael Powe  wrote:

> Hello,
>
> Strictly speaking, this isn't overloading a method in the way we do it
> in Java.  But similar.  Maybe.
>
> I am writing a module for processing web server log files and one of
> the methods I provide is to extract a given query parameter and its
> value. Because there are several types of log files with different
> line structures, I had the thought to write methods with descriptive
> names that simply returned a generic method that processed the method
> arguments. e.g.,
>
> def setpattern_iis(self,pattern,parameter) :
>type='iis'
>return pattern_generator(self,type,pattern,parameter)
>
> In this case, creating a regular expression to parse the log lines for
> a query parameter.
>
> This is just a bit more "self documenting" than using the generic
> method with the 'type' argument and requiring the user to enter the
> type.  At the same time, it allows me to put all the parsing code in
> one method.
>
> My question is, is this a bad thing to do in python?
>
> Thanks.
>
> mp
>
> --
> Michael Powemich...@trollope.orgNaugatuck CT USA
> War is a sociological safety valve that cleverly diverts popular
> hatred for the ruling classes into a happy occasion to mutilate or
> kill foreign enemies. - Ernest Becker
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
Well I can't comment on right or wrong I would think creating a simple class
with a __call__ method is a
little more pythonic.

Example:

class PatternGenerator(object):
"""Run a regex."""
def __init__(self, type_):
self.type = type_
def __call__(self, pattern, parameter):
return pattern_generator(self, self.type, pattern, parameter)

# Initialize class
setpattern_iis = PatternGenerator('iis')

# call the method here
setpattern_iis("pattern", "params")

Hope that helps,

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


Re: [Tutor] working with empty lists

2010-09-16 Thread Joel Goldstick
I typed in this:


  3 l = []
  4
  5 for i in range(0,10):
  6 l.append(i+1)
  7
  8 for i in range(0,10):
  9 print ('%s. %s' % (i, l[i]))
 10
 11 def paginate_stuff(list, start):
 12 pagesize = 2
 13 for i in list[start:start+pagesize]:
 14 print ('%s. %s' % (i,list[i]))
 15 return
 16
 17 paginate_stuff(l,0)

and i get this:
0. 1
1. 2
2. 3
3. 4
4. 5
5. 6
6. 7
7. 8
8. 9
9. 10
1. 2
2. 3


What are you expecting?


But I keep losing list[0]
>
> Im reasonably sure that it has something to do with my for loop, but I
> don't understand how
> ___
> 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] quick speed question

2010-09-16 Thread Eduardo Vieira
On Thu, Sep 16, 2010 at 1:16 AM, Evert Rol  wrote:

> The latter: they are not the same:
>
 d = {'key': 'food'}
 d['key'] == 'foo'
> False
 'foo' in d['key']
> True
>
>
> Btw, generally don't use a reserved Python word for a variable, such as dict 
> in this case (I know it's an example, but it's still unsafe practice).
>
If you want to find out if 'foo' is a key, you can do: 'foo' in d,
which will return False. I'm not sure, but if I recall this can even
be faster than using the if.

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


[Tutor] robots question

2010-09-16 Thread Roelof Wobben

Hello, 

As a exercise from this book ( Thinking like a computer scientist ) I have to 
make this programm on this 
page(http://openbookproject.net/thinkcs/python/english2e/ch12.html)
Exercise 11 

#
# robots.py
#
from gasp import *

SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
GRID_WIDTH = SCREEN_WIDTH/10 - 1
GRID_HEIGHT = SCREEN_HEIGHT/10 - 1


def place_player():
# x = random.randint(0, GRID_WIDTH)
# y = random.randint(0, GRID_HEIGHT)
x, y = GRID_WIDTH/2 + 3, GRID_HEIGHT/2
return {'shape': Circle((10*x+5, 10*y+5), 5, filled=True), 'x': x, 'y': y}

def place_robot(x,y, junk):
x = random.randint(0, GRID_WIDTH)
y = random.randint(0, GRID_HEIGHT)
return {'shape': Box((10*x, 10*y), 10, 10), 'x': x, 'y': y}


def place_robots(numbots):
robots = []
# for i in range(numbots):
#x = random.randint(0, GRID_WIDTH)
#y = random.randint(0, GRID_HEIGHT)
#robots.append(place_robot(x, y))
robots.append(place_robot(GRID_WIDTH/2 - 4, GRID_HEIGHT/2 + 2, junk= False))
robots.append(place_robot(GRID_WIDTH/2 - 4, GRID_HEIGHT/2 - 2, junk = 
False))
return robots

def move_player(player):
update_when('key_pressed')
if key_pressed('escape'):
return True
elif key_pressed('4'):
if player['x'] > 0: player['x'] -= 1
elif key_pressed('7'):
if player['x'] > 0: player['x'] -= 1
if player['y'] < GRID_HEIGHT: player['y'] += 1
elif key_pressed('8'):
if player['y'] < GRID_HEIGHT: player['y'] += 1
elif key_pressed('9'):
if player['x'] < GRID_WIDTH: player['x'] += 1
if player['y'] < GRID_HEIGHT: player['y'] += 1
elif key_pressed('6'):
if player['x'] < GRID_WIDTH: player['x'] += 1
elif key_pressed('3'):
if player['x'] < GRID_WIDTH: player['x'] += 1
if player['y'] > 0: player['y'] -= 1
elif key_pressed('2'):
if player['y'] > 0: player['y'] -= 1
elif key_pressed('1'):
if player['x'] > 0: player['x'] -= 1
if player['y'] > 0: player['y'] -= 1
elif key_pressed('0'):
   player['x'] = random.randint(0, GRID_WIDTH)
   player['y'] = random.randint(0, GRID_HEIGHT)
else:
return False

move_to(player['shape'], (10*player['x']+5, 10*player['y']+5))

return False

def collided(thing1, thing2):
return thing1['x'] == thing2['x'] and thing1['y'] == thing2['y']

def check_collisions(robots, junk, player):
# check whether player has collided with anything
for thing in robots + junk:
if collided(thing, player):
return True
return False



def move_robot(robot, player):
if robot['x'] < player['x']: robot['x'] += 1
elif robot['x'] > player['x']: robot['x'] -= 1

if robot['y'] < player['y']: robot['y'] += 1
elif robot['y'] > player['y']: robot['y'] -= 1

move_to(robot['shape'], (10*robot['x'], 10*robot['y']))

def move_robots(robots, player):
for robot in robots:
move_robot(robot, player)


def play_game(robots):
begin_graphics(SCREEN_WIDTH, SCREEN_HEIGHT)
player = place_player()
robot = place_robots(4)
junk = [place_robot(GRID_WIDTH/2, GRID_HEIGHT/2, junk="true" )]
defeated = False

while not defeated:
quit =  move_player(player)
if quit:
break
move_robots(robot, player)
defeated = check_collisions(robot, player, junk)

if defeated:
remove_from_screen(player['shape'])
for thing in robots + junk:
remove_from_screen(thing['shape'])
Text("They got you!", (240, 240), size=32)
sleep(3)

end_graphics()



if __name__ == '__main__':
play_game(2)

But now Im getting this error message :

Traceback (most recent call last):
  File "/root/workspace/test2/src/test.py", line 120, in 
play_game(2)
  File "/root/workspace/test2/src/test.py", line 106, in play_game
defeated = check_collisions(robot, player, junk)
  File "/root/workspace/test2/src/test.py", line 73, in check_collisions
for thing in robots + junk:
TypeError: can only concatenate list (not "dict") to list

I understand that robots is a dict and junk is a list.

Is that right ?

And why does the book say that when this message is appearing. 

Roelof


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


Re: [Tutor] working with empty lists

2010-09-16 Thread Rance Hall
On Thu, Sep 16, 2010 at 9:24 AM, Joel Goldstick
 wrote:
> I typed in this:
>
>
>   3 l = []
>   4
>   5 for i in range(0,10):
>   6 l.append(i+1)
>   7
>   8 for i in range(0,10):
>   9 print ('%s. %s' % (i, l[i]))
>  10
>  11 def paginate_stuff(list, start):
>  12 pagesize = 2
>  13 for i in list[start:start+pagesize]:
>  14 print ('%s. %s' % (i,list[i]))
>  15 return
>  16
>  17 paginate_stuff(l,0)
>
> and i get this:
> 0. 1
> 1. 2
> 2. 3
> 3. 4
> 4. 5
> 5. 6
> 6. 7
> 7. 8
> 8. 9
> 9. 10
> 1. 2
> 2. 3
>
>
> What are you expecting?
>
>

you are getting what I am getting, so good news there, its not my code
(its my understanding instead)

In the above output where the you go from 9. 10 and the next item is 1. 2

I'm expecting the next item to be 0. 1 again.

It appears as if the for loop iterator is iterating BEFORE it executes
stuff as opposed to after like I'm used to.

if I change the print line inside the for loop to:

print('%s. %s) % (i-1,list[i-1]))

I get what I think I should have gotten orginally

Is this the correct understanding, is the for loop iterator iterating
before any of the stuff executes the first time?  This seems odd to me
somehow.

I appear to have fixed it, now I just wish I understood it.

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


Re: [Tutor] robots question

2010-09-16 Thread Evert Rol
> As a exercise from this book ( Thinking like a computer scientist ) I have to 
> make this programm on this 
> page(http://openbookproject.net/thinkcs/python/english2e/ch12.html)
> Exercise 11 
> 
> #
> # robots.py
> #
> from gasp import *

Argh!
Is that really in the book? 
Bad book, bad.

You can just "import gasp" and type "gasp." a few times.

Lot of code


> def play_game(robots):
> begin_graphics(SCREEN_WIDTH, SCREEN_HEIGHT)
> player = place_player()
> robot = place_robots(4)
> junk = [place_robot(GRID_WIDTH/2, GRID_HEIGHT/2, junk="true" )]
> defeated = False
> 
> while not defeated:
> quit =  move_player(player)
> if quit:
> break
> move_robots(robot, player)
> defeated = check_collisions(robot, player, junk)
> 
> if defeated:
> remove_from_screen(player['shape'])
> for thing in robots + junk:
> remove_from_screen(thing['shape'])
> Text("They got you!", (240, 240), size=32)
> sleep(3)
> 
> end_graphics()
> 
> 
> 
> if __name__ == '__main__':
> play_game(2)
> 
> But now Im getting this error message :
> 
> Traceback (most recent call last):
>   File "/root/workspace/test2/src/test.py", line 120, in 
> play_game(2)
>   File "/root/workspace/test2/src/test.py", line 106, in play_game
> defeated = check_collisions(robot, player, junk)
>   File "/root/workspace/test2/src/test.py", line 73, in check_collisions
> for thing in robots + junk:
> TypeError: can only concatenate list (not "dict") to list
> 
> I understand that robots is a dict and junk is a list.
> 
> Is that right ?

I think robots is not even a dict, but I may be wrong here.
Check your variable *names* inside play_game, and your use of '2' and '4'. 
Aren't you mixing up 'robot' and 'robots'?
Have you tried putting print statements inside the code? Also 'print 
type()' can be variable.
Try more debugging when you get an exception.


> And why does the book say that when this message is appearing. 

A quick glance at those webpages doesn't show any place where the book gives 
this code. This seems to be code you added.


  Evert

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


Re: [Tutor] robots question

2010-09-16 Thread Peter Otten
Roelof Wobben wrote:

> As a exercise from this book ( Thinking like a computer scientist ) I have
> to make this programm on this
> page(http://openbookproject.net/thinkcs/python/english2e/ch12.html)
> Exercise 11

> def check_collisions(robots, junk, player):

> defeated = check_collisions(robot, player, junk)

Just look at the argument names: check_collisions() is probably expecting a 
/list/ of robots where you are passing it a single one.

> But now Im getting this error message :
> 
> Traceback (most recent call last):
>   File "/root/workspace/test2/src/test.py", line 120, in 
> play_game(2)
>   File "/root/workspace/test2/src/test.py", line 106, in play_game
> defeated = check_collisions(robot, player, junk)
>   File "/root/workspace/test2/src/test.py", line 73, in check_collisions
> for thing in robots + junk:
> TypeError: can only concatenate list (not "dict") to list
> 
> I understand that robots is a dict and junk is a list.
> 
> Is that right ?

Yes. You are getting a dict because a single robot's state is stored in a 
dictionary.

> And why does the book say that when this message is appearing.

The way the program is presented makes it hard to tell at what point your 
and Eckel's idea of the script start to differ without going through the 
entire chapter.

Aside: that's why real projects use version control systems. When a program 
stops working after a change there is always the option to go back to the 
state of the program before the bug was introduced.

Peter

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


Re: [Tutor] working with empty lists

2010-09-16 Thread Joel Goldstick
On Thu, Sep 16, 2010 at 11:46 AM, Rance Hall  wrote:

> On Thu, Sep 16, 2010 at 9:24 AM, Joel Goldstick
>  wrote:
> > I typed in this:
> >
> >
> >   3 l = []
> >   4
> >   5 for i in range(0,10):
> >   6 l.append(i+1)
> >   7
> >   8 for i in range(0,10):
> >   9 print ('%s. %s' % (i, l[i]))
> >  10
> >  11 def paginate_stuff(list, start):
> >  12 pagesize = 2
> >  13 for i in list[start:start+pagesize]:
> >  14 print ('%s. %s' % (i,list[i]))
> >  15 return
> >  16
> >  17 paginate_stuff(l,0)
> >
> > and i get this:
> > 0. 1
> > 1. 2
> > 2. 3
> > 3. 4
> > 4. 5
> > 5. 6
> > 6. 7
> > 7. 8
> > 8. 9
> > 9. 10
> > 1. 2
> > 2. 3
> >
> >
> > What are you expecting?
> >
> >
>
> you are getting what I am getting, so good news there, its not my code
> (its my understanding instead)
>
> In the above output where the you go from 9. 10 and the next item is 1. 2
>
> I'm expecting the next item to be 0. 1 again.
>
> It appears as if the for loop iterator is iterating BEFORE it executes
> stuff as opposed to after like I'm used to.
>
> if I change the print line inside the for loop to:
>
> print('%s. %s) % (i-1,list[i-1]))
>
> I get what I think I should have gotten orginally
>
> Is this the correct understanding, is the for loop iterator iterating
> before any of the stuff executes the first time?  This seems odd to me
> somehow.
>
> I appear to have fixed it, now I just wish I understood it.
>
> R
>

This line is illustrative:

>  13 for i in list[start:start+pagesize]:

start is 0, pagesize is 2 so we get list[0:2] which means i gets the value
of what is in list[0], then next time list[1] then it stops

list[0] IS 1, list[1] is 2

so: >  14 print ('%s. %s' % (i,list[i]))

will print 1. list[1] which is 2

then print 2. list[2] which is 3

maybe what you want is this:
  for i, value enumerate(list[start:start+pagesize], start):
  print i, value


___
> 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] working with empty lists

2010-09-16 Thread Rance Hall
On Thu, Sep 16, 2010 at 11:21 AM, Joel Goldstick
 wrote:
>
>
> On Thu, Sep 16, 2010 at 11:46 AM, Rance Hall  wrote:
>>
>> On Thu, Sep 16, 2010 at 9:24 AM, Joel Goldstick
>>  wrote:



> This line is illustrative:
>
>>  13 for i in list[start:start+pagesize]:
>
> start is 0, pagesize is 2 so we get list[0:2] which means i gets the value
> of what is in list[0], then next time list[1] then it stops
>
> list[0] IS 1, list[1] is 2
>
> so: >  14 print ('%s. %s' % (i,list[i]))
>
> will print 1. list[1] which is 2
>
> then print 2. list[2] which is 3
>
> maybe what you want is this:
>   for i, value enumerate(list[start:start+pagesize], start):
>       print i, value
>

For some reason I wasn't seeing that I was iterating over the list
contents not the list indexes, and because in my sample data both were
numbers it worked but not how I wanted it too,

Damn that dyslexia, oh well.  Thanks for helping me through it.

By the way, this also works as I expect:

for i in range(start, start+pagesize):

also gives me what I want to see.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] FW: robots question

2010-09-16 Thread Roelof Wobben



From: rwob...@hotmail.com
To: __pete...@web.de
Subject: RE: [Tutor] robots question
Date: Thu, 16 Sep 2010 17:43:41 +








Hello , 

I change everything to this :

#
# robots.py
#
from gasp import *

SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
GRID_WIDTH = SCREEN_WIDTH/10 - 1
GRID_HEIGHT = SCREEN_HEIGHT/10 - 1


def place_player():
# x = random.randint(0, GRID_WIDTH)
# y = random.randint(0, GRID_HEIGHT)
x, y = GRID_WIDTH/2 + 3, GRID_HEIGHT/2
return {'shape': Circle((10*x+5, 10*y+5), 5, filled=True), 'x': x, 'y': y}

def place_robot(x,y, junk):
x = random.randint(0, GRID_WIDTH)
y = random.randint(0, GRID_HEIGHT)
return {'shape': Box((10*x, 10*y), 10, 10), 'x': x, 'y': y}


def place_robots(numbots):
robots = []
# for i in range(numbots):
#x = random.randint(0, GRID_WIDTH)
#y = random.randint(0, GRID_HEIGHT)
#robots.append(place_robot(x, y))
robots.append(place_robot(GRID_WIDTH/2 - 4, GRID_HEIGHT/2 + 2, junk= False))
robots.append(place_robot(GRID_WIDTH/2 - 4, GRID_HEIGHT/2 - 2, junk = 
False))
print type(robots)
return robots

def move_player(player):
update_when('key_pressed')
if key_pressed('escape'):
return True
elif key_pressed('4'):
if player['x'] > 0: player['x'] -= 1
elif key_pressed('7'):
if player['x'] > 0: player['x'] -= 1
if player['y'] < GRID_HEIGHT: player['y'] += 1
elif key_pressed('8'):
if player['y'] < GRID_HEIGHT: player['y'] += 1
elif key_pressed('9'):
if player['x'] < GRID_WIDTH: player['x'] += 1
if player['y'] < GRID_HEIGHT: player['y'] += 1
elif key_pressed('6'):
if player['x'] < GRID_WIDTH: player['x'] += 1
elif key_pressed('3'):
if player['x'] < GRID_WIDTH: player['x'] += 1
if player['y'] > 0: player['y'] -= 1
elif key_pressed('2'):
if player['y'] > 0: player['y'] -= 1
elif key_pressed('1'):
if player['x'] > 0: player['x'] -= 1
if player['y'] > 0: player['y'] -= 1
elif key_pressed('0'):
   player['x'] = random.randint(0, GRID_WIDTH)
   player['y'] = random.randint(0, GRID_HEIGHT)
else:
return False

move_to(player['shape'], (10*player['x']+5, 10*player['y']+5))

return False

def collided(thing1, thing2):
return thing1['x'] == thing2['x'] and thing1['y'] == thing2['y']

def check_collisions(robots, junk, player):
# check whether player has collided with anything
for thing in robots + junk:
if collided(thing, player):
return True
return False



def move_robot(robot, player):
if robot['x'] < player['x']: robot['x'] += 1
elif robot['x'] > player['x']: robot['x'] -= 1

if robot['y'] < player['y']: robot['y'] += 1
elif robot['y'] > player['y']: robot['y'] -= 1

move_to(robot['shape'], (10*robot['x'], 10*robot['y']))

def move_robots(robots, player):
for robot in robots:
move_robot(robot, player)


def play_game():
begin_graphics(SCREEN_WIDTH, SCREEN_HEIGHT)
player = place_player()
robot = place_robots(4)
junk = [ place_robot(GRID_WIDTH/2, GRID_HEIGHT/2, junk="true" )]
robots = []
defeated = False

while not defeated:
quit =  move_player(player)
if quit:
break
move_robots(robots, player)
print "type robots", type(robots)
print "type junk", type(junk)
print "type player", type(player)
defeated = check_collisions(robots, player, junk)

if defeated:
remove_from_screen(player['shape'])
for thing in robots + junk:
remove_from_screen(thing['shape'])
Text("They got you!", (240, 240), size=32)
sleep(3)

end_graphics()



if __name__ == '__main__':
play_game()


And now Im getting this message :

** Message: pygobject_register_sinkfunc is deprecated (GtkWindow)
** Message: pygobject_register_sinkfunc is deprecated (GtkInvisible)
** Message: pygobject_register_sinkfunc is deprecated (GtkObject)

type robotsTraceback (most recent call last):
 
type junk 
type player 
  File "/root/workspace/test2/src/test.py", line 125, in 
play_game()
  File "/root/workspace/test2/src/test.py", line 111, in play_game
defeated = check_collisions(robots, player, junk)
  File "/root/workspace/test2/src/test.py", line 74, in check_collisions
for thing in robots + junk:
TypeError: can only concatenate list (not "dict") to list

So far I can see the problem is that player is a dict and the rest is a list.

Is this the correct conclusion ?

Roelof


> To: tutor@python.org
> From: __pete...@web.de
> Date: Thu, 16 Sep 2010 18:10:13 +0200
> Subject: Re: [Tutor] robots question
> 
> Roelof Wobben wrote:
> 
> > As a exercise from this book ( Thinking like a computer scientist ) I have
> > to make this programm on this
> > page(http://openbookproject.net/thinkcs/python/english2e/ch12.html)
> > Exercise 11
> 
> > def check_collisions(robots, junk, pl

Re: [Tutor] intercepting and recored I/O function calls

2010-09-16 Thread Alan Gauld


"Jojo Mwebaze"  wrote


I am using centos, however i don't even have admin privileges. 
Which API

are you referring to?


The OS API - Win32 in Windows or the Unix standard library etc

Alan G 



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


Re: [Tutor] FW: robots question

2010-09-16 Thread Peter Otten
Roelof Wobben wrote:

> I change everything to this :

> def check_collisions(robots, junk, player):

> defeated = check_collisions(robots, player, junk)

Do you see the problem?

> print "type robots", type(robots)
> print "type junk", type(junk)
> print "type player", type(player)

Adding print statements for debugging purposes is a good approach.

> And now Im getting this message :
> 
> ** Message: pygobject_register_sinkfunc is deprecated (GtkWindow)
> ** Message: pygobject_register_sinkfunc is deprecated (GtkInvisible)
> ** Message: pygobject_register_sinkfunc is deprecated (GtkObject)
> 
> type robotsTraceback (most recent call last):
>  
> type junk 
> type player 
>   File "/root/workspace/test2/src/test.py", line 125, in 
> play_game()
>   File "/root/workspace/test2/src/test.py", line 111, in play_game
> defeated = check_collisions(robots, player, junk)
>   File "/root/workspace/test2/src/test.py", line 74, in check_collisions
> for thing in robots + junk:
> TypeError: can only concatenate list (not "dict") to list
> 
> So far I can see the problem is that player is a dict and the rest is a
> list.
> Is this the correct conclusion ?

It may be correct but it's a low-level view. A more appropriate description 
would be that you are trying to concatenate a list of robots with a player.

Peter

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


[Tutor] FW: FW: robots question

2010-09-16 Thread Roelof Wobben




> From: rwob...@hotmail.com
> To: __pete...@web.de
> Subject: RE: [Tutor] FW: robots question
> Date: Thu, 16 Sep 2010 18:22:03 +
>
>
>
>
> 
>> To: tutor@python.org
>> From: __pete...@web.de
>> Date: Thu, 16 Sep 2010 20:10:02 +0200
>> Subject: Re: [Tutor] FW: robots question
>>
>> Roelof Wobben wrote:
>>
>>> I change everything to this :
>>
>>> def check_collisions(robots, junk, player):
>>
>>> defeated = check_collisions(robots, player, junk)
>>
>> Do you see the problem?
>
>

yes, Player en junk are swapped.

>
>
>>
>>> print "type robots", type(robots)
>>> print "type junk", type(junk)
>>> print "type player", type(player)
>>
>> Adding print statements for debugging purposes is a good approach.
>>
>>> And now Im getting this message :
>>>
>>> ** Message: pygobject_register_sinkfunc is deprecated (GtkWindow)
>>> ** Message: pygobject_register_sinkfunc is deprecated (GtkInvisible)
>>> ** Message: pygobject_register_sinkfunc is deprecated (GtkObject)
>>>
>>> type robotsTraceback (most recent call last):
>>>
>>> type junk
>>> type player
>>> File "/root/workspace/test2/src/test.py", line 125, in
>>> play_game()
>>> File "/root/workspace/test2/src/test.py", line 111, in play_game
>>> defeated = check_collisions(robots, player, junk)
>>> File "/root/workspace/test2/src/test.py", line 74, in check_collisions
>>> for thing in robots + junk:
>>> TypeError: can only concatenate list (not "dict") to list
>>>
>>> So far I can see the problem is that player is a dict and the rest is a
>>> list.
>>> Is this the correct conclusion ?
>>
>> It may be correct but it's a low-level view. A more appropriate description
>> would be that you are trying to concatenate a list of robots with a player.
>

Oke,

 I will try to make one list which will contain the robots and a player.
 
 

>>
>> Peter
>>
>> ___
>> 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


[Tutor] Comparing two lists

2010-09-16 Thread Michael Powe
Hello,

I have two lists.

alist = ['label', 'guid']

blist = ['column0label', 'column1label', 'dimension0guid',
'description', 'columnid'] 

I want to iterate over blist and extract the items that match my
substrings in alist; alternatively, throw out the items that aren't in
alist (but, I've had bad experiences removing items from lists "in
place," so I tend toward the "copy" motif.)

In real life, blist column entries could have embedded column numbers
from 0 to 19.

I can do this with excrutiatingly painful 'for' loops.  Looking for
something more efficient and elegant.  

Thanks.

mp

-- 
Michael Powemich...@trollope.orgNaugatuck CT USA

"The secret to strong security: less reliance on secrets."
-- Whitfield Diffie


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


Re: [Tutor] Comparing two lists

2010-09-16 Thread Vince Spicer
On Thu, Sep 16, 2010 at 12:27 PM, Michael Powe  wrote:

> Hello,
>
> I have two lists.
>
> alist = ['label', 'guid']
>
> blist = ['column0label', 'column1label', 'dimension0guid',
> 'description', 'columnid']
>
> I want to iterate over blist and extract the items that match my
> substrings in alist; alternatively, throw out the items that aren't in
> alist (but, I've had bad experiences removing items from lists "in
> place," so I tend toward the "copy" motif.)
>
> In real life, blist column entries could have embedded column numbers
> from 0 to 19.
>
> I can do this with excrutiatingly painful 'for' loops.  Looking for
> something more efficient and elegant.
>
> Thanks.
>
> mp
>
> --
> Michael Powemich...@trollope.orgNaugatuck CT USA
>
> "The secret to strong security: less reliance on secrets."
> -- Whitfield Diffie
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
Michel,

One solution is to use list comprehensions.

newlist = [x for x in blist if [a for a in alist if a in x]]

This works, although there may be more efficient ways to accomplish this

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


Re: [Tutor] Comparing two lists

2010-09-16 Thread Vince Spicer
On Thu, Sep 16, 2010 at 12:49 PM, Vince Spicer  wrote:

>
>
> On Thu, Sep 16, 2010 at 12:27 PM, Michael Powe wrote:
>
>> Hello,
>>
>> I have two lists.
>>
>> alist = ['label', 'guid']
>>
>> blist = ['column0label', 'column1label', 'dimension0guid',
>> 'description', 'columnid']
>>
>> I want to iterate over blist and extract the items that match my
>> substrings in alist; alternatively, throw out the items that aren't in
>> alist (but, I've had bad experiences removing items from lists "in
>> place," so I tend toward the "copy" motif.)
>>
>> In real life, blist column entries could have embedded column numbers
>> from 0 to 19.
>>
>> I can do this with excrutiatingly painful 'for' loops.  Looking for
>> something more efficient and elegant.
>>
>> Thanks.
>>
>> mp
>>
>> --
>> Michael Powemich...@trollope.orgNaugatuck CT USA
>>
>> "The secret to strong security: less reliance on secrets."
>> -- Whitfield Diffie
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
> Michel,
>
> One solution is to use list comprehensions.
>
> newlist = [x for x in blist if [a for a in alist if a in x]]
>
> This works, although there may be more efficient ways to accomplish this
>
> Vince
>
>
On major speed up is to make a simple filter that returns as soon as a match
is found instead of
completing the loop every element in alist

def filter_(x, against):
for a in against:
if a in x:
return True
return False

newlist = [x for x in blist if filter_(x, alist)]

:)

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


Re: [Tutor] Comparing two lists

2010-09-16 Thread Michael Powe
On Thu, Sep 16, 2010 at 12:59:08PM -0600, Vince Spicer wrote:
> On Thu, Sep 16, 2010 at 12:49 PM, Vince Spicer  wrote:

> > On Thu, Sep 16, 2010 at 12:27 PM, Michael Powe wrote:

> >> alist = ['label', 'guid']

> >> blist = ['column0label', 'column1label', 'dimension0guid',
> >> 'description', 'columnid']
> >>
> >> I want to iterate over blist and extract the items that match my
> >> substrings in alist; alternatively, throw out the items that aren't in
> >> alist (but, I've had bad experiences removing items from lists "in
> >> place," so I tend toward the "copy" motif.)

> > One solution is to use list comprehensions.

> > newlist = [x for x in blist if [a for a in alist if a in x]]

> > This works, although there may be more efficient ways to accomplish this

> On major speed up is to make a simple filter that returns as soon as a match
> is found instead of
> completing the loop every element in alist
 
> def filter_(x, against):
> for a in against:
> if a in x:
> return True
> return False
> 
> newlist = [x for x in blist if filter_(x, alist)]

Hello,

Very cool, thanks.

I've used list comprehensions before but I just couldn't get the
structure right this time, for some reason.

Thanks.

mp

-- 
Michael Powemich...@trollope.orgNaugatuck CT USA
"No provision in our Constitution ought to be dearer to man than that
which protects the rights of conscience against the enterprises of the
civil authority." -- Thomas Jefferson to New London Methodists,
1809. ME 16:332


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


Re: [Tutor] Comparing two lists

2010-09-16 Thread Emile van Sebille

On 9/16/2010 11:27 AM Michael Powe said...

Hello,

I have two lists.

alist = ['label', 'guid']

blist = ['column0label', 'column1label', 'dimension0guid',
'description', 'columnid']



Something like this?

>>> [ ii for jj in alist for ii in blist if jj in ii ]
['column0label', 'column1label', 'dimension0guid']

Emile

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


Re: [Tutor] Comparing two lists

2010-09-16 Thread Michael Powe
On Thu, Sep 16, 2010 at 12:59:08PM -0600, Vince Spicer wrote:
> On Thu, Sep 16, 2010 at 12:49 PM, Vince Spicer  wrote:

> > On Thu, Sep 16, 2010 at 12:27 PM, Michael Powe wrote:

> >> I have two lists.

> >> alist = ['label', 'guid']
> >>
> >> blist = ['column0label', 'column1label', 'dimension0guid',
> >> 'description', 'columnid']

> >> I want to iterate over blist and extract the items that match my
> >> substrings in alist; alternatively, throw out the items that aren't in
> >> alist (but, I've had bad experiences removing items from lists "in
> >> place," so I tend toward the "copy" motif.)

> On major speed up is to make a simple filter that returns as soon as
> a match is found instead of completing the loop every element in
> alist

> def filter_(x, against):
> for a in against:
> if a in x:
> return True
> return False

Hello,

Totally awesome.  I actually have a dictionary, with the key being an
ini file header and the value being one of these lists of ini
settings.  With your method, I am able to loop through the dictionary,
and expunge the unwanted settings.

I knew there had to be a way to take advantage of the fact that the 'i
in s' object test acts like a substring test for strings.  

Thanks.

mp

-- 
Michael Powemich...@trollope.orgNaugatuck CT USA

'Unless we approve your idea, it will not be permitted, it will not be
allowed.'  -- Hilary Rosen, President, RIAA


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


Re: [Tutor] Function behavior

2010-09-16 Thread Alan Gauld


"Ken Green"  wrote


I am unclear on the behavior of using a function.


You certainly are!
Which tutorial are you working from?
You have several fundamental errors here, its hard to know
where to start.


def change(amount):
if match == 1:
amount = 0
if match == 2:
amount = 0
if match == 3:
amount = 3


This function is called change and it has an input parameter called 
amount.
The parameter is like a local variable only visible inside the 
function.

Because there are no return statements in it it will always return the
default value of None - probably not what you want.

Inside the function you compare a variable called match - which is not
defined in the function so presumably will be found outside in the 
module

or global scope - to a number.
You then set the parameter amount to another number, one greater
than the test value. But since amount is the parameter and invisible
outside the function that will have no affect on anything outside the
function.


match = raw_input("How many matches?: ")


Now we define the global variable match but set it to a string.
The change() function is expecting match to be a number.
Maybe we should convert it using int()?


change(match)



This does nothing and since we don't assign the functions value
to anything the None that it returns is lost.


print amount


amount is not defined anywhere at the global scope and
the amount parameter in the function is not visible outside
the function.


How many matches?: 2
Traceback (most recent call last):
  File "/home/ken/Python262/TEST Function.py", line 13, in 
print amount
NameError: name 'amount' is not defined



Should it be def change(match) instead of def change(amount)?
Perhaps, change(amount) instead of change(match)?


You need to go back to basics on how parameters and arguments
work (This is, I admit, a subtle concept when you first come across 
it)



Perhaps, I need to add return somewhere?


Yes you probably do. You can do what you want without it but
its considered bad practice. Functions should reurn their results.

Try reading the functions and modules topic in my tutorial
to see if that helps.

--
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] constructing objects with one set of required options

2010-09-16 Thread Gregory, Matthew
Sorry for what is probably a poor subject line ...

Generally, I'm trying to understand the best way to set up an object's __init__ 
if there are some required parameters and other parameters that can be 
specified in a number of ways.  As an example, I'm working on an envelope class 
that describes a spatial envelope complete with cell size information.  
Assuming that this envelope needs to have its upper left corner specified and a 
cell size, I can *either* specify a lower right corner or the number of rows 
and columns to finish the specification.  Can folks provide guidance on a good 
way to do this?  Specifically, I'm wondering if some or all options should be 
by position or by keyword.

Here's my first cut of doing it all by keyword.

class EnvelopeException(Exception):
pass

class Envelope(object):
def __init__(self, **kwargs):
try:
self.x_min = kwargs['x_min']
self.y_max = kwargs['y_max']
self.cell_size = kwargs['cell_size']
except KeyError:
err_str = 'Not all required parameters were specified'
raise EnvelopeException(err_str)

try:
# First try n_cols and n_rows as keyword args
self.n_cols = kwargs['n_cols']
self.n_rows = kwargs['n_rows']
except KeyError:
try:
# Try x_max and y_min instead
self.x_max = kwargs['x_max']
self.y_min = kwargs['y_min']
except KeyError:
err_str  = 'Either the number of rows and columns or '
err_str += 'the lower-right coordinate was not specified.'
raise EnvelopeException(err_str)

# calculate the remaining parts of the specification
...

(I realize that I could also specify the x_max and the n_rows or y_min and 
n_cols and still derive the envelope, but that seemed nonintuitive to me, 
although maybe I should consider it.)

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


Re: [Tutor] constructing objects with one set of required options

2010-09-16 Thread James Mills
On Fri, Sep 17, 2010 at 7:43 AM, Gregory, Matthew
 wrote:
> Sorry for what is probably a poor subject line ...
>
> Generally, I'm trying to understand the best way to set up an object's 
> __init__ if there are some required parameters and other parameters that can 
> be specified in a number of ways.  As an example, I'm working on an envelope 
> class that describes a spatial envelope complete with cell size information.  
> Assuming that this envelope needs to have its upper left corner specified and 
> a cell size, I can *either* specify a lower right corner or the number of 
> rows and columns to finish the specification.  Can folks provide guidance on 
> a good way to do this?  Specifically, I'm wondering if some or all options 
> should be by position or by keyword.
>
> Here's my first cut of doing it all by keyword.
>
> class EnvelopeException(Exception):
>    pass
>
> class Envelope(object):
>    def __init__(self, **kwargs):
>        try:
>            self.x_min = kwargs['x_min']
>            self.y_max = kwargs['y_max']
>            self.cell_size = kwargs['cell_size']
>        except KeyError:
>            err_str = 'Not all required parameters were specified'
>            raise EnvelopeException(err_str)
>
>        try:
>            # First try n_cols and n_rows as keyword args
>            self.n_cols = kwargs['n_cols']
>            self.n_rows = kwargs['n_rows']
>        except KeyError:
>            try:
>                # Try x_max and y_min instead
>                self.x_max = kwargs['x_max']
>                self.y_min = kwargs['y_min']
>            except KeyError:
>                err_str  = 'Either the number of rows and columns or '
>                err_str += 'the lower-right coordinate was not specified.'
>                raise EnvelopeException(err_str)
>
>        # calculate the remaining parts of the specification
>        ...
>
> (I realize that I could also specify the x_max and the n_rows or y_min and 
> n_cols and still derive the envelope, but that seemed nonintuitive to me, 
> although maybe I should consider it.)

Rather than present you with what I think (subjective)
might be a "good solution", why don't you look up in the
python documentation how you define methods and
what you can do with them (parameters-wise).

I'll summarize:

def foo(self, a, b, c):
   ...
def foor(self, a, b, *args):
   ...
def foo(self, a, b, c=None):
   ...
def foo(self, a, b, *args, **kwargs):
   ...

There are probably other combinations, but these are
probably the most common.

The point I'm trying to make here is that this is
really "up to you".

Use a combination of variable arguments (*args)
and maybe some arguments with default values
(c=None) or just use **kwargs. Choice is yours :)

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] constructing objects with one set of required options

2010-09-16 Thread Gregory, Matthew
Hi James,

James Mills wrote:
> Rather than present you with what I think (subjective)
> might be a "good solution", why don't you look up in the
> python documentation how you define methods and
> what you can do with them (parameters-wise).
> 
> I'll summarize:
> 
> def foo(self, a, b, c):
>...
> def foor(self, a, b, *args):
>...
> def foo(self, a, b, c=None):
>...
> def foo(self, a, b, *args, **kwargs):
>...
> 
> There are probably other combinations, but these are
> probably the most common.
> 
> The point I'm trying to make here is that this is
> really "up to you".
> 
> Use a combination of variable arguments (*args)
> and maybe some arguments with default values
> (c=None) or just use **kwargs. Choice is yours :)

Thanks for your reply.  I do understand all the different ways parameters can 
be passed and realize that it's up to me to choose that signature.  But, 
mostly, I wanted advice on how to make this signature as intuitive as possible 
to a user.  So, from my earlier example, a signature with positional args like 
this is a bad idea:

class Envelope:
def __init__(x_min, y_max, cell_size, *args):
...

# are args 3 and 4 rows and columns or x_max, y_min?
e = Envelope(10, 20, 1, 30, 10)

so I know at least the last two args should probably be keywords, but a 
signature like this is somewhat confusing to me as well because it's not 
immediately clear to me what the first three parameters are by looking at the 
*call* (obviously by looking at the method you can figure it out).

   def __init__(x_min, y_max, cell_size, **kwargs):
   e = Envelope(10, 20, 1, n_cols=30, n_rows=10)
   e = Envelope(10, 20, 1, x_max=30, y_min=10)

So I know I'm getting around to answering my own question, but the clearest way 
to me was to provide all keyword args.  I just didn't know if this was too 
verbose from a user's standpoint.  Really just a stylistic question that might 
be best left to the individual.

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


Re: [Tutor] constructing objects with one set of required options

2010-09-16 Thread James Mills
On Fri, Sep 17, 2010 at 8:35 AM, Gregory, Matthew
 wrote:
> Thanks for your reply.  I do understand all the different ways parameters can 
> be passed and realize that it's up to me to choose that signature.  But, 
> mostly, I wanted advice on how to make this signature as intuitive as 
> possible to a user.  So, from my earlier example, a signature with positional 
> args like this is a bad idea:
>
>    class Envelope:
>        def __init__(x_min, y_max, cell_size, *args):
>            ...
>
>    # are args 3 and 4 rows and columns or x_max, y_min?
>    e = Envelope(10, 20, 1, 30, 10)

Don't forget "self".

This signature seems okay to me.

> so I know at least the last two args should probably be keywords, but a 
> signature like this is somewhat confusing to me as well because it's not 
> immediately clear to me what the first three parameters are by looking at the 
> *call* (obviously by looking at the method you can figure it out).
>
>   def __init__(x_min, y_max, cell_size, **kwargs):
>   e = Envelope(10, 20, 1, n_cols=30, n_rows=10)
>   e = Envelope(10, 20, 1, x_max=30, y_min=10)
>
> So I know I'm getting around to answering my own question, but the clearest 
> way to me was to provide all keyword args.  I just didn't know if this was 
> too verbose from a user's standpoint.  Really just a stylistic question that 
> might be best left to the individual.

In my experience, I've always defined explicit arguments and keyword arguments
for constructors and use **kwargs for anything that can be specified as optional
but have defaults. eg:

class Foo(object)
   def __init__(self, a, b, c, x=1, **kwargs):
  super(Foo, self).__init__()

  self.a = a
  self.b = b
  self.c = c

  self.x = x

  self.y = kwargs.get("y", None)

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] intercepting and recored I/O function calls

2010-09-16 Thread Martin A. Brown

[apologies in advance for an answer that is partially off topic]

Hi there JoJo,

 : I could begin with tracing I/O calls in my App.. if its 
 : sufficient enough i may not need i/o calls for the OS.

What do you suspect?  Filesystem I/O?

  * open(), close(), opendir() closedir() filesystem latency?
  * read(), write() latency?
  * low read() and write() throughput?

Network I/O?

  * Are name lookups taking a long time?
  * Do you have slow network throughput?  (Consider tcpdump.)

Rather than writing code (at first glance), why not use a system 
call profiler to check this out.  It is very unlikely that python 
itself is the problem.  Could it be the filesystem/network?  Could 
it be DNS?  A system call profiler can help you find this.

Are you asking this because you plan on diagnosing I/O performance 
issues in your application?  Is this a one time thing in a 
production environment that is sensitive to application latency?  
If so, you might try tickling the application and attaching to the 
process with a system call tracer.  Under CentOS you should be able 
to install 'strace'.  If you can run the proggie on the command 
line:

  strace -o /tmp/trace-output-file.txt -f python yourscript.py args

Then, go learn how to read the /tmp/trace-output-file.txt.

Suggested options:

  -ffollow children
  -ttt  sane Unix-y timestamps
  -Ttotal time spent in each system call
  -s 256256 byte limit on string output (default is 32)
  -o file   store trace data in a file
  -p pidattach to running process of pid
  -conly show a summary of cumulative time per system call

 : > But this is extremely dependant on the Operating System - you will
 : > basically have to intercept the system calls. So, which OS are 
 : > you using?  And how familiar are you with its API?
 : 
 : I am using centos, however i don't even have admin privileges.  
 : Which API are you referring to?

You shouldn't need admin privileges if you can run the program as 
yourself.  If you have setuid/setgid bits, then you will need 
somebody with administrative privileges to help you.

OK, so let's say that you have already done this and understand all 
of the above, you know it's not the system and you really want to 
understand where your application is susceptible to bad performance 
or I/O issues.  Now, we're back to python land.

  * look at the profile module
http://docs.python.org/library/profile.html

  * instrument your application by using the logging module
http://docs.python.org/library/logging.html

You might ask how it is a benefit to use the logging module.  Well, 
if your program generates logging data (let's say to STDERR) and you 
do not include timestamps on each log line, you can trivially add 
timestamps to the logging data using your system's logging 
facilities:

  { python thingy.py >/dev/null ; } 2>&1 | logger -ist 'thingy.py' --

Or, if you like DJB tools:

  { python thingy.py >/dev/null ; } 2>&1 | multilog t ./directory/

Either of which solution leaves you (implicitly) with timing 
information.

 : > Also, While you can probably do this in Python but its likely 
 : > to have a serious impact on the OS performance, it will slow 
 : > down the performamce quite noticeably. I'd normally recommend 
 : > using C for something like this.

Alan's admonition bears repeating.  Trapping all application I/O is 
probably just fine for development, instrumenting and diagnosing, 
but you may wish to support that in an easily removable manner, 
especially if performance is paramount.

Good luck,

-Martin

-- 
Martin A. Brown
http://linux-ip.net/
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] "Overloading" methods

2010-09-16 Thread Alan Gauld


On Thu, Sep 16, 2010 at 6:02 AM, Michael Powe  
wrote:


line structures, I had the thought to write methods with 
descriptive
names that simply returned a generic method that processed the 
method

arguments. e.g.,

def setpattern_iis(self,pattern,parameter) :
   type='iis'
   return pattern_generator(self,type,pattern,parameter)

In this case, creating a regular expression to parse the log lines 
for

a query parameter.


This doesn't really show that, it shows you calling a function and
returning its result, but we have no way of knowing what that is.

However the concept is sound and quite common in functional
programming where the function which returns another function
is referred to as a higher order function.


This is just a bit more "self documenting" than using the generic
method with the 'type' argument and requiring the user to enter the
type.  At the same time, it allows me to put all the parsing code 
in

one method.


Going by your example above it only saves one parameter - the
type - and I'm not sure that's so valuable. However without real code
its hard to judge. The concept is sound but like so many things
its possible to abuse it.

You can usually achieve similar ends with classes and/or dispatch
tables.

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] robots question

2010-09-16 Thread Alan Gauld


"Roelof Wobben"  wrote


#
# robots.py

This is pretty weird code, there are several odd things in it.

def place_player():
   # x = random.randint(0, GRID_WIDTH)
   # y = random.randint(0, GRID_HEIGHT)
   x, y = GRID_WIDTH/2 + 3, GRID_HEIGHT/2
   return {'shape': Circle((10*x+5, 10*y+5), 5, filled=True), 'x': x, 
'y': y}


So this returns a dictionary which always contains the same data.

def place_robot(x,y, junk):
   x = random.randint(0, GRID_WIDTH)
   y = random.randint(0, GRID_HEIGHT)
   return {'shape': Box((10*x, 10*y), 10, 10), 'x': x, 'y': y}

This returns a similar dict but with random data.
It ignores the values of x and y passed in and does not use junk at 
all.


def place_robots(numbots):
   robots = []
   # for i in range(numbots):
   #x = random.randint(0, GRID_WIDTH)
   #y = random.randint(0, GRID_HEIGHT)
   #robots.append(place_robot(x, y))
   robots.append(place_robot(GRID_WIDTH/2 - 4, GRID_HEIGHT/2 + 2, 
junk= False))
   robots.append(place_robot(GRID_WIDTH/2 - 4, GRID_HEIGHT/2 - 2, 
junk = False))

   print type(robots)
   return robots

This returns a list of 2 dictionaries. The x,y parameters are ignored 
by the function.



def move_player(player):
   update_when('key_pressed')
   if key_pressed('escape'):
   return True
   elif key_pressed('4'): ...
   else:
   return False
   move_to(player['shape'], (10*player['x']+5, 10*player['y']+5))
   return False

This seems OK, it returns True for escape otherwise False.

def collided(thing1, thing2):
   return thing1['x'] == thing2['x'] and thing1['y'] == thing2['y']

This returns a boolean


def check_collisions(robots, junk, player):
   # check whether player has collided with anything
   for thing in robots + junk:
   if collided(thing, player):
   return True
   return False

Could be simplified to just

for thing in robots + junk:
return collided(thing, player)

It requires that robots and junk are capable of being added together
and the result being iterable.

def move_robot(robot, player):
   if robot['x'] < player['x']: robot['x'] += 1
   elif robot['x'] > player['x']: robot['x'] -= 1

   if robot['y'] < player['y']: robot['y'] += 1
   elif robot['y'] > player['y']: robot['y'] -= 1

   move_to(robot['shape'], (10*robot['x'], 10*robot['y']))

I don't see move_to so assume its part of the module you imported?

def move_robots(robots, player):
   for robot in robots:
   move_robot(robot, player)

ok


def play_game():
   begin_graphics(SCREEN_WIDTH, SCREEN_HEIGHT)
   player = place_player()
   robot = place_robots(4)
   junk = [ place_robot(GRID_WIDTH/2, GRID_HEIGHT/2, junk="true" )]
   robots = []
   defeated = False

So at this point
player is a dict
robot is a list of 2 dicts
junk is a list of one dict
robots is an empty list


   while not defeated:
   quit =  move_player(player)
   if quit:
   break
   move_robots(robots, player)
   print "type robots", type(robots)
   print "type junk", type(junk)
   print "type player", type(player)
   defeated = check_collisions(robots, player, junk)

You now call check_collisions passing an empty list and a dict and a 
list of a dict

The order in the definition is:

def check_collisions(robots, junk, player):

so it looks like you swapped the last two arguments


And now Im getting this message :

** Message: pygobject_register_sinkfunc is deprecated (GtkWindow)
** Message: pygobject_register_sinkfunc is deprecated (GtkInvisible)
** Message: pygobject_register_sinkfunc is deprecated (GtkObject)


Not sure where that lot came from...

type robotsTraceback (most recent call last):

type junk 
type player 
 File "/root/workspace/test2/src/test.py", line 125, in 
   play_game()
 File "/root/workspace/test2/src/test.py", line 111, in play_game
   defeated = check_collisions(robots, player, junk)
 File "/root/workspace/test2/src/test.py", line 74, in 
check_collisions

   for thing in robots + junk:
TypeError: can only concatenate list (not "dict") to list

But this is valid because of the swapped arguments.

So far I can see the problem is that player is a dict and the rest 
is a list.

Is this the correct conclusion ?


Yes, but you missed the fact that you changed the order of the 
arguments.
When you get type errors check the types at your interfaces(functions, 
classes etc)

match the definitions.

--
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] How to get both 2.6 scripts as well as 3.1 scripts to run at command line?

2010-09-16 Thread Steven D'Aprano
On Thu, 16 Sep 2010 01:35:17 pm David Hutto wrote:
> print("a is", a)
> or
> from future import *

Neither of those lines are correct. Given (say) a=42, in Python 2.6 the 
first line will print the tuple:

("a is", 42)

while in Python 3.1 it will print the string:

a is 42

Note the extra punctuation in the first version. For a quick-and-dirty 
script, you might not care about that, so passing tuples to print in 
2.x is a reasonably simple work-around, but they are not the same.

On the other hand, the second line does behave the same in both Python 
2.6 and 3.1:

>>> from future import *
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named future

It might be the same, but I'm pretty sure it's not useful.

What you are thinking of is the special module __future__ with leading 
and trailing double-underscores. __future__ is special -- the line 

from __future__ import ...

(where ... is one or more feature) tells the Python compiler to change 
behaviour. If you use a "from __future__ import" line, it MUST be the 
first executable line in a module or script. It's okay for it to follow 
blank lines, comments or a doc-string, but it must be before any other 
line of Python code.

In the case of Python 2.6 you can execute:

from __future__ import print_function

to turn print into a function like in 3.1.

However, you can't use the asterisk form:

>>> from __future__ import *
  File "", line 1
SyntaxError: future feature * is not defined



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


Re: [Tutor] "Overloading" methods

2010-09-16 Thread Steven D'Aprano
On Thu, 16 Sep 2010 10:02:18 pm Michael Powe wrote:
> Hello,
>
> Strictly speaking, this isn't overloading a method in the way we do
> it in Java.  But similar.  Maybe.

Ha ha, you sound like me -- I can recognise design patterns, but I have 
no idea what they're called, or why anyone bothers to distinguish 
between the "builder" pattern and the "factory" pattern... the 
difference is too subtle for me.

It sounds like what you're trying to do is a design pattern, or 
combination of patterns.


> I am writing a module for processing web server log files and one of
> the methods I provide is to extract a given query parameter and its
> value.

So you have a module that provides a single log-processing class with a 
single method that extracts query parameters?

If there will only ever be a single instance of the class, you should 
consider making the methods ordinary functions. Instead of:

inst = module.LogProcessor()
inst.extract(stuff)


you get:

module.extract(stuff)


Modules give you Singleton behaviour for free!


> Because there are several types of log files with different 
> line structures, I had the thought to write methods with descriptive
> names that simply returned a generic method that processed the method
> arguments. e.g.,
>
> def setpattern_iis(self,pattern,parameter) :
>   type='iis'
>   return pattern_generator(self,type,pattern,parameter)
>
> In this case, creating a regular expression to parse the log lines
> for a query parameter.

Sounds fine to me. I would question the name -- a method 
called "setpattern_iis" should, well, *set* a pattern somewhere (a 
global? a property?), not return a value. But other than that, the 
basic tactic is sound. Whether it is more or less straightforward 
compared to alternatives is another question. (See below.)


> This is just a bit more "self documenting" than using the generic
> method with the 'type' argument and requiring the user to enter the
> type.

True, but consider how the caller might use this. I'm guessing what your 
API might be:

import module
log_parser = module.Log_Parser()  # make a generic parser
regex = logParser.setpattern_iis(pattern, parameter)  # get a regex
results = logParser.search_log(regex, log)  # and use it

Am I close? 

Perhaps a better API might be:

import module
log_parser = module.IIS_Log_Parser()  # make a IIS parser
results = log_parser.search_log(pattern, parameters, log)


In this case, the basic strategy would be to have an abstract log 
parser:

class AbstractLogParser(object):
type = None

def __init__(self):
if self is AbstractLogParser:
raise TypeError('abstract class cannot be initialised')

# define common methods
def pattern_generator(self, pattern, parameter):
type = self.type
return type + "spam"  # whatever...

def search_log(self, pattern, parameters, log):
regex = self.pattern_generator(pattern, parameter)
return regex.search(log)  # whatever


Creating a new subclass is easy:

class IISLogParser(AbstractLogParser):
type = 'iis'



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


Re: [Tutor] robots question

2010-09-16 Thread Steven D'Aprano
On Fri, 17 Sep 2010 01:57:48 am Evert Rol wrote:
> > As a exercise from this book ( Thinking like a computer scientist )
> > I have to make this programm on this
> > page(http://openbookproject.net/thinkcs/python/english2e/ch12.html)
> > Exercise 11
> >
> > #
> > # robots.py
> > #
> > from gasp import *
>
> Argh!
> Is that really in the book?
> Bad book, bad.
>
> You can just "import gasp" and type "gasp." a few times.

Settle down!

import * does have its uses. It should be considered advanced 
functionality, and people (especially beginners) should beware of 
over-using it, but there's no need to treat it as forbidden.



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


Re: [Tutor] Comparing two lists

2010-09-16 Thread Steven D'Aprano
On Fri, 17 Sep 2010 04:27:28 am Michael Powe wrote:
> Hello,
>
> I have two lists.
>
> alist = ['label', 'guid']
>
> blist = ['column0label', 'column1label', 'dimension0guid',
> 'description', 'columnid']
>
> I want to iterate over blist and extract the items that match my
> substrings in alist; 

Presumably you want to get:

clist = ['column0label', 'column1label', 'dimension0guid', 'columnid']


> alternatively, throw out the items that aren't 
> in alist (but, I've had bad experiences removing items from lists "in
> place," so I tend toward the "copy" motif.)

That's almost always the best approach in Python.


> In real life, blist column entries could have embedded column numbers
> from 0 to 19.
>
> I can do this with excrutiatingly painful 'for' loops.  Looking for
> something more efficient and elegant.

Why would they be painful, let alone excruciatingly so?

clist = []
for b in blist:
for a in alist:
if a in b:
clist.append(b)
break

Okay, it's not elegant but it is concise as far as number of operations 
performed, and six lines of code isn't really that bad. There shouldn't 
be anything painful about it. It's simple to read and understand, and 
short enough that you could use it in place if necessary, although I'd 
wrap it in a function.

You can get rid of the inner for-loop:

clist = []
for b in blist:
if any(a in b for a in alist):
clist.append(b)

which then makes the list comp form obvious:

clist = [b for b in blist if any(a in b for a in alist)]



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


Re: [Tutor] robots question

2010-09-16 Thread Steven D'Aprano
On Fri, 17 Sep 2010 11:28:04 am Steven D'Aprano wrote:

> Settle down!

Sorry, that reads a bit more harshly than I intended. Please insert a 
smiley after it.

:)


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


[Tutor] plotting pixels

2010-09-16 Thread Bill Allen
Is there a simple way to plot pixels in Python, without resorting to turtle
graphics?


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


Re: [Tutor] plotting pixels

2010-09-16 Thread James Mills
On Fri, Sep 17, 2010 at 12:13 PM, Bill Allen  wrote:
> Is there a simple way to plot pixels in Python, without resorting to turtle
> graphics?

Give matplotlib a go.

Alternatively you may want to try pygame or pyglet.

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] plotting pixels

2010-09-16 Thread Bill Allen
On Thu, Sep 16, 2010 at 9:21 PM, James Mills
wrote:

> On Fri, Sep 17, 2010 at 12:13 PM, Bill Allen  wrote:
> > Is there a simple way to plot pixels in Python, without resorting to
> turtle
> > graphics?
>
> Give matplotlib a go.
>
> Alternatively you may want to try pygame or pyglet.
>
> cheers
> James
>
> --
> -- James Mills
> --
>
Thanks!  I'll give those a try.

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


[Tutor] Scribbler Robot

2010-09-16 Thread Nick
http://www.georgiarobotics.com/roboteducation/robot-kit.html  

you can check the robot out at this link.  is this a good buy you guys think, 
or is there a better python compatible robot out there?  I just want something 
to keep me interested in programming and that gives me ideas of programs to 
write.  The benefit of the scribbler is also that free book online learning 
with robotics...  It has all kinds of sample code for programs for the 
scribbler.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor