Re: [Tutor] strings and int()

2009-01-15 Thread Andre Engels
On Thu, Jan 15, 2009 at 1:14 AM, Mr Gerard Kelly
 wrote:
> If you have a string "6", and you do int("6"), you get the number 6.
>
> But if you have a string "2*3" and you do int("2*3") you get a name error.
>
> How do you take an expression in a string, and evaluate the expression
> to get a number?
>
> I want to be able to turn the string "2*3" into the number 6.

There is a method for that, namely eval. eval("2*3") evaluates 2*3 as
a Python expression and thus gives the integer 6. However, usage of
eval is very much discouraged, because it is a very unsafe function.
The problem is that a Python expression can be formed to do whatever
Python can, and that's a lot. If you use it on something coming from
outside the program, you open up your program to an attack by
providing malevolent data. If you use it on something from inside your
program, it is usually is better to look more precisely on what you
are creating.

Still, I guess it could be used provided that you _first_ check
whether the string is of a form that does not have anything dangerous
coming from it. In your case, you might execute eval only if the
string that it is to be executed on consists only of numbers and the
characters -+/*%(). I _think_ there is nothing bad that can happen
then.

-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] NLTK

2009-01-15 Thread Senthil Kumaran
>  Ishan Puri  wrote:
> Hi,
> I have download NLTK for Python 2.5. It download automatically to
> C:\Program Files\Python25\libs\site-packages\nltk. When I try to open a
> module in python, it says that no such module exists. What do I need to do?

There are ways to install the module in the site-packages.
Just downloading and copying to site-packages may not be enough.

After you have downloaded the NLTK page, extract it to a separate
directory, and find a file called setup.py
If it is present,
do
python setup.py install

That sould do.

If setup.py is not present, locate README.txt and follow the instructions.

Even after following the instructions, if you get any error message,
copy/paste the error message here so that we would be able to assist
you better.


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


Re: [Tutor] eval and floating point

2009-01-15 Thread Senthil Kumaran
On Thu, Jan 15, 2009 at 9:42 AM, Bill Campbell  wrote:

> Python does the Right Thing(tm) when dividing two integers,
> returning an integer result.
>

Unless it is python 3k, in which integer division (single /) can
result in float. Because int is a long by default. :-)

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


Re: [Tutor] traceback

2009-01-15 Thread spir
Le Wed, 14 Jan 2009 21:19:11 +0100,
Willi Richert  a écrit :

> Hi,
> 
> do you observe the same behavior with traceback.format_exc()? I've used that 
> always in such situations which worked all the time.
> 
> Regards,
> wr

Actually yes, for the traceback object returned by sys.exc_info() is None. 
(sys.exc_info() -->
(None,None,None)). Like if there was no exception raised, or like if it had 
been clear()ed. 
But when I don't catch the exception launched by a test program, I get the 
standard python error
message and the prog stops -- which proves that there *is* an active exception. 
Simply, I cannot
have it returned by sys.exc_info().
I will try more today to understand why/when/how this happens. As I said, in 
some circomstances
all works well (sys.exc_info() returns a filled (type,value,traceback) tuple) 
but as of now I
cannot understand why.

Denis

> Am Mittwoch, 14. Januar 2009 18:09:51 schrieb spir:
> > Hello,
> >
> > I rather often use exceptions as information providers at design or debug
> > time. A typical use of mine is to have a test version of methods that wrap
> > standard version:
> >
> > def run():
> > do stuff
> > that may
> > raise exc
> > def testRun():
> > try:
> > run()
> > except Error,error:
> > sys.error.write(str(error))
> >
> > So that I can run a bunch of (possibly failing) tests and still get all
> > worthful info. Now, the drawback is that I then lose python provided
> > traceback, as for any reason str(exc) does not return tracback, only the
> > "message". To have the traceback I planned to catch the traceback manually.
> > The aims whare:
> > * be able to output the tracback prepended to the message, when useful
> > * try to find a more readable (for me) format
> > * filter it: e.g. print only last trace mark of each module
> > If you have ideas on the best way to do this, thanks.
> >
> > I tried to use sys.exc_info() that returns a (type,value,traceback) tuple
> > and the format_tb() function of the traceback module. *Sometimes* I get the
> > traceback as expected and all is fine. But in most cases sys.exc_info()
> > returns (None,None,None) like if there was absolutely no active exception.
> > I cannot consistently reproduce the issue to make a clear diagnosis.
> >
> > Thank you,
> > Denis
> >
> > --
> > la vida e estranya
> > ___
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> 
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


--
la vida e estranya
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] single key ordered sequence

2009-01-15 Thread spir
Hello,

a little algorithmic question.

I have a list of tuples element, in which the first item is a kind of key. I 
need a target list
with only one tuple per key. But the order must be kept -- so that I cannot use 
a temp dictionary.
Additionally, in this case the chosen element for a repeted key is the last one 
occurring in
source list.

How would you do that? 
I used the following method that walks through the list with indexes in 
top-down order, and
"marks" items to delete by "None-ing" them. But this a ugly trick imo, and I 
find the overall
method to complicated for such a simple task. There shold be a clear one-liner 
for that, I guess.

Also, how to practically walk in reverse order in a list without copying it 
(e.g. items[::-1]),
especially if i need both indexes and items (couldn't find with enumerate()).

items = 
[(1,'a'),(1,'b'),(2,'a'),(3,'a'),(3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')]
keys = []
for index in range(len(items)-1,-1,-1):
key = items[index][0]
if key in keys:
items[index] = None
else:
keys.append(key)
items = [item for item in items if item is not None]

denis
--
la vida e estranya
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] traceback

2009-01-15 Thread Willi Richert
Hi,

from http://effbot.org/pyref/sys.exc_info.htm:

"The information returned is specific both to the current thread and to the 
current stack frame. If the current stack frame is not handling an exception, 
the information is taken from the calling stack frame, or its caller, and so 
on until a stack frame is found that is handling an exception."

Maybe you are actually in two different threads?
Take also a look at http://pbe.lightbird.net/traceback-module.html

Regards,
wr

Am Donnerstag, 15. Januar 2009 11:54:50 schrieb spir:
> Le Wed, 14 Jan 2009 21:19:11 +0100,
>
> Willi Richert  a écrit :
> > Hi,
> >
> > do you observe the same behavior with traceback.format_exc()? I've used
> > that always in such situations which worked all the time.
> >
> > Regards,
> > wr
>
> Actually yes, for the traceback object returned by sys.exc_info() is None.
> (sys.exc_info() --> (None,None,None)). Like if there was no exception
> raised, or like if it had been clear()ed. But when I don't catch the
> exception launched by a test program, I get the standard python error
> message and the prog stops -- which proves that there *is* an active
> exception. Simply, I cannot have it returned by sys.exc_info().
> I will try more today to understand why/when/how this happens. As I said,
> in some circomstances all works well (sys.exc_info() returns a filled
> (type,value,traceback) tuple) but as of now I cannot understand why.
>
> Denis
>
> > Am Mittwoch, 14. Januar 2009 18:09:51 schrieb spir:
> > > Hello,
> > >
> > > I rather often use exceptions as information providers at design or
> > > debug time. A typical use of mine is to have a test version of methods
> > > that wrap standard version:
> > >
> > > def run():
> > >   do stuff
> > >   that may
> > >   raise exc
> > > def testRun():
> > >   try:
> > >   run()
> > >   except Error,error:
> > >   sys.error.write(str(error))
> > >
> > > So that I can run a bunch of (possibly failing) tests and still get all
> > > worthful info. Now, the drawback is that I then lose python provided
> > > traceback, as for any reason str(exc) does not return tracback, only
> > > the "message". To have the traceback I planned to catch the traceback
> > > manually. The aims whare:
> > > * be able to output the tracback prepended to the message, when useful
> > > * try to find a more readable (for me) format
> > > * filter it: e.g. print only last trace mark of each module
> > > If you have ideas on the best way to do this, thanks.
> > >
> > > I tried to use sys.exc_info() that returns a (type,value,traceback)
> > > tuple and the format_tb() function of the traceback module. *Sometimes*
> > > I get the traceback as expected and all is fine. But in most cases
> > > sys.exc_info() returns (None,None,None) like if there was absolutely no
> > > active exception. I cannot consistently reproduce the issue to make a
> > > clear diagnosis.
> > >
> > > Thank you,
> > > Denis
> > >
> > > --
> > > la vida e estranya
> > > ___
> > > Tutor maillist  -  Tutor@python.org
> > > http://mail.python.org/mailman/listinfo/tutor
> >
> > ___
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
>
> --
> la vida e estranya
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Dipl.-Inform. Willi Richert
C-LAB - Cooperative Computing & Communication Laboratory
 der Universität Paderborn und Siemens

FU.323
Fürstenallee 11
D-33102 Paderborn
Tel: +49 5251 60 6120
Fax: +49 5251 60 6065
http://www.c-lab.de
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] tkinter canvas

2009-01-15 Thread Alan Gauld

"Mr Gerard Kelly"  wrote

All it does take a number (6 in this case) and draw that number of 
blue

boxes on a canvas.

I want to be able to bind these boxes to an event - so that I can 
either
click on them, or hold the mouse cursor over them, and have them 
change

color.


I don;t think you can bind events to an object on a canvas, the events
can only be bound to the canvas.

So you would need to determine which object was being highlighted
using the x,y coordinates of the event at the canvas level and then
manipulate the shapes accordingly. This might be easier if you create
a series of shape objects and hold a list of those. You can then 
iterate
over the list to lovcate which object contains the point and that 
object

can update itself. This also makes handling the case of overlapping
objects easier.

There might be a more Tkinter'ish way of doing this but I've not come
across it.

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] eval and floating point

2009-01-15 Thread Alan Gauld


"Mr Gerard Kelly"  wrote

I've noticed that the eval() function gives an integer, so 
eval("3/2")
gives back 1. float(eval("3/2")) doesn't seem to work, any way to 
get a

floating point number back with eval()?


Move the float inside the eval:

eval("float(3/2)")

It's nothing to do with eval but with Python. eval just asks the
interpreter to evaluate the string. Which is why you hardly ever
need to use eval, you can usually work with the string in your
own code and execute it that way.

Alan G


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


Re: [Tutor] Non-blocking non-interactive graphics display

2009-01-15 Thread Alan Gauld


"David Williams"  wrote 


I am looking for the simplest way of displaying a little positional
data as a line graphic in a window as a script runs.


I got a bit lost in the description which followed but a couple of 
things stood out:



My problem is that using tkinter, it looks to be a bit difficult to
get this to work since showing the window blocks the rest of the
script from running. 


That shouldn't happen if your code is event driven.
You manipulate the data, update the screen then stop and wait 
for the next evernt (which could be a timer)



I am not terribly familiar with threads and keen
to avoid them if they are unnecessary. 


It doesn't sound like you need threads for this.

The display is non-interactive and so communication with it 
can be one-way. 


You still want to use events but probabnly driven by timers


Bonus points if it is part of the Enthought Python Distribution and
pleasingly anti-aliased.


Sorry, I've never come across Envision before.

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] running & debugging in python interactive shell

2009-01-15 Thread Alan Gauld


"Artie Ziff"  wrote

running python scripts. Does anyone know of an article that 
describes

best practices for running and debugging scripts inside the python
shell? Of course, I use import directive to run my script for first 
run.

I am seeking techniques for invoking parts of script after initial
import. I hope this makes sense to those persons reading. :)


Provided you have built the module as a set of functions/classes
then after import you can just call those functions from the shell.

You cannot invoke arbitrary lines of code (as you can in the
Smalltalk workspace for example). Accessing functions etc is
normal practice in the shell so I'm not sure what you are really
asking here?


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



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


Re: [Tutor] Creating simple windows in XP

2009-01-15 Thread Alan Gauld

"Alex Krycek"  wrote

I'd like to create very simple GUI's in XP.  For the sake of 
simplicity, I'm

trying to avoid downloading and installing anything (although I am
considering EasyGui).


The basic GUI framework in Python is Tkinter and that works fine on 
XP.
See my tutorial topic on GUI programming for a very simople intro 
before

trying any of themore fully featured Tkinter tutorials...


To see how well it works, I've tried having my
program run a Visual Basic script ( i.e. 
subprocess.call(someScript.vbs,
shell = True) ).  It seemed to work ok. I was just wondering if 
there was a

better and/or easier way of doing this.


That does of course work but is not really you creating a GUI its just
running another program. You could start Word or Excel just as easily!

There are many other Python GUI frameworks, some have GUI builders
somewhat like VB. But they are all downloadable add-ons. Tkinter is 
the
only one that comes as sandard. Its primitive, but easy to learn and 
use

for basic form style applications.

--
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] eval and floating point

2009-01-15 Thread Andre Engels
On Thu, Jan 15, 2009 at 1:08 PM, Alan Gauld  wrote:
>
> "Mr Gerard Kelly"  wrote
>
>> I've noticed that the eval() function gives an integer, so eval("3/2")
>> gives back 1. float(eval("3/2")) doesn't seem to work, any way to get a
>> floating point number back with eval()?
>
> Move the float inside the eval:
>
> eval("float(3/2)")

That still does not work, because the 'float' comes after the
division. 3/2 equals 1, so float(3/2) equals 1.0. To make it work,
you'll have to put the float inside the division:

eval("float(3)/2")

or

eval("3/float(2)")

Which, as said before, is written less complicatedly as:

eval("3.0/2")


-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] tkinter canvas

2009-01-15 Thread Kent Johnson
On Thu, Jan 15, 2009 at 12:41 AM, Mr Gerard Kelly
 wrote:

> I want to be able to bind these boxes to an event - so that I can either
> click on them, or hold the mouse cursor over them, and have them change
> color.

Here is a version of your program that binds the Enter and Leave
events to each box and changes the box color when the mouse is over
it:

#

from Tkinter import *

master = Tk()

numboxes=6

width=40*(numboxes+2)
height=200
w = Canvas(master, width=width, height=height)
w.pack()

size=width/(numboxes+2)

box=[0]*numboxes

def enter(e, i):
e.widget.itemconfigure(box[i], fill='red')

def leave(e, i):
e.widget.itemconfigure(box[i], fill='blue')

for i in range(numboxes):
box[i]=w.create_rectangle((1+i)*40, 40, (2+i)*40, height-40, fill="blue")
w.tag_bind(box[i], '', lambda e, i=i: enter(e, i))
w.tag_bind(box[i], '', lambda e, i=i: leave(e, i))

mainloop()

###

The 'i=i' in the lambda is needed due to the (surprising) way that
variables are bound to closures; without it, every event would be
bound to the same value of i. Some explanation here:
http://code.activestate.com/recipes/502271/

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


Re: [Tutor] Non-blocking non-interactive graphics display

2009-01-15 Thread Kent Johnson
On Thu, Jan 15, 2009 at 1:00 AM, David Williams  wrote:

> I am looking for the simplest way of displaying a little positional
> data as a line graphic in a window as a script runs.
>
> Something like:
>
>#Set up some points
>pt1 = (0,0)
>pt2 = (2,1)
>pt3 = (3,2)
>#Create a window that displays the points as two lines connected at pt2
>import somethingsomething #maybe something like import enthought.enable
>window = somethingsomething.graph_points_as_line(pt1,pt2,pt3)
>#Iterate
>for i in range(0,100):
>#Change the points slightly, this takes a bit of time
>[pt1, pt2, pt3] = 
> update_points_with_derived_values(pt1,pt2,pt3)
>#Update the display
>window.graph_points(pt1,pt2,pt3)
>
> My problem is that using tkinter, it looks to be a bit difficult to
> get this to work since showing the window blocks the rest of the
> script from running.

A little more context might help. What is the rest of the script
doing? Is it the update points that is being blocked?

tkinter supports animation. Here is an example of animation in tkinter
that might help:
http://effbot.org/zone/tkinter-animation.htm

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


Re: [Tutor] Creating simple windows in XP

2009-01-15 Thread Kent Johnson
On Thu, Jan 15, 2009 at 1:29 AM, Alex Krycek  wrote:
> Hello,
>
> I'd like to create very simple GUI's in XP.  For the sake of simplicity, I'm
> trying to avoid downloading and installing anything (although I am
> considering EasyGui).  To see how well it works, I've tried having my
> program run a Visual Basic script ( i.e. subprocess.call(someScript.vbs,
> shell = True) ).  It seemed to work ok. I was just wondering if there was a
> better and/or easier way of doing this.

Tkinter is the only GUI framework that comes with Python. If EasyGUI
meets your needs, why not use it?

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


Re: [Tutor] traceback -- how it works?

2009-01-15 Thread spir
Le Wed, 14 Jan 2009 21:19:11 +0100,
Willi Richert  a écrit :

> Hi,
> 
> do you observe the same behavior with traceback.format_exc()? I've used that 
> always in such situations which worked all the time.
> 
> Regards,
> wr

Hello again, Willi & all,

I guess I got the point. I thought that tracebacks where generated when an 
exception occurs, and
then the exception itself was in a way linked to the matching traceback. 
Actually I thought that
because the trace path exists before the exception. But I was wrong. It seems 
instead that the
exception is first generated and only a traceback object. Maybe python 
generates the traceback
only when it needs to print out the exception report, a part of which beeing 
the traceback.
As a consequence, when an exception is created, no traceback exists at all, so 
that it may not be
possible to have custom exceptions know about their own tracbacks.

I wanted for a trial to have an "Error" type print out traceback in a different 
form. With
rather complicated tests using a project of mine, I got what seemed 
unpredictable results where
sometimes only a traceback existed.
But simply launching an Error gives this:

raise Error("TEST")
==>
Traceback (most recent call last):
  File "tools.py", line 324, in 
testError()
  File "tools.py", line 287, in testError
raise Error("TEST")
__main__.Error: 

TEST

Now, if I catch the first exception by nesting it inside a try...except, I will 
get the traceback
of the first exception inside the second one:

try:
print 1/0
except ZeroDivisionError,error:
raise Error(str(error) + " -- CAUGHT")
==>
Traceback (most recent call last):
  File "tools.py", line 324, in 
testError()
  File "tools.py", line 291, in testError
raise Error(str(error) + " -- CAUGHT")
__main__.Error: 

   module 'tools.py'-- in testError():
  line 00289:  print 1/0
integer division or modulo by zero -- CAUGHT

Another more complex test involving an exception generated from within en 
external module gives:

### module tools.py ###
from throw_error import throw_error
def raise_uncaught_error():
try:
throw_error()
except TypeError:
raise Error("A set cannot hold a mutable item.")
### module throw_error.py ###
from sets import Set
def build_set(l):
s = Set(l)
def throw_error():
build_set([[1,2,3]])
==>
Traceback (most recent call last):
  File "tools.py", line 318, in 
testError()
  File "tools.py", line 310, in testError
raise_uncaught_error()
  File "tools.py", line 294, in raise_uncaught_error
raise Error("A set cannot hold a mutable item.")
__main__.Error: 

   module 'tools.py'-- in raise_uncaught_error():
  line 00291:  throw_error()
   module '/home/spir/prog/ospyp/throw_error.py'-- in throw_error():
  line 9:  build_set([[1,2,3]])
   module '/home/spir/prog/ospyp/throw_error.py'-- in build_set():
  line 6:  s = Set(l)
   module '/usr/lib/python2.5/sets.py'-- in __init__():
  line 00429:  self._update(iterable)
   module '/usr/lib/python2.5/sets.py'-- in _update():
  line 00374:  data[element] = value
A set cannot hold a mutable item.

The python traceback is the one of the second exception (mine), while the 
traceback read and
reformatted by my custom exception is the one of the original exception 
(lauched by the module
sets). Which is rather interesting -- even if not what I intended to do.
Now, I can catch my own exception to avoid stopping a test unit run, for 
instance, and only print
out the exception message:

def raise_caught_error():
try:
raise_uncaught_error()
except Error,error:
print error
==>

   module 'tools.py'-- in raise_uncaught_error():
  line 00291:  throw_error()
   module '/home/spir/prog/ospyp/throw_error.py'-- in throw_error():
  line 9:  build_set([[1,2,3]])
   module '/home/spir/prog/ospyp/throw_error.py'-- in build_set():
  line 6:  s = Set(l)
   module '/usr/lib/python2.5/sets.py'-- in __init__():
  line 00429:  self._update(iterable)
   module '/usr/lib/python2.5/sets.py'-- in _update():
  line 00374:  data[element] = value
A set cannot hold a mutable item.

thank you for your help,
Denis

> Am Mittwoch, 14. Januar 2009 18:09:51 schrieb spir:
> > Hello,
> >
> > I rather often use exceptions as information providers at design or debug
> > time. A typical use of mine is to have a test version of methods that wrap
> > standard version:
> >
> > def run():
> > do stuff
> > that may
> > raise exc
> > def testRun():
> > try:
> > run()
> > except Error,error:
> > sys.error.write(str(error))
> >
> > So that I can run a bunch of (possibly failing) tests and still get all
> > worthful info. Now, the drawback is that I then lose python provided
> > traceback, as for any reason str(exc) does not return tracback, only the
> > "message". To have the traceback I planned to catch the traceback

Re: [Tutor] traceback

2009-01-15 Thread Kent Johnson
On Wed, Jan 14, 2009 at 12:09 PM, spir  wrote:
> Hello,
>
> I rather often use exceptions as information providers at design or debug 
> time. A typical use
> of mine is to have a test version of methods that wrap standard version:
>
> def run():
>do stuff
>that may
>raise exc
> def testRun():
>try:
>run()
>except Error,error:
>sys.error.write(str(error))
>
> So that I can run a bunch of (possibly failing) tests and still get all 
> worthful info.

You might be interested in the unittest module. It lets you create and
run a series of tests, some of which may fail, while reporting errors
in a useful way.

My introduction is here:
http://personalpages.tds.net/~kent37/kk/00014.html

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


Re: [Tutor] single key ordered sequence

2009-01-15 Thread Kent Johnson
On Thu, Jan 15, 2009 at 6:48 AM, spir  wrote:

> I have a list of tuples element, in which the first item is a kind of key. I 
> need a target list
> with only one tuple per key. But the order must be kept -- so that I cannot 
> use a temp dictionary.
> Additionally, in this case the chosen element for a repeted key is the last 
> one occurring in
> source list.
>
> How would you do that?

In [1]: items =
[(1,'a'),(1,'b'),(2,'a'),(3,'a'),(3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')]
In [2]: seen = set()
In [3]: newItems = []

In [5]: for item in reversed(items):
   ...: if item[0] not in seen:
   ...: seen.add(item[0])
   ...: newItems.append(item)

In [6]: newItems
Out[6]: [(5, 'c'), (4, 'a'), (3, 'b'), (2, 'a'), (1, 'b')]

In [7]: newItems.reverse()

In [8]: newItems
Out[8]: [(1, 'b'), (2, 'a'), (3, 'b'), (4, 'a'), (5, 'c')]

Or, with a somewhat hacky list comp:

In [9]: seen = set()

In [10]: [ item for item in reversed(items) if item[0] not in seen and
not seen.add(item[0]) ]

> Also, how to practically walk in reverse order in a list without copying it 
> (e.g. items[::-1]),
> especially if i need both indexes and items (couldn't find with enumerate()).

See use of reversed() above. You can combine it with enumerate():

In [13]: list(enumerate(reversed(items)))
Out[13]:
[(0, (5, 'c')),
 (1, (5, 'b')),
 (2, (5, 'a')),
 (3, (4, 'a')),
 (4, (3, 'b')),
 (5, (3, 'a')),
 (6, (2, 'a')),
 (7, (1, 'b')),
 (8, (1, 'a'))]

In [16]: list(reversed(list(enumerate(items
Out[16]:
[(8, (5, 'c')),
 (7, (5, 'b')),
 (6, (5, 'a')),
 (5, (4, 'a')),
 (4, (3, 'b')),
 (3, (3, 'a')),
 (2, (2, 'a')),
 (1, (1, 'b')),
 (0, (1, 'a'))]

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


Re: [Tutor] help with getting python to run from command prompt onWindows XP

2009-01-15 Thread Brian van den Broek

Alan Gauld said unto the world at 14/01/09 07:34 PM:


"Brian van den Broek"  wrote

icon for Idle launching as expected. When run from IDLE, `print 
sys.executable' yields `C:\\Python26\\pythonw.exe'.

He reports that C:\Python26 contains both python.exe and pythonw.exe.

I've had him add the text `;C:\Python26' (without quotes) to the end 
of his Path environment variable via the Control Panel|System 
Properties way of editing Environment variables. I've had him reboot 
afterwards.


Get him to type

SET > env.txt

at the DOS prompt that should list all environment variables into env.txt

Get him to email that file to you and check what it says about PATH.

After all of that, he reports that an attempt to run python from the 
command prompt produces a complaint that `` `python' is not recognized 
as an internal or external command, operable program or batch file.''


What happens if he types

C:PROMPT> C:\Python26\python.exe

In other words uses the full path?



Hi all,

Thanks to all respondents for the input. Apologies for the delay in 
reply; there's a bit of a lag as I'm communicating with my friend by 
email, too.


With the full path, python loads as expected. I'm awaiting the results of
SET > env.txt
as per Alan's suggestion above.

If that doesn't clear it up for me, I shall report back.

Thanks again,

Brian vdB

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


Re: [Tutor] help with getting python to run from command prompt onWindows XP

2009-01-15 Thread Brian van den Broek

Brian van den Broek said unto the world at 15/01/09 11:27 AM:

Alan Gauld said unto the world at 14/01/09 07:34 PM:


"Brian van den Broek"  wrote


DOS prompt and replies including Alan's suggestion to get a text file 
dump of environment variables.>



With the full path, python loads as expected. I'm awaiting the results of
SET > env.txt
as per Alan's suggestion above.


Never fails. Shortly after posting, I got an answer back from the 
friend I'm trying to help.


The (recognized by me as) relevant bits of output are:
Path=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program 
Files\texlive\2008\bin\win32;C:\Python26

PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH

There is no subsequent Path line that might be stomping on the line 
shown above.


I'm surprised that it is `Path' rather than `PATH'. Does that matter? 
I'm pretty sure that my friend didn't change that, as once he got into 
the `Edit System Variable' dialog, he felt uncertain and sent me a 
screen shot before he effected any modifications; the screen shot 
shows `Path'.


Last, the texlive entry is from an installation of latex that I guided 
him through right before we installed python. Invoking latex from the 
command line works as expected, so I conclude that the Path is not broken.



If that doesn't clear it up for me, I shall report back.


Didn't and did.

Thanks and best,

Brian

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


Re: [Tutor] help with getting python to run from command prompt onWindows XP

2009-01-15 Thread Kent Johnson
On Thu, Jan 15, 2009 at 11:48 AM, Brian van den Broek
 wrote:
> The (recognized by me as) relevant bits of output are:
> Path=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program
> Files\texlive\2008\bin\win32;C:\Python26
> PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH
>
> There is no subsequent Path line that might be stomping on the line shown
> above.
>
> I'm surprised that it is `Path' rather than `PATH'. Does that matter?

I don't think so, my PC has 'Path' also. I'm stumped...

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


Re: [Tutor] help with getting python to run from command prompt onWindows XP

2009-01-15 Thread Dj Gilcrease
if he just needs to run python scripts you just need to type the
script name (preferably from the directory it is in)

eg: C:\Path\To\App>app_name.py

and it will run

Also if you have changed the enviromental variables, you need to close
the command prompt and re-open it on windows since it does not
propagate to existing instances

Dj Gilcrease
OpenRPG Developer
~~http://www.openrpg.com



On Thu, Jan 15, 2009 at 9:48 AM, Brian van den Broek
 wrote:
> Brian van den Broek said unto the world at 15/01/09 11:27 AM:
>>
>> Alan Gauld said unto the world at 14/01/09 07:34 PM:
>>>
>>> "Brian van den Broek"  wrote
>
>  prompt and replies including Alan's suggestion to get a text file dump of
> environment variables.>
>
>> With the full path, python loads as expected. I'm awaiting the results of
>> SET > env.txt
>> as per Alan's suggestion above.
>
> Never fails. Shortly after posting, I got an answer back from the friend I'm
> trying to help.
>
> The (recognized by me as) relevant bits of output are:
> Path=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program
> Files\texlive\2008\bin\win32;C:\Python26
> PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH
>
> There is no subsequent Path line that might be stomping on the line shown
> above.
>
> I'm surprised that it is `Path' rather than `PATH'. Does that matter? I'm
> pretty sure that my friend didn't change that, as once he got into the `Edit
> System Variable' dialog, he felt uncertain and sent me a screen shot before
> he effected any modifications; the screen shot shows `Path'.
>
> Last, the texlive entry is from an installation of latex that I guided him
> through right before we installed python. Invoking latex from the command
> line works as expected, so I conclude that the Path is not broken.
>
>> If that doesn't clear it up for me, I shall report back.
>
> Didn't and did.
>
> Thanks and best,
>
> Brian
>
> ___
> 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] Python3.0 and Tkinter on ubuntu 8.10 HOWTO

2009-01-15 Thread Senthil Kumaran
On Wed, Jan 14, 2009 at 03:38:20PM -0500, Vern Ceder wrote:
> Since there was some interest in the question of how to get a full  
> Python 3.0, including Tkinter and IDLE, compiled on Ubuntu Intrepid  
> 8.10, I've written up what I've done and posted it at  
> http://learnpython.wordpress.com/2009/01/14/installing-python-30-on-ubuntu/
>

Good explaination!
You can also make a note about make fullinstall, which will make
Python 3.0 as the default
And also mention about python binary being present as
python2.5,python2.6 and python3.0 when more than one version is
installed.

Thanks,
Senthil

-- 
Senthil Kumaran O.R.
http://uthcode.sarovar.org 

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


Re: [Tutor] help with getting python to run from command prompt onWindows XP

2009-01-15 Thread Marc Tompkins
On Thu, Jan 15, 2009 at 9:35 AM, Dj Gilcrease  wrote:

> if he just needs to run python scripts you just need to type the
> script name (preferably from the directory it is in)
>
> eg: C:\Path\To\App>app_name.py
>
> and it will run
>

By default, and on most people's machines, not true.  You can double-click
on a .py script from the GUI, and if your file associations are set
correctly then Python (or PythonW) will be invoked - but from the command
line, not so much.

HOWEVER:  if you add ";.PY;.PYW" to the end of your PATHEXT string, then
this will work.  (Just tried it out on my machine and wonder why I never did
before.)

Unfortunately, this still requires that Windows be able to find "python.exe"
or "pythonw.exe" in the system path... so it's nifty, but doesn't solve the
OP's problem.


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


Re: [Tutor] single key ordered sequence

2009-01-15 Thread Senthil Kumaran
> Also, how to practically walk in reverse order in a list without
> copying it (e.g. items[::-1]),
> especially if i need both indexes and items (couldn't find with
> enumerate()).
> 
Are you looking for reversed()?
The way you are doing it is probably OK. 
But it can be simplified thus:

keys = []
target = []

for item in reversed(items):
if not item[0] in keys:
keys.append(item[0])
target.append(item)

print target

If this is not what you wanted,then I have misunderstood your
requirement and just based it on your code.

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


Re: [Tutor] help with getting python to run from command prompt onWindows XP

2009-01-15 Thread Marc Tompkins
On Thu, Jan 15, 2009 at 8:48 AM, Brian van den Broek
wrote:

>
> The (recognized by me as) relevant bits of output are:
> Path=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program
> Files\texlive\2008\bin\win32;C:\Python26
> PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH
>
> There is no subsequent Path line that might be stomping on the line shown
> above.
>

New thought: could this be some sort of long-filename/short-filename
weirdness?  What happens if you have your friend do the following:

> C:\>dir /x py*
>  Volume in drive C has no label.
>  Volume Serial Number is E400-17CA
>
>  Directory of C:\
>
> 2008-09-22  10:24 PM   Python26
>0 File(s)  0 bytes
>1 Dir(s)   9,809,756,160 bytes free
>

See that long empty space between "" and "Python26"?  That means that
there's no fake short filename associated with "Python26", which is what we
expect - "Python26" is less than eight characters and has no spaces.
However, funky things can happen during installation, and I have seen cases
where filenames that _look_ normal STILL get fake short filenames associated
with them.

If you see anything between "" and "Python26" on your friend's machine
(it would probably look like PYTHON~1.0, or something similar), then try
putting (whatever it is) into the Path instead...


-- 
www.fsrtechnologies.com

p.s. - Full disclosure - I actually still have Python 2.5.1, so my directory
is actually "Python25".  Shouldn't matter, but wanted to disclose that.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] eval and floating point

2009-01-15 Thread Alan Gauld


"Andre Engels"  wrote


eval("float(3/2)")


That still does not work, because the 'float' comes after the
division. 3/2 equals 1, so float(3/2) equals 1.0. To make it work,
you'll have to put the float inside the division:

eval("float(3)/2")


Ahem! Quite. That was what I actually intended to post!

But having seen the other posts suggesting using future 
I had a rethink.


I don't think either float() or the "3.0" approach will help the 
OP because I suspect he is trying to eval a string stored 
in a variable. In that case the "import future" trick is probably 
the only solution that will work, short of parsing the string and 
doing the division without using eval...


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] running & debugging in python interactive shel

2009-01-15 Thread W W
On Wed, Jan 14, 2009 at 8:18 PM, Che M  wrote:

>  
> I'd like to add to this question and expand it:  can anyone point me to
> a good resource on debugging *generally*?
>

The first result on "Debugger tutorial" on google sent me to this:
http://www.cs.princeton.edu/~benjasik/gdb/gdbtut.html

Though it's for a specific program, it seems to have some good general
purpose advice. Personally, I've never had the need for a debugger (maybe
because I'm not writing complicated enough programs) - a simple "print"
statement (in the right spot) tends to take care of all of my debugging
needs.

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


Re: [Tutor] eval and floating point

2009-01-15 Thread wesley chun
>>> eval("float(3/2)")
>>
>> That still does not work, because the 'float' comes after the
>> division. 3/2 equals 1, so float(3/2) equals 1.0. To make it work,
>> you'll have to put the float inside the division:
>> eval("float(3)/2")

correct. as long as one of the operands is a float, the division will
be (or rather, the division *won't* be integer), i.e., "3./2" or
"3/2.".

> the "import future" trick is probably the only solution that will work,
> short of parsing the string and doing the division without using eval...

in addition to the import of division from __future__, which adds one
extra line of code to all your source files which need this
functionality, you can also use -Qnew to launch the interpreter, which
defaults to the 3.x true division semantics:

$ python -Qnew
Python 2.4.5 (#1, May  9 2008, 12:23:22)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 3/2
1.5

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
"Python Fundamentals", Prentice Hall, (c)2009
http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] tkinter canvas

2009-01-15 Thread Alan Gauld

"Kent Johnson"  wrote


for i in range(numboxes):
   box[i]=w.create_rectangle((1+i)*40, 40, (2+i)*40, height-40, 
fill="blue")

   w.tag_bind(box[i], '', lambda e, i=i: enter(e, i))
   w.tag_bind(box[i], '', lambda e, i=i: leave(e, i))


I'm wrong again. I've never noticed tag_bind() before.
Although on investigation it is used by Grayson in his Tkinter book...

I notice it can also be used in the Text widget to catch events on
specific items of text or embedded images etc.

Nice.

Alan G 



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


Re: [Tutor] help with getting python to run from command prompt onWindows XP

2009-01-15 Thread Alan Gauld


"Brian van den Broek"  wrote


The (recognized by me as) relevant bits of output are:
Path=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program 
Files\texlive\2008\bin\win32;C:\Python26

PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH


That looks OK. Puzzling!

Scraping the barrel here but he is definitely using a command prompt 
to

type the command?  ie He is not using Start->Run?
The latter has a different registry based, way of determining the 
path.


Otherwise I'm baffled!

Alan G 



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


Re: [Tutor] Creating simple windows in XP

2009-01-15 Thread Alex Krycek
Thanks for the suggestions guys. I had looked at Tkinter before and liked
that it comes w/ Python. It's just that it's so complex writing anything.
EasyGui is pretty simple, but I relying on standard tools. I liked how in
VB, for example, to open a dialog box you could write:

MsgBox("Text", vbOKOnly, "Title").

I'll probably go with EasyGui. Thanks again.



On Thu, Jan 15, 2009 at 5:33 AM, Kent Johnson  wrote:

> On Thu, Jan 15, 2009 at 1:29 AM, Alex Krycek 
> wrote:
> > Hello,
> >
> > I'd like to create very simple GUI's in XP.  For the sake of simplicity,
> I'm
> > trying to avoid downloading and installing anything (although I am
> > considering EasyGui).  To see how well it works, I've tried having my
> > program run a Visual Basic script ( i.e. subprocess.call(someScript.vbs,
> > shell = True) ).  It seemed to work ok. I was just wondering if there was
> a
> > better and/or easier way of doing this.
>
> Tkinter is the only GUI framework that comes with Python. If EasyGUI
> meets your needs, why not use it?
>
> Kent
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] single key ordered sequence

2009-01-15 Thread Jervis Whitley
On Fri, Jan 16, 2009 at 4:56 AM, Senthil Kumaran wrote:

> > Also, how to practically walk in reverse order in a list without
> > copying it (e.g. items[::-1]),
> > especially if i need both indexes and items (couldn't find with
> > enumerate()).
> >
> Are you looking for reversed()?
> The way you are doing it is probably OK.
> But it can be simplified thus:
>
> keys = []
> target = []
>
> for item in reversed(items):
> if not item[0] in keys:
>keys.append(item[0])
>target.append(item)
>
> print target
>
> If this is not what you wanted,then I have misunderstood your
> requirement and just based it on your code.
>
> Thanks,
> Senthil
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>

how about this:
items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'),
(3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')]
mydict = dict(items)
items = [item for item in mydict.iteritems()]

testing shows:
C:\WINDOWS\system32\cmd.exe /c python test_time.py
**ORIGINAL**
s = """
items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'),
(3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')]
keys = []
for index in range(len(items)-1,-1,-1):
   key = items[index][0]
   if key in keys:
   items[index] = None
   else:
   keys.append(key)
items = [item for item in items if item is not None]
"""
timeit.Timer(stmt=s).timit()
5.40928835422

**Test1**
s = """
items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'),
(3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')]
keys = []
for item in reversed(items):
key = item[0]
if key in keys:
items.remove(item)
else:
keys.append(key)
#items = [item for item in items if item is not None]
"""
timeit.Timer(stmt=s).timit()
5.02896436267

**Test2**
s= """
items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'),
(3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')]
keys = dict(items)
items = [item for item in keys.iteritems()]
"""

timeit.Timer(stmt=s).timit()
3.38715506199
Hit any key to close this window...
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] single key ordered sequence

2009-01-15 Thread Kent Johnson
On Thu, Jan 15, 2009 at 3:44 PM, Jervis Whitley  wrote:
> how about this:
> items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'),
> (3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')]
> mydict = dict(items)
> items = [item for item in mydict.iteritems()]

That only coincidentally preserves order; the order of items in a
dictionary is, for practical purposes, unpredictable.

BTW [item for item in mydict.iteritems()] can be written as just mydict.items().

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


[Tutor] traceback again: __traceback__ arg for exceptions in py3.0

2009-01-15 Thread spir

I just discovered the following:

PEP 3134: Exception objects now store their traceback as the __traceback__ 
attribute. This means
that an exception object now contains all the information pertaining to an 
exception, and there
are fewer reasons to use sys.exc_info() (though the latter is not removed).

in http://docs.python.org/dev/3.0/whatsnew/3.0.html

denis

--
la vida e estranya
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] indented grammar parsing

2009-01-15 Thread Kent Johnson
On Sun, Jan 11, 2009 at 1:11 PM, spir  wrote:
> Hello,
>
> this is a rather specific question about parsing an indented grammar.
> I have a working implementation (presented below) that may be worth a critic 
> review -- if you like
> it.
>
> First issue is: is there a way to express an indented formatfing using a 
> common grammar
> language such as BNF (or regex)? If yes, how to do that? If not, what kind of 
> formal grammar is
> actually such a format? Is there any standard way to express it?
>
> I guess from this text that python parsers have a pre-parse phase that 
> generate the so-called
> INDENT and DEDENT tokens -- which are then used during actual parsing.

It's pretty common for parsers to be implemented in two phases,
lexical scanning and actual parsing. The lexical scanner recognizes
patterns in the source file and outputs a sequence of tokens. The
parser analyzes the tokens, not the actual source text. So for the
Python lexical scanner to emit INDENT and DEDENT tokens doesn't seem
that strange to me.

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


Re: [Tutor] Opsware Global Shell Scripting

2009-01-15 Thread Kayvan Sarikhani
Hello...thanks to several individuals, I've been able to get a little
farther in this Opsware global shell script:

#!/usr/bin/python
import os
outfile = open('test.txt','w')
for servername in os.listdir('/opsw/Server/@'):
print '---', servername
print >> outfile, '---', servername
rosh = 'rosh -n %s -l $LOGNAME \ date' % (servername)
os.system(rosh)
outfile.close()

This does most of what I need, but I've run into two issues.

1) After it uses the rosh command to remotely access a managed system, it
executes the "date" command...but I need to be able to direct the date
output to the outfile. I imagine it's probably going to be similar to how it
directs output of the servernames, but still not quite sure how this fits in
the scheme of this command.

2) Some connection attempts to systems just hang...not really sure why
(yet), but I'd like to be able to specify some kind of timeout so that it
executes the rosh command, and if it doesn't connect in 10 seconds, breaks
the connection, and moves on to the next server in the list. I've read that
there is some kind of a built-in timeout function, but I'm quite stumped on
this one.

If anyone has any suggestions or pointers, I'd really appreciate it. Thanks
very much!

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


Re: [Tutor] single key ordered sequence

2009-01-15 Thread Jervis Whitley
On Fri, Jan 16, 2009 at 9:15 AM, Kent Johnson  wrote:

> On Thu, Jan 15, 2009 at 3:44 PM, Jervis Whitley 
> wrote:
> > how about this:
> > items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'),
> > (3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')]
> > mydict = dict(items)
> > items = [item for item in mydict.iteritems()]
>
> That only coincidentally preserves order; the order of items in a
> dictionary is, for practical purposes, unpredictable.
>
> BTW [item for item in mydict.iteritems()] can be written as just
> mydict.items().
>
> Kent

I realise that what you have said is true, however
can you show me a case where
> items = dict(items).items()

will not preserve order? Thanks.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] running & debugging in python interactive shel

2009-01-15 Thread Che M



Date: Thu, 15 Jan 2009 12:20:45 -0600
From: sri...@gmail.com
To: pine...@hotmail.com
Subject: Re: [Tutor] running & debugging in python interactive shel
CC: tutor@python.org

On Wed, Jan 14, 2009 at 8:18 PM, Che M  wrote:







>> I'd like to add to this question and expand it:  can anyone point me to
>> a good resource on debugging *generally*? 
> The first result on "Debugger tutorial" on google sent me to this:

> http://www.cs.princeton.edu/~benjasik/gdb/gdbtut.html 

> Though it's for a specific program, it seems to have some good general 
> purpose advice. 
> Personally, I've never had the need for a debugger (maybe because I'm not 
> writing complicated 
> enough programs) - a simple "print" statement (in the right spot) tends to 
> take care of all of my 
> debugging needs.

That page didn't strike me as very helpful for my case, but thanks
anyway.  I'll Google for it, too, but just wondered if any of the
tutors here had any recommendations.  I just checked Alan Gauld's
tutorial and I see it doesn't have a debugger section (completely
understandably, as this is sort of advanced).  

I also use print statements a fair bit.  I've just heard that using
a debugger is a very useful thing and I thought maybe someone would 
have some tips here or knew of a good Python-relevant tutorial about it.

Thanks,
Che


-Wayne



_
Windows Live™: Keep your life in sync. 
http://windowslive.com/explore?ocid=TXT_TAGLM_WL_t1_allup_explore_012009
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with getting python to run from command prompt onWindows XP

2009-01-15 Thread Brian van den Broek

Kent Johnson said unto the world at 15/01/09 12:33 PM:

On Thu, Jan 15, 2009 at 11:48 AM, Brian van den Broek
 wrote:

The (recognized by me as) relevant bits of output are:
Path=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program
Files\texlive\2008\bin\win32;C:\Python26
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH

There is no subsequent Path line that might be stomping on the line shown
above.

I'm surprised that it is `Path' rather than `PATH'. Does that matter?


I don't think so, my PC has 'Path' also. I'm stumped...

Kent



Hi all,

Thanks for the further replies. As consensus seems to be there's 
nothing obvious to explain the problem, it's either going to be that 
my (relatively unsophisticated about computers) friend and I had a 
miscommunication over email or there is something at play that I won't 
be able to discern remotely.


I'll have him verify all steps again and then call `gremlins'.

Thanks for the help,

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


Re: [Tutor] single key ordered sequence

2009-01-15 Thread bob gailer

Jervis Whitley wrote:



On Fri, Jan 16, 2009 at 9:15 AM, Kent Johnson > wrote:


On Thu, Jan 15, 2009 at 3:44 PM, Jervis Whitley
mailto:jervi...@gmail.com>> wrote:
> how about this:
> items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'),
> (3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')]
> mydict = dict(items)
> items = [item for item in mydict.iteritems()]

That only coincidentally preserves order; the order of items in a
dictionary is, for practical purposes, unpredictable.

BTW [item for item in mydict.iteritems()] can be written as just
mydict.items().

Kent

I realise that what you have said is true, however 
can you show me a case where 


> items = dict(items).items()

will not preserve order? Thanks.
  

On my computer:

>>> dict((('z', 1), ('y', 2))).items()
[('y', 2), ('z', 1)]

--
Bob Gailer
Chapel Hill NC
919-636-4239
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Creating simple windows in XP

2009-01-15 Thread Alan Gauld


"Alex Krycek"  wrote

EasyGui is pretty simple, but I relying on standard tools. I liked 
how in

VB, for example, to open a dialog box you could write:

MsgBox("Text", vbOKOnly, "Title").



You mean like doing

import tkMessageBox
tkMessageBox.showinfo("Window Text", "A short message")

in Tkinter? :-)

OR

res = tkMessageBox.askokcancel("Which?", "Ready to stop?")
print res

At that level Tkinter is pretty easy too.

--
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] running & debugging in python interactive shel

2009-01-15 Thread Alan Gauld

"Che M"  wrote


tutors here had any recommendations.  I just checked Alan Gauld's
tutorial and I see it doesn't have a debugger section (completely


You need to get a copy of the paper book, it has a chapter on 
debugging,
starting with print statements and going through to the Python 
debugger
and finally the IDLE debugger - but that is only available in the 
book...


Alan G



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


Re: [Tutor] single key ordered sequence

2009-01-15 Thread Jervis Whitley
On Fri, Jan 16, 2009 at 10:39 AM, bob gailer  wrote:

> Jervis Whitley wrote:
>
>>
>>
>> On Fri, Jan 16, 2009 at 9:15 AM, Kent Johnson > ken...@tds.net>> wrote:
>>
>>On Thu, Jan 15, 2009 at 3:44 PM, Jervis Whitley
>>mailto:jervi...@gmail.com>> wrote:
>>> how about this:
>>> items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'),
>>> (3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')]
>>> mydict = dict(items)
>>> items = [item for item in mydict.iteritems()]
>>
>>That only coincidentally preserves order; the order of items in a
>>dictionary is, for practical purposes, unpredictable.
>>
>>BTW [item for item in mydict.iteritems()] can be written as just
>>mydict.items().
>>
>>Kent
>>
>> I realise that what you have said is true, however can you show me a case
>> where
>> > items = dict(items).items()
>>
>> will not preserve order? Thanks.
>>
>>
> On my computer:
>
> >>> dict((('z', 1), ('y', 2))).items()
> [('y', 2), ('z', 1)]
>
> --
> Bob Gailer
> Chapel Hill NC
> 919-636-4239
>
Same on mine, thanks.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with getting python to run from command prompt onWindows XP

2009-01-15 Thread Alan Gauld


"Brian van den Broek"  wrote 


I'll have him verify all steps again and then call `gremlins'.


One last thing to try is to get him to send a screen shot with the 
error message showing. That will prove that he is using the right 
type of console, typing the right command and reporting the 
right error!


Beyond that I think we are beaten...

Alan G

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


Re: [Tutor] tkinter canvas

2009-01-15 Thread Mr Gerard Kelly
wow, that's excellent, thanks so much.

I haven't got a clue how lambda functions work, but they seem pretty
useful, so I'll try to figure them out.

- Original Message -
From: Kent Johnson 
Date: Thursday, January 15, 2009 10:24 pm
Subject: Re: [Tutor] tkinter canvas
> On Thu, Jan 15, 2009 at 12:41 AM, Mr Gerard Kelly
>  wrote:
> 
> > I want to be able to bind these boxes to an event - so that I can 
> either> click on them, or hold the mouse cursor over them, and have 
> them change
> > color.
> 
> Here is a version of your program that binds the Enter and Leave
> events to each box and changes the box color when the mouse is over
> it:
> 
> #
> 
> from Tkinter import *
> 
> master = Tk()
> 
> numboxes=6
> 
> width=40*(numboxes+2)
> height=200
> w = Canvas(master, width=width, height=height)
> w.pack()
> 
> size=width/(numboxes+2)
> 
> box=[0]*numboxes
> 
> def enter(e, i):
>e.widget.itemconfigure(box[i], fill='red')
> 
> def leave(e, i):
>e.widget.itemconfigure(box[i], fill='blue')
> 
> for i in range(numboxes):
>box[i]=w.create_rectangle((1+i)*40, 40, (2+i)*40, height-40, 
> fill="blue")w.tag_bind(box[i], '', lambda e, i=i: 
> enter(e, i))
>w.tag_bind(box[i], '', lambda e, i=i: leave(e, i))
> 
> mainloop()
> 
> ###
> 
> The 'i=i' in the lambda is needed due to the (surprising) way that
> variables are bound to closures; without it, every event would be
> bound to the same value of i. Some explanation here:
> http://code.activestate.com/recipes/502271/
> 
> Kent
> 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] running & debugging in python interactive she

2009-01-15 Thread Jervis Whitley
On Fri, Jan 16, 2009 at 9:56 AM, Che M  wrote:

>
>
>
> >> I'd like to add to this question and expand it:  can anyone point me to
> >> a good resource on debugging *generally*?
> > The first result on "Debugger tutorial" on google sent me to this:
>
> > http://www.cs.princeton.edu/~benjasik/gdb/gdbtut.html
>
> > Though it's for a specific program, it seems to have some good general
> purpose advice.
> > Personally, I've never had the need for a debugger (maybe because I'm not
> writing complicated
> > enough programs) - a simple "print" statement (in the right spot) tends
> to take care of all of my
> > debugging needs.
>
> That page didn't strike me as very helpful for my case, but thanks
> anyway.  I'll Google for it, too, but just wondered if any of the
> tutors here had any recommendations.  I just checked Alan Gauld's
> tutorial and I see it doesn't have a debugger section (completely
> understandably, as this is sort of advanced).
>
> I also use print statements a fair bit.  I've just heard that using
> a debugger is a very useful thing and I thought maybe someone would
> have some tips here or knew of a good Python-relevant tutorial about it.
>
> Thanks,
> Che
>
>
> -Wayne
>
> I did a search for 'python pdb tutorial' and found this resource:
http://www.ferg.org/papers/debugging_in_python.html

pdb is the python debugger, this tutorial will give you more than enough to
get started.

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


[Tutor] 2 & 4 or more spaces per indentation level..

2009-01-15 Thread Eric Dorsey
Dear Pythonistas:

Working in IDLE on Windows Vista, I have one program that I set to have 2
character spacing (due to the levels of if's and while's going on -- later
my brother called this a bit of a code smell, ie. logic shouldn't go that
deep, it should be broken out into separate functions instead. Thoughts on
that are welcome to, do any of you feel logic should only go so many layers
deep?), and my editor defaults to 4 (Which I believe is the standard
according to PEP 8)
I copied some code from the 2 spacing program to another I'm writing
currently which has the default 4, and it got things kind of screwy with
spacing. I believe I've got it fixed now by manually tabbing/spacing, etc.,
but I was wondering, if this happened on a much bigger scale, or you were
say, pasting code in from some example where they used a different spacing
than you, is there a simple/good/smart way to get it all back to the 4
spacing default? Or if for example I wanted to convert my 2 spacing program
to the conventional 4?

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


[Tutor] Corpora

2009-01-15 Thread Ishan Puri
Hi,
I was wondering if anyone could tell me where I can get corpora containing 
IMs, or blogs or any internet communication? This is kind of urgent.
Thanks.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 2 & 4 or more spaces per indentation level..

2009-01-15 Thread Senthil Kumaran
On Thu, Jan 15, 2009 at 06:57:09PM -0700, Eric Dorsey wrote:
>Working in IDLE on Windows Vista, I have one program that I set to have
>2 character spacing (due to the levels of if's and while's going on --
>later my brother called this a bit of a code smell, ie. logic shouldn't
>go that deep, it should be broken out into separate functions instead.

Your brother is right. Logic should not go deep and moreover the
screen width not enough even with 2 space indentation gives a
not-so-good picture too.

>Thoughts on that are welcome to, do any of you feel logic should only
>go so many layers deep?), and my editor defaults to 4 (Which I believe
>is the standard according to PEP 8)

Thats the way to approach. Follow PEP8.

>they used a different spacing than you, is there a simple/good/smart
>way to get it all back to the 4 spacing default? Or if for example I

Rule #0 is Never mix tabs and spaces.
Rule #1 is use a standard spacing through out the code.

And when copying from a certain space-setting indentation to another,
the modular script will still work fine. You can use some global
find/replace mechanism to do suit your setting.
For eg. I remember doing :%s/\ \ /\ \ \ \ /g

OR you can also run your code through pyindent or python code
beautifier (Google for it, you might find one). But after using the
beautifier under these situations, just rely on your eyes to do a
quick check if the logic has not gone awry ( which rarely does, but
still I would believe myself more than the tool).

-- 
Senthil

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


Re: [Tutor] Corpora

2009-01-15 Thread John Fouhy
2009/1/16 Ishan Puri :
> Hi,
> I was wondering if anyone could tell me where I can get corpora
> containing IMs, or blogs or any internet communication? This is kind of
> urgent.

Have you tried the enron email dataset? http://www.cs.cmu.edu/~enron/
(google may turn up other links)

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


Re: [Tutor] Corpora

2009-01-15 Thread Senthil Kumaran
On Fri, Jan 16, 2009 at 9:11 AM, Ishan Puri  wrote:
> Hi,
> I was wondering if anyone could tell me where I can get corpora
> containing IMs, or blogs or any internet communication? This is kind of

www.google.com

And for IM's specifically, you can look at "Alice Bot" Project, the
corpus will be in structured format and you might end up using python
to parse it ( and your question becomes relevant to this list :) )

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