Re: [Tutor] I can't believe this needs to be this complex

2008-08-02 Thread Dick Moores

At 10:08 AM 8/2/2008, Alan Gauld wrote:

"Dick Moores" <[EMAIL PROTECTED]> wrote

BTW Kent, I'm going to take this opportunity to ask you about 
"System" in the IPython timing results. It's always zero for the 
code I time. What's an example of code that would have System be 
greater than zero? And what's the distinction between User and 
System? (I'm using Win XP, if that's relevant.)


In timing user time is time that the CPU spends executing user
code - your program. System time is time the CPU spends doing
OS things.

If your code had a blocking call that waited for input on a port say,
then the OS might be doing other stuff in the background while
your code waited. This would show as system time.
In some OR even time spent reading files from disk is
counted as system time because your code is executing
low level OS functions.

Try timing a function that does nothing but read a large file.
See if there is any system time showing up.


Well, here's one that reads in the text of Dickens' _Little Dorrit_ 
and returns the word count:


In [11]: run -t -N10 timing_test_little_dorrit.py
339832
339832
339832
339832
339832
339832
339832
339832
339832
339832

IPython CPU timings (estimated):
Total runs performed: 10
  Times :  Total   Per run
  User  : 5.94446752311 s, 0.594446752311 s.
  System:0.0 s,0.0 s.


Or time a GUI
app that waits for user input...


This one is a Gui that has an Exit button. I called it and then hit the button:

In [4]: run -t ToolkitV15.py

IPython CPU timings (estimated):
  User  : 10.5294301371 s.
  System:0.0 s.

So no non-zero System time yet. But thanks for your explanation.

Dick


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] locks and threads

2008-08-02 Thread Kent Johnson
On Sat, Aug 2, 2008 at 2:36 PM, James <[EMAIL PROTECTED]> wrote:
> All,
>
> I'm trying to write a class that will acquire a lock before entering a
> critical section, and then release it. Does this look like the right
> way to go about accomplishing my goal?
>
> try:
> grabLock = self.lock.acquire( 0 )
>if grabLock:
>print 'acquired lock successfully'
>else:
>print "did *not* obtain lock"
>< ** what do I put here? ** >
> finally:
>if grabLock is True:
>
>
>self.lock.release()
>print 'released lock'
>
> What should I be doing in the else: statement? If I can't grab the
> lock, should I simply try again? Maybe a while loop that keeps trying
> until I grab the lock? (I'm not really sure how I'm going to integrate
> the 'try' statement with the while loop, though, to solve the problem
> of not grabbing the lock)

What are you using for the lock. A threading.Lock will block if you
try to acquire it and it is not available.

Why do you need the try? You could put the acquire in a while loop.
You probably want to sleep in the loop, so you don't chew up too much
CPU.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Firstrade URL Authentication?

2008-08-02 Thread Kent Johnson
On Sat, Aug 2, 2008 at 11:17 AM, Federo <[EMAIL PROTECTED]> wrote:
> There must be some sofisticated trick to login to www.Firstrade.com. Any Idea
> what else can I try?

You have to find out what it does in the browser using Firebug or
other tools that will let you see the headers and data. Perhaps there
is another cookie (Django authentication sends a cookie with the login
form). Perhaps there is some other header that must be set. Look for
other cookies and try setting the User-Agent header to match what the
browser sends, or just match all the headers.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Firstrade URL Authentication?

2008-08-02 Thread Federo
Hi Kent

Thanks for your reply. According to your instruction I have tried in Python 
interactive window the following (in my test I have used real username and 
password):

>>> import urllib2
>>> import urllib
>>> opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
>>> urllib2.install_opener(opener)
>>> params = urllib.urlencode(dict(username='user', password='pass'))
>>> f = opener.open('https://investor.firstrade.com/firstrade/login.do', params)
>>> data = f.read()
>>> f.close()
>>> f = opener.open('https://investor.firstrade.com/firstrade/mainmenu.do')
>>> data = f.read()
>>> print(data)

It printed out login page which means I wasn't able to login to the main page. 
There must be some sofisticated trick to login to www.Firstrade.com. Any Idea 
what else can I try?

Cheers, Fedo


On Fri, 1 Aug 2008 at 12:45:47, Kent Johnson wrote:

> On Fri, Aug 1, 2008 at 3:39 AM, Federo <[EMAIL PROTECTED]> wrote:
> > Hi ..
> >
> > I have to admit that Python is really surprising me. It was lucky day a
> few
> > weeks ago I firts time start using Python. Lot's of things realy can be
> done
> > with short learning curve. Your user guieds was best place to start!
> >
> > Below is problem I am unable to solve. I would appreciate your advice or
> > even better code sample. The problem is URL authorisation.
> 
> I have a writeup on form-based authentication here:
> http://personalpages.tds.net/~kent37/kk/00010.html#e10form-based-authenticati
> on
> 
> Kent




http://www.email.si/

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Developing Macro: Is it possible in Python?

2008-08-02 Thread Federo
Hi

Is it possible to do macro with Python? Macro should be able to click on given 
x,y screen location (one click, double click), drag scroll bar up / down etc.. 
Macro should be also able to extract data from predefined screen x,y location. 
I would use this to control desktop windows based program. The program is 
written from external provider - not Microsoft or me (it runs on xp 
environment)..

Above actions can be easily performed using Macro Scheduler. I am looking for 
possibility to do the same with Python?

Is there any other way beside macro to control windows based application? The 
best will be to be able to control application from background (the same time 
mouse and screen would be free for other work. No flashing on screen. In ideal 
program would be ran as beck - hiden process..)

Cheers, Fedo


http://www.email.si/

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Output never stops

2008-08-02 Thread Vivek Sant

Hi David,

Simple explanation - you should use if instead of while. A while  
statement executes whatever is in that block again and again until  
the condition becomes false. So your code, the way you have it, first  
checks if the user's input is not -1. If you have typed Lary, it goes  
on to print Lary, hits the end of the while block, and starts back at  
the top, since choice still is not -1. If you change while to if, the  
statement will only be executed once.


Here's a scenario you might want to use a while loop (which might be  
what you were trying to do): suppose you want to keep on asking for  
input if the input is not a quit code, or valid input. To do this,  
you could just put the choice = raw_input line inside the while  
block, and perhaps make sure to initialize choice to '' (an empty  
string or something).


Vivek


On Aug 2, 2008, at 10:21 PM, David wrote:


David wrote:
Very new to python and never programed before. Can not figure out  
why the output never stops when I run this in a terminal



#!/usr/bin/python


choice = raw_input("Enter the name Lary or Joan (-1 to quit): ")
while choice != '-1':  person = {'Lary': 43,'Joan': 24}
  if choice == 'Lary':
  print "Lary's age is:", person.get('Lary')

  elif choice == 'Joan':
  print "Joan's age is:", person.get('Joan')

  else:
   print 'Bad Code'


should have been like this;

#!/usr/bin/python


choice = raw_input("Enter the name Lary or Joan (-1 to quit): ")
while choice != '-1':   person = {'Lary': 43,'Joan': 24}
  if choice == 'Lary':
  print "Lary's age is:", person.get('Lary')

  elif choice == 'Joan':
  print "Joan's age is:", person.get('Joan')

  else:
   print 'Bad Code'


--
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Output never stops

2008-08-02 Thread David

David wrote:
Very new to python and never programed before. Can not figure out why 
the output never stops when I run this in a terminal



#!/usr/bin/python


choice = raw_input("Enter the name Lary or Joan (-1 to quit): ")
while choice != '-1':  person = {'Lary': 43,'Joan': 24}
  if choice == 'Lary':
  print "Lary's age is:", person.get('Lary')

  elif choice == 'Joan':
  print "Joan's age is:", person.get('Joan')

  else:
   print 'Bad Code'


should have been like this;

#!/usr/bin/python


choice = raw_input("Enter the name Lary or Joan (-1 to quit): ")
while choice != '-1': 
  person = {'Lary': 43,'Joan': 24}

  if choice == 'Lary':
  print "Lary's age is:", person.get('Lary')

  elif choice == 'Joan':
  print "Joan's age is:", person.get('Joan')

  else:
   print 'Bad Code'


--
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Output never stops

2008-08-02 Thread David
Very new to python and never programed before. Can not figure out why 
the output never stops when I run this in a terminal



#!/usr/bin/python


choice = raw_input("Enter the name Lary or Joan (-1 to quit): ")
while choice != '-1':  person = {'Lary': 43,'Joan': 24}
  if choice == 'Lary':
  print "Lary's age is:", person.get('Lary')

  elif choice == 'Joan':
  print "Joan's age is:", person.get('Joan')

  else:
   print 'Bad Code'

--
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Classes in separate files

2008-08-02 Thread Alan Gauld

"James" <[EMAIL PROTECTED]> wrote


Another question on classes in separate files...


It could just as well be about functions. The issue is about
visibility of names not classes.

main.py instantiates a class called 'testClass' inside of a file 
temp.py.


In main.py:
  t = temp.testClass()
...
So here's a question...how does the object *t* (defined in the 
temp.py

file) access a global (or even local) variable in main.py? Is it
possible?


You would need to import main into temp.py.
But thats OK since your code has to know about main to want
to access one of its variables! But it destroys yuour classes
reuse capability since they are now bound to main...

Otherwise make it a parameter to the method and pass it in from
where it is called in main.


What if I want the object t to write to a global variable
inside of main.py...is that possible?


Same as above import the module. Or make the method returm
the value and explicitly set the value.

All of which emphasises why global variables are a bad design
idea. And why class methods should work with their own internal
data as much as possible.

--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why use lambda?

2008-08-02 Thread Alan Gauld


"bob gailer" <[EMAIL PROTECTED]> wrote


In my Python Pipelines program for the Count stage I have:

opts = {
 'characters' : lambda rec, tot: tot + len(rec),
 'words' :  lambda rec, tot: tot + len(rec.split()),
 'lines' :  lambda rec, tot: tot + 1,
 'minline' :lambda rec, tot: min(len(rec), tot),
 'maxline' :lambda rec, tot: max(len(rec), tot),
  }


def characters(rec,tot): return tot + len(rec)
def words(rec,tot): return tot + len(rec.split())
etc...

Not many more characters than using lambda and
avoids the need for the dictionary lookup:

instead of

w = opts['words'](r,c)

just use:

w = words(r,c)

If you need the dictionary for dynamic lookup then just insert
the functions intop the dict:

opts = {
'characters' : characters,
'worsds' : words,
etc...
}

Consider how many more lines of code it would take if I had to use 
defs.


More or less by definition a Python lambda expression can
be replaced with a one-liner function.

Consider how readable it is to have the expressions all in one 
place.


In this case I'm not sure the gain is huge, its largely a matter of
personal preference.

Alan G. 



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why use lambda?

2008-08-02 Thread bob gailer

desmond mansfield wrote:

I've read some small tutorials on lambda, and how I can use it to define functions 
"on-the-fly".
But what I don't understand, and cannot seem to find an answer to, is why I'd 
actually want to use it ?

What can lambda do that normal function definitions cannot?
Is it quicker to execute/less memory intensive?
Or is it just quicker to type and easier to think about?

In my Python Pipelines program for the Count stage I have:

opts = {
 'characters' : lambda rec, tot: tot + len(rec),
 'words' :  lambda rec, tot: tot + len(rec.split()),
 'lines' :  lambda rec, tot: tot + 1,
 'minline' :lambda rec, tot: min(len(rec), tot),
 'maxline' :lambda rec, tot: max(len(rec), tot),
  }

Consider how many more lines of code it would take if I had to use defs. 
Consider how readable it is to have the expressions all in one place.


--
Bob Gailer
919-636-4239 Chapel Hill, NC

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] removing whole numbers from text

2008-08-02 Thread Benoit Thiell

Dear Dinesh,

if you're using the regular expression only once, I would recommend:
without_numbers = " ".join(re.split(" [0-9]+ ", phrase))

If not, compile the regular expression first and use the compiled version.

Regards,
Benoit Thiell.

On Sat, 2 Aug 2008, Noufal Ibrahim wrote:


Alan Gauld wrote:


"Dinesh B Vadhia" <[EMAIL PROTECTED]> wrote


I want to remove whole numbers from text but retain numbers
attached to words.


Is this a homework?
If so we can only offer suggestions to direction but not give solutions.


What is the best to do this using re?


Yes, use re to define a pattern then use sub() to replace with
an empty string



If you're having trouble with writing regular expressions, you can either use 
http://www.weitz.de/regex-coach/ (Regex-coach) or Emacs re-builder mode for 
some interactive training.



--
~noufal
http://nibrahim.net.in/
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] locks and threads

2008-08-02 Thread James
All,

I'm trying to write a class that will acquire a lock before entering a
critical section, and then release it. Does this look like the right
way to go about accomplishing my goal?

try:
grabLock = self.lock.acquire( 0 )
if grabLock:
print 'acquired lock successfully'
else:
print "did *not* obtain lock"
< ** what do I put here? ** >
finally:
if grabLock is True:


self.lock.release()
print 'released lock'

What should I be doing in the else: statement? If I can't grab the
lock, should I simply try again? Maybe a while loop that keeps trying
until I grab the lock? (I'm not really sure how I'm going to integrate
the 'try' statement with the while loop, though, to solve the problem
of not grabbing the lock)

Thoughts?

-j
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] removing whole numbers from text

2008-08-02 Thread Noufal Ibrahim

Alan Gauld wrote:


"Dinesh B Vadhia" <[EMAIL PROTECTED]> wrote


I want to remove whole numbers from text but retain numbers
attached to words.


Is this a homework?
If so we can only offer suggestions to direction but not give solutions.


What is the best to do this using re?


Yes, use re to define a pattern then use sub() to replace with
an empty string



If you're having trouble with writing regular expressions, you can 
either use http://www.weitz.de/regex-coach/ (Regex-coach) or Emacs 
re-builder mode for some interactive training.



--
~noufal
http://nibrahim.net.in/
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I can't believe this needs to be this complex

2008-08-02 Thread Alan Gauld

"Dick Moores" <[EMAIL PROTECTED]> wrote

BTW Kent, I'm going to take this opportunity to ask you about 
"System" in the IPython timing results. It's always zero for the 
code I time. What's an example of code that would have System be 
greater than zero? And what's the distinction between User and 
System? (I'm using Win XP, if that's relevant.)


In timing user time is time that the CPU spends executing user
code - your program. System time is time the CPU spends doing
OS things.

If your code had a blocking call that waited for input on a port say,
then the OS might be doing other stuff in the background while
your code waited. This would show as system time.
In some OR even time spent reading files from disk is
counted as system time because your code is executing
low level OS functions.

Try timing a function that does nothing but read a large file.
See if there is any system time showing up. Or time a GUI
app that waits for user input...

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] removing whole numbers from text

2008-08-02 Thread Alan Gauld


"Dinesh B Vadhia" <[EMAIL PROTECTED]> wrote


I want to remove whole numbers from text but retain numbers
attached to words.


Is this a homework?
If so we can only offer suggestions to direction but not give 
solutions.



What is the best to do this using re?


Yes, use re to define a pattern then use sub() to replace with
an empty string

Alan G.










___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor




___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why use lambda?

2008-08-02 Thread Alan Gauld

"desmond mansfield" <[EMAIL PROTECTED]> wrote

But what I don't understand, and cannot seem to find an 
answer to, is why I'd actually want to use it ?


Its a matter of taste. There is nothing you can do with 
lambda that you cannot do with a function definition.
But you might need an awful lot of functions which can 
make your code cluttered.



What can lambda do that normal function definitions cannot?


Exist without a name.


Is it quicker to execute/less memory intensive?


No.


Or is it just quicker to type and easier to think about?


Quicker to type but most folks don't find them easier to think about!
The exception to that is people trained in Lambda calculus where 
lambdas are a fundamental part of the theory. Using lambdas 
then becomes the natural way to express a solution. Lambda 
calculus is what the Functional Programming style is based upon.

Python supports FP so it has lambdas. You don't have to use them.

Some other languages provide much stronger support for lambdas 
than does Python. The python community tends to be split 
into those who would like to see lanmdas made much more 
powerful and those who woyuld like to see them removed 
entirely! The current syntactic sugar version pleases nobody 
very much. :-)


From a pure FP theory point of view a function is a named 
lambda. In some dialects of Lisp you define a function by 
creating a lambda, like this:


(defun f 
  (lambda (expr)))


In Python we can say that

def f : return (expr)

is identical to

f = lambda: (expr)

Ruby and Smalltalk both offer "code blocks" which perform the 
same function but with more flexibility.


--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Classes in separate files

2008-08-02 Thread Alan Gauld

"James" <[EMAIL PROTECTED]> wrote

The issue is, however, that I'm not sure the "best" way to pass 
things

into classes, and the "best" way to get something back.


In an OOP syustem you don;t normally have to pass a lot into
a method since most of the data should be internal to the object
Often a single object parameter is all thats required - if any.


I have a main file, main.py. It's going to create several instances
that are defined by a class in class1.py. *However*, I also need to
instantiate numerous other classes defined in class2.py.


The files issue is largely irrelevant and no different for OOP
than for procedural coding. Keep related classes in a single
module. Put unrelated classes in another module to ease
reuse.


class1.py has a few classes, such as
- ticket (represents a ticket opened to fix bugs in a program)
- ticketAnalyzer (an object who looks at all the tickets 
opened/available)


Its convention to make class names start with an upperc ase letter.
Attributes/methods/instances start with lowercase.

As to TicketAnalyzer - why doesn't the ticket analyze itself?


class2.py has a few classes, as well, such as:
- codemonkey (defines a person that is going to take tickets and fix 
them)


So has a method called fix(aTicket)?

- codereviewer (defines a person who will double check a 
codemonkey's work)


So has a method called check(aTicket)?

These two classes sound like subclasses of a common
superclass - called Person maybe?

main.py has the "main" function, and will be what is actually 
invoked at

the command line. In main.py I can instantiate an object of type
ticket, an object of type ticketAnalyzer, and then instantiate
code{monkey,reviewer} classes. However, how do I get codemonkey and
codereviewer to call methods on the ticket and ticketAnalyzer 
classes?


in the CodeMonkey.fix(aTicket) method the code can reference aTicket.

as in:

def fix(self, aTicket):
faultType = aTicket.analyze()
#   do whatever you do to fix it?!
aTicket.status = aTicket.analyze()  # check if its fixed
return aTicket.status

The only solution I can think of here is having the main function 
(in

main.py) which instantiates all these objects actually *pass in* to
the codemonkey and reviewer the reference to the specific objects
ticketAnalyzer and ticket. Is this the best way to do it?


Its one approach. Without knowing a lot more about the problem
it seems a reasonable way forward


handle that behavior in the __init__ of code{monkey,reviewer}?


Almost certainly not. the monkey and reviewer will presumably
work on more than one ticket so you want to feed the work in
progressively rather than create new instances for each ticket
- I assume, maybe not!

You don't say much about what the system does, which is
pretty fundamental to OOD since it is driven by the behaviour
required. I'm guessing that you want to be able to create
multiple tickets and assign them to a group of monkeys
and reviewers? The system then manages the progress
of the tickets?


I instead create a method inside of the codemonkey and reviewer
classes that accepts the object pointer to the ticket objects and 
then

interact between ticket/code* objects as such?


That's the way I'd go.
OOP programs are all about objects interacting.
Think of the main function as being the global controller
kicking off the initial scenarios which then run as
semi-autonomous threads.


I image it would be much easier to have everything in one file, but
that goes against my grain. ;)


As I said earlier the physical location of the code makes
no difference to the logical design of the system. A few
import startements will deal with that.

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why use lambda?

2008-08-02 Thread Danny Yoo
> What can lambda do that normal function definitions cannot?
> Is it quicker to execute/less memory intensive?
> Or is it just quicker to type and easier to think about?

Notational convenience.  Think about how, in arithmetic expressions,
how we're not forced to give explicit names to all the subexpressions:

#
def hypotenuse(a, b):
return ((a * a) + (b * b))**0.5
#

Imagine a world where we have to give explicit names to all of the
subexpressions:

###
def hypotenuse(a, b):
tmp1 = a * a
tmp2 = b * b
tmp3 = tmp1 + tmp2
tmp4 = tmp3**0.5
return tmp4


Does this look funny to you?  Why?



Sometimes we don't care what something is named: we just want to use
the value.  lambda's use is motivated by the same idea: sometimes, we
want to use a function value without having to give a name. Here's a
toy example.


def deepmap(f, datum):
"""Deeply applies f across the datum."""
if type(datum) == list:
return [deepmap(f, x) for x in datum]
else:
return f(datum)


If we wanted to apply a squaring on all the numbers in the nested list
(while still maintaining the nested structure):

[42, 43, [44, [45]]]

then we can use deepmap by feeding in a square function to it.

##
def square(x):
return x * x

deepmap(square, [42, 43, [44, [45]]])
###

An alternative way to express the above is:

deepmap(lambda x: x *x, [42, 43, [44, [45]]])

Here, we avoid having to first give a name to the function value we're
passing to deepmap.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] removing whole numbers from text

2008-08-02 Thread Dinesh B Vadhia
I want to remove whole numbers from text but retain numbers attached to words.  
All whole numbers to be removed have a leading and trailing space.

For example, in "the cow jumped-20 feet high30er than the lazy 20 timing fox 
who couldn't keep up the 865 meter race." remove the whole numbers 20 and 865 
but keep the 20 in jumped-20 and the 30 in high30er.

What is the best to do this using re?

Dinesh





___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why use lambda?

2008-08-02 Thread Shrutarshi Basu
>From what I've seen, Lambda is most useful if you're passing functions
as arguments to other functions. You could use lambda to create a
function on-the-fly, as you've said, and that will save you the
trouble of having to write it separately. Try looking for examples on
functional programming in Python to find more examples.

On Sat, Aug 2, 2008 at 10:40 AM, desmond mansfield <[EMAIL PROTECTED]> wrote:
>
> I've read some small tutorials on lambda, and how I can use it to define 
> functions "on-the-fly".
> But what I don't understand, and cannot seem to find an answer to, is why I'd 
> actually want to use it ?
>
> What can lambda do that normal function definitions cannot?
> Is it quicker to execute/less memory intensive?
> Or is it just quicker to type and easier to think about?
>
> Any answers would be appreciated. thanks,
> _
> Make a mini you on Windows Live Messenger!
> http://clk.atdmt.com/UKM/go/107571437/direct/01/
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
The ByteBaker :
http://www.bytebaker.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Classes in separate files

2008-08-02 Thread James
Another question on classes in separate files...

main.py instantiates a class called 'testClass' inside of a file temp.py.

In main.py:
   t = temp.testClass()

So now I can access some of the variables inside of 't'. For example,
let's say that in main.py, I do the following:

# get a variable from the t class (I know, this is not the cleanest
way to do this ;))
tempVariable = t.tempVar

So here's a question...how does the object *t* (defined in the temp.py
file) access a global (or even local) variable in main.py? Is it
possible? What if I want the object t to write to a global variable
inside of main.py...is that possible?

Thanks!
-j

On Sat, Aug 2, 2008 at 10:34 AM, James <[EMAIL PROTECTED]> wrote:
> All,
>
> I've started tinkering (just a little) with classes, primarily because
> I have to. (I've never been a huge fan of OOP, but can tolerate it
> when used properly).
>
> I'll be the first to admit that I don't know much about how to program
> "correctly" when dealing with objects, however, so any thoughts in the
> matter would be greatly appreciated.
>
> I have a few files that I use as "libraries" which contain dozens of
> functions that I use across a wide array of programs. This works fine
> when I want to invoke a function, pass in a few parameters, and then
> get something back. I'm now trying to put a few classes which I know I
> will be using repeatedly in a separate file, as well.
>
> The issue is, however, that I'm not sure the "best" way to pass things
> into classes, and the "best" way to get something back.
>
> I have a main file, main.py. It's going to create several instances
> that are defined by a class in class1.py. *However*, I also need to
> instantiate numerous other classes defined in class2.py.
>
> class1.py has a few classes, such as
>  - ticket (represents a ticket opened to fix bugs in a program)
>  - ticketAnalyzer (an object who looks at all the tickets opened/available)
>
> class2.py has a few classes, as well, such as:
>  - codemonkey (defines a person that is going to take tickets and fix them)
>  - codereviewer (defines a person who will double check a codemonkey's work)
>
> main.py has the "main" function, and will what is actually invoked at
> the command line. In main.py I can instantiate an object of type
> ticket, an object of type ticketAnalyzer, and then instantiate
> code{monkey,reviewer} classes. However, how do I get codemonkey and
> codereviewer to call methods on the ticket and ticketAnalyzer classes?
>
> The only solution I can think of here is having the main function (in
> main.py) which instantiates all these objects actually *pass in* to
> the codemonkey and reviewer the reference to the specific objects
> ticketAnalyzer and ticket. Is this the best way to do it? Should I
> handle that behavior in the __init__ of code{monkey,reviewer}? Should
> I instead create a method inside of the codemonkey and reviewer
> classes that accepts the object pointer to the ticket objects and then
> interact between ticket/code* objects as such?
>
> I image it would be much easier to have everything in one file, but
> that goes against my grain. ;)
>
> Thoughts appreciated!
> -j
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Why use lambda?

2008-08-02 Thread desmond mansfield

I've read some small tutorials on lambda, and how I can use it to define 
functions "on-the-fly".
But what I don't understand, and cannot seem to find an answer to, is why I'd 
actually want to use it ?

What can lambda do that normal function definitions cannot?
Is it quicker to execute/less memory intensive?
Or is it just quicker to type and easier to think about?

Any answers would be appreciated. thanks,
_
Make a mini you on Windows Live Messenger!
http://clk.atdmt.com/UKM/go/107571437/direct/01/
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Classes in separate files

2008-08-02 Thread James
All,

I've started tinkering (just a little) with classes, primarily because
I have to. (I've never been a huge fan of OOP, but can tolerate it
when used properly).

I'll be the first to admit that I don't know much about how to program
"correctly" when dealing with objects, however, so any thoughts in the
matter would be greatly appreciated.

I have a few files that I use as "libraries" which contain dozens of
functions that I use across a wide array of programs. This works fine
when I want to invoke a function, pass in a few parameters, and then
get something back. I'm now trying to put a few classes which I know I
will be using repeatedly in a separate file, as well.

The issue is, however, that I'm not sure the "best" way to pass things
into classes, and the "best" way to get something back.

I have a main file, main.py. It's going to create several instances
that are defined by a class in class1.py. *However*, I also need to
instantiate numerous other classes defined in class2.py.

class1.py has a few classes, such as
 - ticket (represents a ticket opened to fix bugs in a program)
 - ticketAnalyzer (an object who looks at all the tickets opened/available)

class2.py has a few classes, as well, such as:
 - codemonkey (defines a person that is going to take tickets and fix them)
 - codereviewer (defines a person who will double check a codemonkey's work)

main.py has the "main" function, and will what is actually invoked at
the command line. In main.py I can instantiate an object of type
ticket, an object of type ticketAnalyzer, and then instantiate
code{monkey,reviewer} classes. However, how do I get codemonkey and
codereviewer to call methods on the ticket and ticketAnalyzer classes?

The only solution I can think of here is having the main function (in
main.py) which instantiates all these objects actually *pass in* to
the codemonkey and reviewer the reference to the specific objects
ticketAnalyzer and ticket. Is this the best way to do it? Should I
handle that behavior in the __init__ of code{monkey,reviewer}? Should
I instead create a method inside of the codemonkey and reviewer
classes that accepts the object pointer to the ticket objects and then
interact between ticket/code* objects as such?

I image it would be much easier to have everything in one file, but
that goes against my grain. ;)

Thoughts appreciated!
-j
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I can't believe this needs to be this complex

2008-08-02 Thread Dick Moores

At 05:02 AM 8/2/2008, Kent Johnson wrote:

On Sat, Aug 2, 2008 at 6:07 AM, Dick Moores <[EMAIL PROTECTED]> wrote:
> I'm pretty new to Python's dictionaries, but I had a need for a function
> that would find the values in a dict that have more than one key each.

From your sample output it appears that you want not just the values,
but a list of (value, keys) pairs for which there are more than one
key. It is easy to just build a reverse dict and filter its items:

In [15]: from collections import defaultdict
In [16]: rev=defaultdict(list)
In [18]: for k, v in d.iteritems():
rev[v].append(k)

In [20]: [ [v, keys] for v, keys in rev.iteritems() if len(keys) > 1 ]

Out[20]:
[[1, ['a', 'e', 'g']],
 [2, ['b', 'f', 'i', 'h']],
 [4, ['d', 'j']],
 ['U.S. Senator', ['John McCain', 'Barack Obama']],
 [56, [45, 55]]]

This also has the advantage of making only two passes over the data so
its performance should be O(n). Your solution and Andre's make one or
more passes over the data for each data element so they will have
O(n*n) performance meaning for a large dict they could be very slow.


Wow, the genius' genius appears!

You're using some Python tools I didn't know about. More study!

I made a function of your code and time tested it against mine, using 
as d that dict of colors at .


Yours is 73 times faster!

In [12]: run -t -N10 fcn_values_dupe_keys.py
Time was 0.297 seconds
Time was 0.328 seconds
Time was 0.344 seconds
Time was 0.328 seconds
Time was 0.313 seconds
Time was 0.344 seconds
Time was 0.39 seconds
Time was 0.297 seconds
Time was 0.312 seconds
Time was 0.297 seconds

IPython CPU timings (estimated):
Total runs performed: 10
  Times :  Total   Per run
  User  : 3.3092253345 s, 0.33092253345 s.
  System:0.0 s,0.0 s.

In [13]: run -t -N10 kent1.py
Time was 0 seconds
Time was 0 seconds
Time was 0 seconds
Time was 0 seconds
Time was 0 seconds
Time was 0.015 seconds
Time was 0 seconds
Time was 0 seconds
Time was 0 seconds
Time was 0 seconds

IPython CPU timings (estimated):
Total runs performed: 10
  Times :  Total   Per run
  User  : 0.044969961266 s, 0.0044969961266 s.
  System:0.0 s,0.0 s.

BTW Kent, I'm going to take this opportunity to ask you about 
"System" in the IPython timing results. It's always zero for the code 
I time. What's an example of code that would have System be greater 
than zero? And what's the distinction between User and System? (I'm 
using Win XP, if that's relevant.)


Thanks,

Dick

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I can't believe this needs to be this complex

2008-08-02 Thread Kent Johnson
On Sat, Aug 2, 2008 at 6:07 AM, Dick Moores <[EMAIL PROTECTED]> wrote:
> I'm pretty new to Python's dictionaries, but I had a need for a function
> that would find the values in a dict that have more than one key each.

>From your sample output it appears that you want not just the values,
but a list of (value, keys) pairs for which there are more than one
key. It is easy to just build a reverse dict and filter its items:

In [15]: from collections import defaultdict
In [16]: rev=defaultdict(list)
In [18]: for k, v in d.iteritems():
rev[v].append(k)

In [20]: [ [v, keys] for v, keys in rev.iteritems() if len(keys) > 1 ]

Out[20]:
[[1, ['a', 'e', 'g']],
 [2, ['b', 'f', 'i', 'h']],
 [4, ['d', 'j']],
 ['U.S. Senator', ['John McCain', 'Barack Obama']],
 [56, [45, 55]]]

This also has the advantage of making only two passes over the data so
its performance should be O(n). Your solution and Andre's make one or
more passes over the data for each data element so they will have
O(n*n) performance meaning for a large dict they could be very slow.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Scan Directory for files

2008-08-02 Thread Kent Johnson
On Sat, Aug 2, 2008 at 1:41 AM, Fred @ Mac <[EMAIL PROTECTED]> wrote:
> Hello,
>
> new to python, so please go easy on me!
>
> I am using
>
> for f in os.listdir(watch_dir):
>tree = ET.parse(f)

Should be ET.parse(os.path.join(watch_dir, f)) I think...

>for shot in tree.findall('Shot'):
>..do stuff..
>
> to scan a directory for specific files (xml files specifically).
>
> But my script fails if, for example, a directory also exists in "watch_dir"
>
> How can i restructure this so it only returns a list of the .xml files in
> that directory, ignores other files and or directories in "watch_dir"

The glob module can filter file names based on patterns.
os.path.isfile() will tell you if something is a file. So for example:

pattern = os.path.join(watch_dir, "*.xml")
for f in glob.glob(pattern):
  if not os.path.isfile(f): #already did the join in the pattern
continue
  tree = ET.parse(f)

Jason Orendorff's path module is useful for this also though the doc
site seems to be down:
http://pypi.python.org/pypi/path.py/2.2

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I can't believe this needs to be this complex

2008-08-02 Thread Dick Moores

At 03:49 AM 8/2/2008, Dick Moores wrote:

At 03:27 AM 8/2/2008, Andre Engels wrote:
Content-Transfer-Encoding: 
base64Content-Disposition: inlineOn Sat, Aug 2, 
2008 at 11:07 AM, Dick Moores <[EMAIL PROTECTED]> wrote:

> I'm pretty new to Python's dictionaries, but I had a need for a function
> that would find the values in a dict that have more than one key each. It
> took me several hours to write. See
> 
 
.

>
[EMAIL PROTECTED] the function needs to be so complex. And also, I suppose
> I've reinvented the wheel (again). Please instruct me.
>
[EMAIL PROTECTED] list comprehension.

Well, list comprehension does indeed seem the solution to your
problem, although a single list comprehension would not be necessary.
I came to http://py77.python.pastebin.com/m4dcbb34f (note: this is
untested, I have no Python on the computer I am working on now), or
http://py77.python.pastebin.com/f76ba5002 to indeed just use a single
list comprehension (or rather, two nested list comprehensions, again
untested for the above reason).


You genius! How could you answer so quickly and 
accurately (20 minutes!) without access to Python?


Both of your scripts work, after I corrected one 
typo. See .


And here's your one-liner 
() at 
work on the dict of colors at .


Dick


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I can't believe this needs to be this complex

2008-08-02 Thread Dick Moores

At 03:27 AM 8/2/2008, Andre Engels wrote:
Content-Transfer-Encoding: 
base64Content-Disposition: inlineOn Sat, Aug 2, 
2008 at 11:07 AM, Dick Moores <[EMAIL PROTECTED]> wrote:

> I'm pretty new to Python's dictionaries, but I had a need for a function
> that would find the values in a dict that have more than one key each. It
> took me several hours to write. See
> 
 
.

>
[EMAIL PROTECTED] the function needs to be so complex. And also, I suppose
> I've reinvented the wheel (again). Please instruct me.
>
[EMAIL PROTECTED] list comprehension.

Well, list comprehension does indeed seem the solution to your
problem, although a single list comprehension would not be necessary.
I came to http://py77.python.pastebin.com/m4dcbb34f (note: this is
untested, I have no Python on the computer I am working on now), or
http://py77.python.pastebin.com/f76ba5002 to indeed just use a single
list comprehension (or rather, two nested list comprehensions, again
untested for the above reason).


You genius! How could you answer so quickly and 
accurately (20 minutes!) without access to Python?


Both of your scripts work, after I corrected one 
typo. See .


Thanks!

Dick Moores


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I can't believe this needs to be this complex

2008-08-02 Thread Andre Engels
On Sat, Aug 2, 2008 at 11:07 AM, Dick Moores <[EMAIL PROTECTED]> wrote:
> I'm pretty new to Python's dictionaries, but I had a need for a function
> that would find the values in a dict that have more than one key each. It
> took me several hours to write. See
> . Seems to do the job, both with
> the example shown, and with the dict of colors at
> .
>
> But I can't believe the function needs to be so complex. And also, I suppose
> I've reinvented the wheel (again). Please instruct me.
>
> My apologies in advance to Kent for not using a single list comprehension.

Well, list comprehension does indeed seem the solution to your
problem, although a single list comprehension would not be necessary.
I came to http://py77.python.pastebin.com/m4dcbb34f (note: this is
untested, I have no Python on the computer I am working on now), or
http://py77.python.pastebin.com/f76ba5002 to indeed just use a single
list comprehension (or rather, two nested list comprehensions, again
untested for the above reason).

-- 
André Engels, [EMAIL PROTECTED]
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] I can't believe this needs to be this complex

2008-08-02 Thread Dick Moores
I'm pretty new to Python's dictionaries, but I had a need for a 
function that would find the values in a dict that have more than one 
key each. It took me several hours to write. See 
. Seems to do the job, 
both with the example shown, and with the dict of colors at 
.


But I can't believe the function needs to be so complex. And also, I 
suppose I've reinvented the wheel (again). Please instruct me.


My apologies in advance to Kent for not using a single list comprehension.

Thanks,

Dick Moores

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Scan Directory for files

2008-08-02 Thread Alan Gauld


"Fred @ Mac" <[EMAIL PROTECTED]> wrote 


for f in os.listdir(watch_dir):
tree = ET.parse(f)
for shot in tree.findall('Shot'):
..do stuff..

But my script fails if, for example, a directory also exists in  
"watch_dir"


Take a look at os.walk which allows recursive traversal of 
a directory structure.


There is a short discussion in the OS topic on my web tutor.

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Scan Directory for files

2008-08-02 Thread Steve Poe

Fred,

What is/are the exact error message(s)?

You may want to look at the module glob.

Steve



Ar e you typing this in the python interpreter or
On Aug 1, 2008, at 10:41 PM, Fred @ Mac wrote:


Hello,

new to python, so please go easy on me!

I am using

for f in os.listdir(watch_dir):
   tree = ET.parse(f)
   for shot in tree.findall('Shot'):
..do stuff..

to scan a directory for specific files (xml files specifically).

But my script fails if, for example, a directory also exists in  
"watch_dir"


How can i restructure this so it only returns a list of the .xml  
files in that directory, ignores other files and or directories in  
"watch_dir"


Thanks!

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor