From idiot1 at netzero.net  Wed Oct  1 00:42:13 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Wed Oct  1 00:41:20 2003
Subject: [Tutor] Complaint about maximum recursion
In-Reply-To: <3F7A06A0.1040200@pobox.com>
References: <3F7A06A0.1040200@pobox.com>
Message-ID: <3F7A5B25.1020401@netzero.net>

well, off hand I would guess that the thing is exausting some preset limit on 
system resources, and the language kicked in to keep the computer from crashing. 
After 50 recursions, it ought to do something to terminate it! Now if it is 
definately going to terminate, and do it before the system barks and barfs, 
maybe there is a way to set the trigger level higher- or maybe this just means 
you need to go buy another stick of memory???

hmmm, I should write a recursive function in idle with no end with a printout of 
it's depth, and see how bad it gets before I have to reboot the box. Sort of a 
suicide mission, but intresting, and I got all my chores done today, so what the 
  hell...


Jonathan Hayward http://JonathansCorner.com wrote:

> My script now gets this error on starting up. What is wrong if a 50-line 
> stack trace complains about excessive recursion?
> 
> Traceback (most recent call last):
>  File "/home/jonathan/creations/software/inventions/datamine/fathersd", 
> line 3878, in ?
>    multitasking.start_oracle()
>  File "/home/jonathan/creations/software/inventions/datamine/fathersd", 
> line 2288, in start_oracle
>    server_init()
>  File "/home/jonathan/creations/software/inventions/datamine/fathersd", 
> line 3802, in server_init
>    section.get_documents(1)
>  File "/home/jonathan/creations/software/inventions/datamine/fathersd", 
> line 2614, in get_documents
>    self.possibly_include_files_from_directory, "")
>  File "/usr/lib/python2.2/posixpath.py", line 287, in walk
>    walk(name, func, arg)
>  File "/usr/lib/python2.2/posixpath.py", line 279, in walk
>    func(arg, top, names)
>  File "/home/jonathan/creations/software/inventions/datamine/fathersd", 
> line 2681, in possibly_include_files_from_directory
>    self)
>  File "/home/jonathan/creations/software/inventions/datamine/fathersd", 
> line 857, in get_document
>    return webpage(filename, section)
>  File "/home/jonathan/creations/software/inventions/datamine/fathersd", 
> line 2805, in __init__
>    document.__init__(self, filename, section)
>  File "/home/jonathan/creations/software/inventions/datamine/fathersd", 
> line 637, in __init__
>    self.process()
>  File "/home/jonathan/creations/software/inventions/datamine/fathersd", 
> line 808, in process
>    self.compute_title()
>  File "/home/jonathan/creations/software/inventions/datamine/fathersd", 
> line 2948, in compute_title
>    self.title = self.get_tag_contents("title", self.get_file_contents())
>  File "/home/jonathan/creations/software/inventions/datamine/fathersd", 
> line 763, in get_tag_contents
>    internal = self.get_tag_contents_internal(tag, file_contents)
>  File "/home/jonathan/creations/software/inventions/datamine/fathersd", 
> line 772, in get_tag_contents_internal
>    return my_re.findall(file_contents)
> RuntimeError: maximum recursion limit exceeded
> 
> 
> TIA,
> 

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Prometheus
  +                              kniht                                +

Fnord.


From idiot1 at netzero.net  Wed Oct  1 00:53:58 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Wed Oct  1 00:53:03 2003
Subject: [Tutor] rre: Recursion error
Message-ID: <3F7A5DE6.8090207@netzero.net>

Well, I tried this:

def test(count):
	print count
	count=count+1
	test(count)

and when the count got to 346, I chickened out and hit ^C, and got a HUGE error 
report  back. I will spare the list. But it went WELL past 50 recursions. Of 
course, this was a small and simple function, and did not tax the stack at all 
heavily per recursion.

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Prometheus
  +                              kniht                                +

Fnord.



From thomi at imail.net.nz  Wed Oct  1 00:56:51 2003
From: thomi at imail.net.nz (Thomi Richards)
Date: Wed Oct  1 00:56:59 2003
Subject: [Tutor] rre: Recursion error
In-Reply-To: <3F7A5DE6.8090207@netzero.net>
References: <3F7A5DE6.8090207@netzero.net>
Message-ID: <200310011656.51453.thomi@imail.net.nz>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On Wed, 01 Oct 2003 16:53, Kirk Bailey wrote:
> Well, I tried this:
>
> def test(count):
> 	print count
> 	count=count+1
> 	test(count)
>

It might also be interesting to see how long it takes between recursions, and 
graph it...hmmm... might try this on an old 486.... ; )

- -- 
Thomi Richards,
http://once.sourceforge.net/


-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.3 (GNU/Linux)

iD8DBQE/el6T2tSuYV7JfuERAp81AJ9qdx5HhQrcPGLdUzxecWIufBw4CQCePFc5
PnEdCj47ZZkBmlwcxrqSH8Y=
=0Ic4
-----END PGP SIGNATURE-----


From project5 at redrival.net  Wed Oct  1 01:43:54 2003
From: project5 at redrival.net (Andrei)
Date: Wed Oct  1 01:45:58 2003
Subject: [Tutor] Re: rre: Recursion error
In-Reply-To: <3F7A5DE6.8090207@netzero.net>
References: <3F7A5DE6.8090207@netzero.net>
Message-ID: <bldpmg$j7m$1@sea.gmane.org>

Kirk Bailey wrote:

> Well, I tried this:
> 
> def test(count):
>     print count
>     count=count+1
>     test(count)

Tried that only I do the count increase inside the function call.

> and when the count got to 346, I chickened out and hit ^C, and got a 

Got up to 984, nothing interesting happens:

983
984
Traceback (most recent call last):
   File "<input>", line 1, in ?
   File "<input>", line 3, in test

I don't have to wait at all, the traceback appears virtually instantaneously. I 
couldn't even stop it at 300 if I wanted to :). But that's in wxPython, perhaps 
Tk is slower and that's why you didn't get that far. The limit seems to be 
pretty much fixed, memory use is negligeable.

 > HUGE error report  back. I will spare the list. But it went WELL past 50
 > recursions. Of course, this was a small and simple function, and did not
 > tax the stack at all heavily per recursion.

Tried more memory consuming test too:

 >>> class X(object):
...     def __init__(self, i):
...         self.list = [10,10,10,10,10,10,10,10,10,10]*i
...
 >>> def test(i):
...     l.append(X(i))
...     print i
...     test(i+1)
...
 >>> l = []
 >>> test(0)
<snip output and traceback>
 >>> len(l[-1].list)
9850

Stops at 984 too, but eats about 22MB of mem.

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur 
yvfg, fb gurer'f ab arrq gb PP.



From krier115 at student.liu.se  Wed Oct  1 01:47:32 2003
From: krier115 at student.liu.se (Kristoffer Erlandsson)
Date: Wed Oct  1 01:47:45 2003
Subject: [Tutor] Complaint about maximum recursion
In-Reply-To: <3F7A06A0.1040200@pobox.com>
References: <3F7A06A0.1040200@pobox.com>
Message-ID: <20031001054732.GA14599@n14.ryd.student.liu.se>

On Tue, Sep 30, 2003 at 11:41:36PM +0100, Jonathan Hayward http://JonathansCorner.com wrote:
[snip]
> line 772, in get_tag_contents_internal
>    return my_re.findall(file_contents)
> RuntimeError: maximum recursion limit exceeded

The problem here is that regular expressions with non-greedy qualifiers
(*? etc) are implemented using recursion. Either try rewriting them to
greedy ones, or if you are sure you are just exceeding the limit by a
small amount you can use sys.setrecursionlimit(n) to increase the limit.
sys.getrecursionlimit() shows you the current limit. 1000 by default on
my system.

Hope this helps a bit :)

Regards,

-- 
Kristoffer Erlandsson                               http://errl.info

From mwagman at charter.net  Wed Oct  1 06:40:52 2003
From: mwagman at charter.net (Mike Wagman)
Date: Wed Oct  1 06:34:56 2003
Subject: [Tutor] Re: rre: Recursion error
In-Reply-To: <bldpmg$j7m$1@sea.gmane.org>
References: <3F7A5DE6.8090207@netzero.net>  <bldpmg$j7m$1@sea.gmane.org>
Message-ID: <1065004848.2862.1.camel@66-188-81-143.mad.wi.charter.com>


I got up to 999 then got


  File "count.py", line 4, in test
    test(count)
RuntimeError: maximum recursion depth exceeded


On Wed, 2003-10-01 at 00:43, Andrei wrote:
> Kirk Bailey wrote:
> 
> > Well, I tried this:
> > 
> > def test(count):
> >     print count
> >     count=count+1
> >     test(count)
> 
> Tried that only I do the count increase inside the function call.
> 
> > and when the count got to 346, I chickened out and hit ^C, and got a 
> 
> Got up to 984, nothing interesting happens:
> 
> 983
> 984
> Traceback (most recent call last):
>    File "<input>", line 1, in ?
>    File "<input>", line 3, in test
> 
> I don't have to wait at all, the traceback appears virtually instantaneously. I 
> couldn't even stop it at 300 if I wanted to :). But that's in wxPython, perhaps 
> Tk is slower and that's why you didn't get that far. The limit seems to be 
> pretty much fixed, memory use is negligeable.
> 
>  > HUGE error report  back. I will spare the list. But it went WELL past 50
>  > recursions. Of course, this was a small and simple function, and did not
>  > tax the stack at all heavily per recursion.
> 
> Tried more memory consuming test too:
> 
>  >>> class X(object):
> ...     def __init__(self, i):
> ...         self.list = [10,10,10,10,10,10,10,10,10,10]*i
> ...
>  >>> def test(i):
> ...     l.append(X(i))
> ...     print i
> ...     test(i+1)
> ...
>  >>> l = []
>  >>> test(0)
> <snip output and traceback>
>  >>> len(l[-1].list)
> 9850
> 
> Stops at 984 too, but eats about 22MB of mem.


From amk at amk.ca  Wed Oct  1 07:38:27 2003
From: amk at amk.ca (amk@amk.ca)
Date: Wed Oct  1 07:38:33 2003
Subject: [Tutor] Complaint about maximum recursion
In-Reply-To: <20031001054732.GA14599@n14.ryd.student.liu.se>
References: <3F7A06A0.1040200@pobox.com>
	<20031001054732.GA14599@n14.ryd.student.liu.se>
Message-ID: <20031001113827.GA24069@rogue.amk.ca>

On Wed, Oct 01, 2003 at 07:47:32AM +0200, Kristoffer Erlandsson wrote:
> greedy ones, or if you are sure you are just exceeding the limit by a
> small amount you can use sys.setrecursionlimit(n) to increase the limit.

No, this won't work.  sys.setrecursionlimit() sets how deep Python code can
recurse.  The recursion inside the regex engine is in C code, and it uses a
hard-wired limit (USE_RECURSION_LIMIT, set to 10000 on most platforms.

--amk

From ajstec at bol.com.br  Wed Oct  1 11:35:17 2003
From: ajstec at bol.com.br (ajstec)
Date: Wed Oct  1 11:41:18 2003
Subject: [Tutor] insert in postgresql
Message-ID: <HM34MT$8D8AEAAAAFDCBCA82DB47C988ABF5CA5@bol.com.br>

Hi all,

    I am using pypgsql, and try :

>>> a='cat'
>>> b='dog'
>>> db.query("insert into curso values
(default,"%(a)","%(b)")")
SyntaxError: invalid syntax

Howto ?

It? (Bye) !

Adilton Silva
Recife - Brasil
 
__________________________________________________________________________
Acabe com aquelas janelinhas que pulam na sua tela.
AntiPop-up UOL - ? gr?tis!
http://antipopup.uol.com.br/



From godoy at metalab.unc.edu  Wed Oct  1 11:49:49 2003
From: godoy at metalab.unc.edu (Jorge Godoy)
Date: Wed Oct  1 11:50:26 2003
Subject: [Tutor] insert in postgresql
In-Reply-To: <HM34MT$8D8AEAAAAFDCBCA82DB47C988ABF5CA5@bol.com.br>
	(ajstec@bol.com.br's message of "Wed,  1 Oct 2003 15:35:17 +0000")
References: <HM34MT$8D8AEAAAAFDCBCA82DB47C988ABF5CA5@bol.com.br>
Message-ID: <m3u16tc602.fsf@ieee.org>

"ajstec" <ajstec@bol.com.br> writes:

> Hi all,
>
>     I am using pypgsql, and try :
>
>>>> a='cat'
>>>> b='dog'
>>>> db.query("insert into curso values
> (default,"%(a)","%(b)")")
> SyntaxError: invalid syntax
>
> Howto ?
>
> It? (Bye) !

Ol? Adilton. :-) Muito calor por a??


You statement is wrong 'cause you're mixing the quotes.

Try it like that:

db.query("insert into curso values (default, %s, %s)" % (a, b))

If I got it correctly and 'default' is also a value and not a variable
name. 


See you,
-- 
Godoy.     <godoy@metalab.unc.edu>

From bgailer at alum.rpi.edu  Wed Oct  1 11:46:50 2003
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Wed Oct  1 12:13:19 2003
Subject: [Tutor] Efficient way to join files
In-Reply-To: <3F7A3067.1000409@telgua.com.gt>
References: <3F7A3067.1000409@telgua.com.gt>
Message-ID: <6.0.0.22.0.20031001093312.04a8b4e8@66.28.54.253>

At 07:39 PM 9/30/2003, H?ctor Villafuerte D. wrote:

>Hi all,
>I need to join multiple files.
>Is there a more efficient way to do it than using
>fileinput.input(file) and looping through those files?
>Thanks in advance,

On Windows? os.popen("copy sourcefile1 + sourcefile2 + ... 
destinationfile").read()

Bob Gailer
bgailer@alum.rpi.edu
303 442 2625
-------------- next part --------------

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.521 / Virus Database: 319 - Release Date: 9/23/2003
From pythontutor at venix.com  Wed Oct  1 12:19:30 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Wed Oct  1 12:19:35 2003
Subject: [Tutor] conversion confusion
In-Reply-To: <CA3458C84C976E45B6372A6C14724C9F326021@ridmsem02.nala.roche.com>
References: <CA3458C84C976E45B6372A6C14724C9F326021@ridmsem02.nala.roche.com>
Message-ID: <3F7AFE92.7030603@venix.com>

int(value2add,16) requires that value2add be a string with characters
from the set: 0123456789abcdefABCDEF
It won't work with any old string, such as 'm'.

The CRC equation doesn't work with strings, it works with integers.  To turn
a single character into its integer representation, python provides the ord
function.
CRCval = ord('m') ^ int(seed,16)

You shouldn't need any hex values within your processing.  Having said that,
to turn the hex string '6d' into an integer, you'd use the int function:
int('6d',16) which equals 109
ord('m') also equals 109

If you want to post the problem code, we can probably help.  I'd expect your
code should look something like:
	input_char = serial.get_a_character()	# I made up the function name
	CRCval = ord(input_char) ^ int(seed,16)
	print "input_char(hex): %x   CRC(hex): %x" % (input_char, CRCval)


One other point.  Your device documentation may show stuff in terms of
C programming code.  In C, 'm' is actually an integer not a string.  So
a C programmer can write:
	'n' - 'm'
and get a result of 1.  In python, we'd write:
	ord('n') - ord('m')
and also get 1.

Hope this helps.  Try giving us a code snippet if necessary.

Stanfield, Vicki {D167~Indianapolis} wrote:

> Well, I still can't get this to work right. It works fine when the value2add is a small number, but when it is an 'm' or some other letter, it doesn't work. If I fake it out and send the 'm' as a string representation of its hex value ('6d'), it will work. So the problem must be that after I hexlify the 'm', it is numeric rather than a string which is what the equation which follows wants.
> 
> CRCval=int(value2add,16) ^ int(seed,16)
> 
> How does one turn a hex number 6d into a string so that the equation will happily take it? I may be going about things strangely, but the value comes in as an 'm' and needs to be a string '6d'. How do I get from one to the other?
> 
> --vicki
> 
> P.S. I apologize if I am being dense here; some parts of this come easy and some with great difficulty.
> 
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582


From hec.villafuerte at telgua.com.gt  Wed Oct  1 14:58:29 2003
From: hec.villafuerte at telgua.com.gt (=?ISO-8859-1?Q?=22H=E9ctor_Villafuerte_D=2E=22?=)
Date: Wed Oct  1 12:58:15 2003
Subject: [Tutor] Efficient way to join files
In-Reply-To: <6.0.0.22.0.20031001093312.04a8b4e8@66.28.54.253>
References: <3F7A3067.1000409@telgua.com.gt>
	<6.0.0.22.0.20031001093312.04a8b4e8@66.28.54.253>
Message-ID: <3F7B23D5.9010606@telgua.com.gt>

Bob Gailer wrote:

> On Windows? os.popen("copy sourcefile1 + sourcefile2 + ... 
> destinationfile").read()

hmmm, interesting... what a nice way to call DOS commands...
Yes, I'm currently working in Windows, but I would like to make
my code as platform independent as possible (I also use Linux...
actually it's my favourite OS! but that's another story...)
Thanks for your suggestions!


From ajstec at bol.com.br  Wed Oct  1 13:02:46 2003
From: ajstec at bol.com.br (ajstec)
Date: Wed Oct  1 13:02:51 2003
Subject: [Tutor] insert in postgresql
Message-ID: <HM38OM$D5CC0D93F6D2E1478F10635D7452E942@bol.com.br>

---------- In?cio da mensagem original -----------

      De: tutor-bounces@python.org
    Para: &quot;ajstec&quot; ajstec@bol.com.br
      Cc: &quot;tutor&quot; tutor@python.org
    Data: Wed, 01 Oct 2003 12:49:49 -0300
 Assunto: Re: [Tutor] insert in postgresql

> "ajstec" <ajstec@bol.com.br> writes:
> 
> > Hi all,
> >
> >     I am using pypgsql, and try :
> >
> >>>> a='cat'
> >>>> b='dog'
> >>>> db.query("insert into curso values
> > (default,"%(a)","%(b)")")
> > SyntaxError: invalid syntax
> >
> > Howto ?
> >
> > It? (Bye) !
> 
> Ol? Adilton. :-) Muito calor por a??
> 
> 
> You statement is wrong 'cause you're mixing the quotes.
> 
> Try it like that:
> 
> db.query("insert into curso values (default, %s, %s)"
% (a, b))
> 
> If I got it correctly and 'default' is also a value
and not a variable
> name. 
> 
> 
> See you,
> -- 
> Godoy.     <godoy@metalab.unc.edu>
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor


Oi,  :-) s? 31 graus

I tried diverse formats but ...

db.query("insert into curso values (default,%s,%s)"%(a,b))
Traceback (most recent call last):
  File "<pyshell#58>", line 1, in ?
    db.query("insert into curso values
(default,%s,%s)"%(a,b))
_pg.error: ERROR:  Attribute "cat" not found


Voc? ? brasileiro ?

 
 
__________________________________________________________________________
Acabe com aquelas janelinhas que pulam na sua tela.
AntiPop-up UOL - ? gr?tis!
http://antipopup.uol.com.br/



From jeff at ccvcorp.com  Wed Oct  1 13:25:10 2003
From: jeff at ccvcorp.com (Jeff Shannon)
Date: Wed Oct  1 13:21:32 2003
Subject: [Tutor] Efficient way to join files
References: <3F7A3067.1000409@telgua.com.gt>
	<6.0.0.22.0.20031001093312.04a8b4e8@66.28.54.253>
Message-ID: <3F7B0DF6.1020809@ccvcorp.com>

Bob Gailer wrote:
> At 07:39 PM 9/30/2003, H?ctor Villafuerte D. wrote:
> 
>> Hi all,
>> I need to join multiple files.
>> Is there a more efficient way to do it than using
>> fileinput.input(file) and looping through those files?
>> Thanks in advance,
> 
> 
> On Windows? os.popen("copy sourcefile1 + sourcefile2 + ... 
> destinationfile").read()

I think that it would be a bit of a stretch to call this "more 
efficient", at least if one thinks at all about the implementation of 
this code.  (Maybe this just depends on one's definition of 
"efficiency"...)

You are proposing, here, to get the OS to read all the files and 
append them to another (new) file, and then read in the new file. 
That's, at a minimum, an extra hard drive read and hard drive write 
for each of those files.  Using fileinput, or otherwise looping 
through a list of files, doesn't do that.  This solution may take 
fewer lines of code, but LoC count isn't necessarily related to real 
efficiency in any meaningful way.

I would also say that it's more clear to state, in code, "take this 
list of files and process them one at a time, with this procedure..." 
than to state "Get someone else to collect all of these files and copy 
them into a new one, and then take that new file and do this..."

It is simplest to write a procedure that pretends to be dealing with 
only a single file, to be sure.  However, I think that the correct 
abstraction is to have a function that is passed a single file, and 
that deals with multiple files by getting them passed to it in 
sequence, rather than to write something that handles multiple files 
by squeezing them all together into an undifferentiated mass.

Jeff Shannon
Technician/Programmer
Credit International


From dyoo at hkn.eecs.berkeley.edu  Wed Oct  1 14:05:57 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Oct  1 14:06:10 2003
Subject: [Tutor] Complaint about maximum recursion
In-Reply-To: <20031001054732.GA14599@n14.ryd.student.liu.se>
Message-ID: <Pine.LNX.4.44.0310011100330.2034-100000@hkn.eecs.berkeley.edu>



On Wed, 1 Oct 2003, Kristoffer Erlandsson wrote:

> On Tue, Sep 30, 2003 at 11:41:36PM +0100, Jonathan Hayward http://JonathansCorner.com wrote:
> [snip]
> > line 772, in get_tag_contents_internal
> >    return my_re.findall(file_contents)
> > RuntimeError: maximum recursion limit exceeded
>
> The problem here is that regular expressions with non-greedy qualifiers
> (*? etc) are implemented using recursion. Either try rewriting them to
> greedy ones, or if you are sure you are just exceeding the limit by a
> small amount you can use sys.setrecursionlimit(n) to increase the limit.
> sys.getrecursionlimit() shows you the current limit. 1000 by default on
> my system.

Hi Jonathan,


Yes, I agree with Kristoffer --- it looks like the regular expression is
causing the recursion to overflow.  It's a known problem:

    http://www.python.org/doc/current/lib/node108.html

that occurs with nongreedy matching (*?).  But in Python 2.3, the regular
expression engine adjusted to handle certain situations in a way that
won't break.

Can you try using Python 2.3 and see if that clears up the problem?


From dyoo at hkn.eecs.berkeley.edu  Wed Oct  1 14:17:59 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Oct  1 14:18:06 2003
Subject: [Tutor] Efficient way to join files
In-Reply-To: <6.0.0.22.0.20031001093312.04a8b4e8@66.28.54.253>
Message-ID: <Pine.LNX.4.44.0310011107080.2034-100000@hkn.eecs.berkeley.edu>



On Wed, 1 Oct 2003, Bob Gailer wrote:

> At 07:39 PM 9/30/2003, H=E9ctor Villafuerte D. wrote:
>
> >I need to join multiple files.

Hi Hector,


Do you need to do this physically, or can you just use an iterator on
multiple files?  If you can use an iterator, then the 'itertools' module
will be useful:

    http://www.python.org/doc/current/lib/itertools-functions.html


In particular, we can "chain" files together by doing something like
this:

###
"""A small 'cat'-like utility that takes files from the command line,
and prints them all."""
import itertools
import sys
files =3D map(open, sys.argv[1:])
all_files =3D itertools.chain(*files)
for line in all_files:
    sys.stdout.write(line)
###


But that being said, the 'fileinput' module does something like this
already with its input() function!  *grin*  According to:

    http://www.python.org/doc/current/lib/module-fileinput.html

fileinput.input() can take in a list of files.  We can recode the above
as:


###
#!/usr/local/bin/python
"""A small 'cat'-like utility that takes files from the command line,
and prints them all."""
import fileinput
import sys
all_files =3D fileinput.input(sys.argv[1:])
for line in all_files:
    sys.stdout.write(line)
###



Please feel free to ask more questions.  Good luck to you!


From hec.villafuerte at telgua.com.gt  Wed Oct  1 16:21:59 2003
From: hec.villafuerte at telgua.com.gt (=?ISO-8859-1?Q?=22H=E9ctor_Villafuerte_D=2E=22?=)
Date: Wed Oct  1 14:21:44 2003
Subject: [Tutor] Efficient way to join files
In-Reply-To: <3F7B0DF6.1020809@ccvcorp.com>
References: <3F7A3067.1000409@telgua.com.gt>	<6.0.0.22.0.20031001093312.04a8b4e8@66.28.54.253>
	<3F7B0DF6.1020809@ccvcorp.com>
Message-ID: <3F7B3767.1020907@telgua.com.gt>


Jeff Shannon wrote:

> Bob Gailer wrote:
>
>> On Windows? os.popen("copy sourcefile1 + sourcefile2 + ... 
>> destinationfile").read()
>
>
> I think that it would be a bit of a stretch to call this "more 
> efficient", at least if one thinks at all about the implementation of 
> this code.  (Maybe this just depends on one's definition of 
> "efficiency"...)
>
> You are proposing, here, to get the OS to read all the files and 
> append them to another (new) file, and then read in the new file. 
> That's, at a minimum, an extra hard drive read and hard drive write 
> for each of those files.  Using fileinput, or otherwise looping 
> through a list of files, doesn't do that.  This solution may take 
> fewer lines of code, but LoC count isn't necessarily related to real 
> efficiency in any meaningful way.
>
> I would also say that it's more clear to state, in code, "take this 
> list of files and process them one at a time, with this procedure..." 
> than to state "Get someone else to collect all of these files and copy 
> them into a new one, and then take that new file and do this..."
>
> It is simplest to write a procedure that pretends to be dealing with 
> only a single file, to be sure.  However, I think that the correct 
> abstraction is to have a function that is passed a single file, and 
> that deals with multiple files by getting them passed to it in 
> sequence, rather than to write something that handles multiple files 
> by squeezing them all together into an undifferentiated mass.


I was reading that there is a Python Profiler! I'll take a look at it 
and post which method resulted "more efficient".
This language is really nice! Pardon my excitement, but before Python I 
only knew C/C++, assembler for PIC's and VB (which I
didn't like) This is my second week with python and I have a strong 
feeling that this relationship will be a long one ;)


From missive at hotmail.com  Wed Oct  1 17:50:28 2003
From: missive at hotmail.com (Lee Harr)
Date: Wed Oct  1 17:50:34 2003
Subject: [Tutor] Re: insert in postgresql
Message-ID: <BAY2-F62ELXGR0FsFX400005077@hotmail.com>

>>>a='cat'
>>>b='dog'
>>>db.query("insert into curso values
(default,"%(a)","%(b)")")^M
SyntaxError: invalid syntax



In python, the single(') and double(") quotes are interchangeable,
and either one can be used to make a triple(""") quote. This is
useful, because a single quote string can contain double quotes
and vice versa. A triple quoted string can contain either one.

I would do it like this:

a = 'cat'
b = 'dog'
q = """insert into cursor values (default '%(a)s', '%(b)s')""" % vars()

db.query(q)


One nice thing about triple quotes is that they can contain newlines:

q = """

INSERT INTO
    cursor
    (foo,
    bar,
    baz)

VALUES
    (default,
    '%(a)s',
    '%(b)s')

""" % vars()


Note that it is always a good idea to include the fields you are inserting
into just in case your db structure changes in the future.

_________________________________________________________________
Tired of spam? Get advanced junk mail protection with MSN 8. 
http://join.msn.com/?page=features/junkmail


From amonroe at columbus.rr.com  Wed Oct  1 19:52:59 2003
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Wed Oct  1 19:53:08 2003
Subject: [Tutor] mailing list archive reader
In-Reply-To: <BAY2-F5593XhQtqoo1g00031da6@hotmail.com>
References: <BAY2-F5593XhQtqoo1g00031da6@hotmail.com>
Message-ID: <39359930883.20031001195259@columbus.rr.com>

> is there a program that can read the mailing list archives from a
> local flie and format them like the online options (ie date, thread,
> author). i downloaded each months archies but the seem to be huge
> flat files with alot of repition for threads. i looked into mailman

Check out www.gmane.org

You can read the mailing list with a newsreader.

Alan


From godoy at metalab.unc.edu  Wed Oct  1 22:34:47 2003
From: godoy at metalab.unc.edu (Jorge Godoy)
Date: Wed Oct  1 22:35:19 2003
Subject: [Tutor] insert in postgresql
In-Reply-To: <HM38OM$D5CC0D93F6D2E1478F10635D7452E942@bol.com.br>
	(ajstec@bol.com.br's message of "Wed,  1 Oct 2003 17:02:46 +0000")
References: <HM38OM$D5CC0D93F6D2E1478F10635D7452E942@bol.com.br>
Message-ID: <m3isn8cqpk.fsf@ieee.org>

"ajstec" <ajstec@bol.com.br> writes:

> Oi,  :-) s? 31 graus

Bem mais quente que em Curitiba. 

> I tried diverse formats but ...
>
> db.query("insert into curso values (default,%s,%s)"%(a,b))
> Traceback (most recent call last):
>   File "<pyshell#58>", line 1, in ?
>     db.query("insert into curso values
> (default,%s,%s)"%(a,b))
> _pg.error: ERROR:  Attribute "cat" not found
> 

See that you have a '^M' char there. You've probably pressed ENTER in
the middle of the string. To use newlines you have to use triple
quotes (either single or double quotes). 

An example was provided in a previous message.

> Voc? ? brasileiro ?

Yes, I'm Brazilian. :-) Living in the South, though. :-) 

-- 
Godoy.     <godoy@metalab.unc.edu>

From ronan at melim.com.br  Thu Oct  2 16:52:12 2003
From: ronan at melim.com.br (Ronan Lucio)
Date: Thu Oct  2 16:51:10 2003
Subject: [Tutor] Copy files
Message-ID: <200310021752.12721.ronan@melim.com.br>

Hello,

Is there some python function to make a copy of a file?

I'd like to do it as with a native function like os.unlink,
os.mkdir, but I'm not finding a function that do it.

Thanks
Ronan

From project5 at redrival.net  Thu Oct  2 17:09:54 2003
From: project5 at redrival.net (Andrei)
Date: Thu Oct  2 17:10:56 2003
Subject: [Tutor] Re: Copy files
In-Reply-To: <200310021752.12721.ronan@melim.com.br>
References: <200310021752.12721.ronan@melim.com.br>
Message-ID: <bli48q$elp$1@sea.gmane.org>

> Is there some python function to make a copy of a file?
> 
> I'd like to do it as with a native function like os.unlink,
> os.mkdir, but I'm not finding a function that do it.

Look at the shutil module.

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur 
yvfg, fb gurer'f ab arrq gb PP.



From Christian.Zandbergen at swisslife.ch  Fri Oct  3 06:09:59 2003
From: Christian.Zandbergen at swisslife.ch (Zandbergen Christian)
Date: Fri Oct  3 06:10:07 2003
Subject: [Tutor] Window pathnames
Message-ID: <109179A1E3D9D511BEEF00D0B7D4912401BA26C9@ns9875.swisslife.ch>

Hi

I try to open a file with python 2.1.3 (deployed with Zope)

and the following Error occures:


	Python 2.1.3 (#35, Apr  8 2002, 17:47:50) [MSC 32 bit (Intel)] on
win32
	Type "copyright", "credits" or "license" for more information.
	>>> open("C:\\dslfjsl\jlsfjslfsj")
	Traceback (most recent call last):
	  File "<stdin>", line 1, in ?
	IOError: [Errno 2] No such file or directory:
'C:\\dslfjsl\\jlsfjslfsj'


It seems that one backslash always returns a double backslash.



With Python 2.3 it's OK. But since I want it to used in conjunction with
Zope I have to stick to Python 2.1.3 or not ......

Christian


From gerrit at nl.linux.org  Fri Oct  3 06:12:05 2003
From: gerrit at nl.linux.org (Gerrit Holl)
Date: Fri Oct  3 06:12:24 2003
Subject: [Tutor] Window pathnames
In-Reply-To: <109179A1E3D9D511BEEF00D0B7D4912401BA26C9@ns9875.swisslife.ch>
References: <109179A1E3D9D511BEEF00D0B7D4912401BA26C9@ns9875.swisslife.ch>
Message-ID: <20031003101205.GA24665@nl.linux.org>

<quote name="Zandbergen Christian" date="1065179399" email="Christian.Zandbergen@swisslife.ch">
> and the following Error occures:
> 
> 	Python 2.1.3 (#35, Apr  8 2002, 17:47:50) [MSC 32 bit (Intel)] on
> win32
> 	Type "copyright", "credits" or "license" for more information.
> 	>>> open("C:\\dslfjsl\jlsfjslfsj")
> 	Traceback (most recent call last):
> 	  File "<stdin>", line 1, in ?
> 	IOError: [Errno 2] No such file or directory:
> 'C:\\dslfjsl\\jlsfjslfsj'
> 
> 
> It seems that one backslash always returns a double backslash.
</quote>

Have you tried to prepend the string with 'r' (e.g. r'C:\aaa\bbb')?

Gerrit.

-- 
Mozilla _is_ the web: it grows faster than you can download it.
1011001 1101111 1110101 1110010 1110011 0101100
1000111 1100101 1110010 1110010 1101001 1110100

From project5 at redrival.net  Fri Oct  3 06:19:31 2003
From: project5 at redrival.net (Andrei)
Date: Fri Oct  3 06:21:36 2003
Subject: [Tutor] Re: Window pathnames
In-Reply-To: <20031003101205.GA24665@nl.linux.org>
References: <109179A1E3D9D511BEEF00D0B7D4912401BA26C9@ns9875.swisslife.ch>
	<20031003101205.GA24665@nl.linux.org>
Message-ID: <bljij9$ca9$1@sea.gmane.org>

Gerrit Holl wrote:
> <quote name="Zandbergen Christian" date="1065179399" email="Christian.Zandbergen@swisslife.ch">
> 
>>and the following Error occures:
>>
>>	Python 2.1.3 (#35, Apr  8 2002, 17:47:50) [MSC 32 bit (Intel)] on
>>win32
>>	Type "copyright", "credits" or "license" for more information.
>>	>>> open("C:\\dslfjsl\jlsfjslfsj")
>>	Traceback (most recent call last):
>>	  File "<stdin>", line 1, in ?
>>	IOError: [Errno 2] No such file or directory:
>>'C:\\dslfjsl\\jlsfjslfsj'
>>
>>
>>It seems that one backslash always returns a double backslash.
> 
> </quote>
> 
> Have you tried to prepend the string with 'r' (e.g. r'C:\aaa\bbb')?

Raw strings in path are not the best idea: if the path happens to end with "\", 
you may not notice it in your editor, but you'll get a syntax error because the 
backslash escapes the end quote. Especially a problem if you don't code the path 
yourself, but it's provided programmatically or by the user. I know because I 
made this error :). It would be better to just use forward slashes - works under 
Windows too.

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur 
yvfg, fb gurer'f ab arrq gb PP.



From ronan at melim.com.br  Fri Oct  3 08:28:14 2003
From: ronan at melim.com.br (Ronan Lucio)
Date: Fri Oct  3 08:27:11 2003
Subject: [Tutor] Re: Copy files
In-Reply-To: <bli48q$elp$1@sea.gmane.org>
References: <200310021752.12721.ronan@melim.com.br>
	<bli48q$elp$1@sea.gmane.org>
Message-ID: <200310030928.14780.ronan@melim.com.br>

Em Qui 02 Out 2003 18:09, Andrei escreveu:
> > Is there some python function to make a copy of a file?
> >
> > I'd like to do it as with a native function like os.unlink,
> > os.mkdir, but I'm not finding a function that do it.
>
> Look at the shutil module.

Great!!
Thank you very much Andrei.

Ronan

From pythontutor at venix.com  Fri Oct  3 11:49:34 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Fri Oct  3 11:49:41 2003
Subject: [Tutor] http return status when using urllib
Message-ID: <3F7D9A8E.3040308@venix.com>

I used urllib to post some data to a site and could not find any easy way
to determine the HTTP status.  When I supplied a deliberately wrong URL
I simply got back the Apache error page with no real indication that
a problem occurred.  I, of course, could read the error message, but
there was no simple mechanism for the script to know it had failed.

urllib2 raises an exception and includes attributes:
	code and msg
in the exception which reflect the HTTP status line.  Obviously,
the exception is enough to alert the script that a problem occurred.

There was no discussion of error handling in "Python in a Nutshell",
"Python Standard Library", or the module docs.  I read through the
urllib source code and the module clearly goes to extra lengths to
prevent an exception.  (Yes, I can override this behavior by
writing my own class.)

Am I missing something in my approach?  Does anyone know the
rationale for hiding errors (and the status code)?

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582


From glingl at aon.at  Fri Oct  3 16:03:48 2003
From: glingl at aon.at (Gregor Lingl)
Date: Fri Oct  3 16:05:39 2003
Subject: [Tutor] friday night entertainment (a generator)
Message-ID: <3F7DD624.50907@aon.at>

Hi,

I just wrote a generator which generates
all the r-permutations of n distict objects,
(this most probably is an old soup, newly cooked up -
or a wheel reinvented):

def perms(n,r,result=()):
    if r == 0:
        yield result
    for element in n:
        t = n[:]
        t.remove(element)
        for perm in perms(t,r-1,result+(element,)):
            yield perm
           
 >>> for p in perms(range(4),2):
    print p

   
(0, 1)
(0, 2)
(0, 3)
(1, 0)
(1, 2)
(1, 3)
(2, 0)
(2, 1)
(2, 3)
(3, 0)
(3, 1)
(3, 2)
 >>>

Do any amendments (concerning efficiency and/or elegance)
come to your mind?

Any hints or suggestions are highly appreciated

Gregor



From jeff at ccvcorp.com  Fri Oct  3 17:24:46 2003
From: jeff at ccvcorp.com (Jeff Shannon)
Date: Fri Oct  3 17:21:11 2003
Subject: [Tutor] Window pathnames
References: <109179A1E3D9D511BEEF00D0B7D4912401BA26C9@ns9875.swisslife.ch>
Message-ID: <3F7DE91E.8080806@ccvcorp.com>

Zandbergen Christian wrote:

> 	>>> open("C:\\dslfjsl\jlsfjslfsj")
> 	Traceback (most recent call last):
> 	  File "<stdin>", line 1, in ?
> 	IOError: [Errno 2] No such file or directory:
> 'C:\\dslfjsl\\jlsfjslfsj'
> 
> 
> It seems that one backslash always returns a double backslash.

That's not quite true.  Try typing in a directory name that starts 
with a 't', for example (like "c:\\stuff\temp"), and you won't get a 
double backslash in the error message -- but you might see an 
indication of why all this happens.

'\t' isn't really a backslash and a 't', as Python sees it -- instead, 
it's a single TAB character (ascii code 0x09).  So the string I showed 
above is interpreted by Python as meaning "c:\stuff[TAB]emp".  There's 
a variety of these nonprintable characters, and they're accessed by 
using a backslash to "escape" the following character -- a backslash 
in a string says "Treat the next character special", and then the next 
character indicates *what* to do.

So how do you get a backslash, then, if it means to treat the next 
character as something special?  Well, you make the next character 
another backslash, and the "special" handling in this case is to just 
print it as it is.  When Python is displaying a string using repr() 
(as error tracebacks do), it shows escape sequences as they would be 
typed; thus, a string containing a (single) backslash will be 
displayed by repr() by using two backslashes.

Now, not all characters indicate something special when escaped.  For 
instance, '\j' has no special meaning.  So Python reads that as two 
separate characters, a backslash and a 'j', when you type it in. 
However, when it displays backslashes, it doubles them (so that you 
don't mistake them for part of an escape code).  That's what's 
happening in your error message.

Jeff Shannon
Technician/Programmer
Credit International


From thomi at imail.net.nz  Fri Oct  3 20:10:01 2003
From: thomi at imail.net.nz (Thomi Richards)
Date: Fri Oct  3 20:10:01 2003
Subject: [Tutor] pointers for python?
Message-ID: <200310041210.01431.thomi@imail.net.nz>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1


Hi all,

In C, you can modify a variable from within a seperate function, by passing a 
pointer to that function. Is there any way to do this in python? it'd be 
kinda useful ;)

I'm sure i read it in the tutorial a while back, but searching the same 
tutorials now, I can't seem to find it anywhere... any ideas?

to clarify, currently, this:

def inc(x):
	x+=1

a=1
inc(a)
print a

prints "1"

is there a way to get the inc() function to modify the original variable, even 
though it's not in the function's scope?


THanks,

- -- 
Thomi Richards,
http://once.sourceforge.net/


-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.3 (GNU/Linux)

iD8DBQE/fg/Z2tSuYV7JfuERAi0jAJ0WsGXRMBGcuUhaVNR2yx7gdWRCnQCgiqce
KED+ZlWXIc+qxewJMdEG+uc=
=o6XS
-----END PGP SIGNATURE-----


From peterabrown at froggy.com.au  Fri Oct  3 20:36:34 2003
From: peterabrown at froggy.com.au (Peter Brown)
Date: Fri Oct  3 20:36:23 2003
Subject: [Tutor] pointers for python?
In-Reply-To: <200310041210.01431.thomi@imail.net.nz>
Message-ID: <3.0.6.32.20031004103634.009f9900@mail.froggy.com.au>

I'm only new to python but this works

>>> def inc(x):
	global y
	y = x + 1
	return y

>>> a  = 1
>>> inc(a)
2
>>> 

Peter

At 12:10 4/10/2003 +1200, you wrote:
>-----BEGIN PGP SIGNED MESSAGE-----
>Hash: SHA1
>
>
>Hi all,
>
>In C, you can modify a variable from within a seperate function, by
passing a 
>pointer to that function. Is there any way to do this in python? it'd be 
>kinda useful ;)
>
>I'm sure i read it in the tutorial a while back, but searching the same 
>tutorials now, I can't seem to find it anywhere... any ideas?
>
>to clarify, currently, this:
>
>def inc(x):
>	x+=1
>
>a=1
>inc(a)
>print a
>
>prints "1"
>
>is there a way to get the inc() function to modify the original variable,
even 
>though it's not in the function's scope?
>
>
>THanks,
>
>- -- 
>Thomi Richards,
>http://once.sourceforge.net/
>
>
>-----BEGIN PGP SIGNATURE-----
>Version: GnuPG v1.2.3 (GNU/Linux)
>
>iD8DBQE/fg/Z2tSuYV7JfuERAi0jAJ0WsGXRMBGcuUhaVNR2yx7gdWRCnQCgiqce
>KED+ZlWXIc+qxewJMdEG+uc=
>=o6XS
>-----END PGP SIGNATURE-----
>
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>


From op73418 at mail.telepac.pt  Fri Oct  3 21:28:01 2003
From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=)
Date: Fri Oct  3 21:26:37 2003
Subject: [Tutor] pointers for python?
In-Reply-To: <200310041210.01431.thomi@imail.net.nz>
References: <200310041210.01431.thomi@imail.net.nz>
Message-ID: <6b8snv8odh9ve1n9a8n9v9anff5g758o4d@4ax.com>

On Sat, 4 Oct 2003 12:10:01 +1200, you wrote:

>-----BEGIN PGP SIGNED MESSAGE-----
>Hash: SHA1
>
>
>Hi all,
>
>In C, you can modify a variable from within a seperate function, by passing a 
>pointer to that function. Is there any way to do this in python? it'd be 
>kinda useful ;)
>
>I'm sure i read it in the tutorial a while back, but searching the same 
>tutorials now, I can't seem to find it anywhere... any ideas?
>
>to clarify, currently, this:
>
>def inc(x):
>	x+=1
>
>a=1
>inc(a)
>print a
>
>prints "1"
>
>is there a way to get the inc() function to modify the original variable, even 
>though it's not in the function's scope?
>

Why not the perfectly Pythonic solution

>>> def inc(x):
... 	return x + 1
... 
>>> a = 1
>>> a = inc(a)
>>> a
2

It even has no side effects - the function that is.

With my best regards,
G. Rodrigues

From idiot1 at netzero.net  Fri Oct  3 21:44:21 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Fri Oct  3 21:54:06 2003
Subject: [Tutor] RE: re
Message-ID: <3F7E25F5.10102@netzero.net>

Regarding re (regular expressions):

%#$^^&*$^@$@!

I am fustrated. I want a function to return a list or a string which is a 
WikiWord split into words, with the split occuring at the Capitalized word.

So if I feed it the word ThisIsAWikiWord, it can give me back:
'This Is A Wiki Word'
*OR*
['This','Is','A','Wiki','Word']

Well, I got THIS far...
 >>> def wordsplit(word):
	return re.split('[A-Z]+',word)

 >>> wordsplit(word)
['', 'ary', 'ad', 'ittle', 'amb']
 >>> word
'MaryHadALittleLamb'
 >>>

Please advise. 'Text Processing in Python' is good, but the RE chapter is not as 
transparent as I would hope. Clue eagerly saught.

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Prometheus
  +                              kniht                                +

Fnord.




From python at rcn.com  Fri Oct  3 22:07:11 2003
From: python at rcn.com (Raymond Hettinger)
Date: Fri Oct  3 22:07:40 2003
Subject: [Tutor] RE: re
In-Reply-To: <3F7E25F5.10102@netzero.net>
Message-ID: <001301c38a1c$396a6fe0$e841fea9@oemcomputer>

Try this:

    re.split('([A-Z][a-z]*)',word)[1:-1]

The clue is in the docs for re.split() which say, "If capturing
parentheses are used in pattern, then the text of all groups in the
pattern are also returned as part of the resulting list".

Raymond Hettinger

-----Original Message-----
From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On
Behalf Of Kirk Bailey
Sent: Friday, October 03, 2003 9:44 PM
To: Tutor
Subject: [Tutor] RE: re

Regarding re (regular expressions):

%#$^^&*$^@$@!

I am fustrated. I want a function to return a list or a string which is
a 
WikiWord split into words, with the split occuring at the Capitalized
word.

So if I feed it the word ThisIsAWikiWord, it can give me back:
'This Is A Wiki Word'
*OR*
['This','Is','A','Wiki','Word']

Well, I got THIS far...
 >>> def wordsplit(word):
	return re.split('[A-Z]+',word)

 >>> wordsplit(word)
['', 'ary', 'ad', 'ittle', 'amb']
 >>> word
'MaryHadALittleLamb'
 >>>

Please advise. 'Text Processing in Python' is good, but the RE chapter
is not as 
transparent as I would hope. Clue eagerly saught.

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Prometheus
  +                              kniht                                +

Fnord.




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


#################################################################
#################################################################
#################################################################
#####
#####
#####
#################################################################
#################################################################
#################################################################

From amonroe at columbus.rr.com  Fri Oct  3 23:13:02 2003
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Fri Oct  3 23:13:08 2003
Subject: [Tutor] Size of any arbitrary object in bytes?
In-Reply-To: <001301c38a1c$396a6fe0$e841fea9@oemcomputer>
References: <001301c38a1c$396a6fe0$e841fea9@oemcomputer>
Message-ID: <19699236584.20031003231302@columbus.rr.com>

Is there a way to find the size of any arbitrary object (list,
dictionary, possibly nested) in bytes, without resorting to recursion?

I was playing with sqlite again, and the __len__ function of the
result set seems to tell me number of records returned, rather than
the physical RAM bytes consumed by the result set.

Alan


From op73418 at mail.telepac.pt  Sat Oct  4 07:36:32 2003
From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=)
Date: Sat Oct  4 07:35:10 2003
Subject: [Tutor] pointers for python?
In-Reply-To: <200310041429.14843.thomi@imail.net.nz>
References: <200310041210.01431.thomi@imail.net.nz>
	<6b8snv8odh9ve1n9a8n9v9anff5g758o4d@4ax.com>
	<200310041429.14843.thomi@imail.net.nz>
Message-ID: <qcbtnv844qji7m8bl8mfvtrths5ocuifrm@4ax.com>

On Sat, 4 Oct 2003 14:29:14 +1200, you wrote:

>-----BEGIN PGP SIGNED MESSAGE-----
>Hash: SHA1
>
>On Sat, 04 Oct 2003 13:28, Gon?alo Rodrigues wrote:
>>
>> Why not the perfectly Pythonic solution
>>
>> >>> def inc(x):
>>
>> ... 	return x + 1
>> ...
>>
>> >>> a = 1
>> >>> a = inc(a)
>> >>> a
>
>
>I waned to do it without having to return a variable.... If it can't be done. 
>that's fine, but i was hoping to be able to do it without a "return"....

P. Brown in another reply gave you another answer involving the global
keyword -- but it's ugly and unpythonic IMHO and it only works for
global names (e.g. module-level). Right now I can't remember of any
other solution -- and I suspect any such would involve some dangerous
hackery.

Maybe the question should be: why do you want to write C code in
Python? In Python, variables are just names referencing an object
(said to be binded (bounded?) to that object). The line above

a = inc(a)

just rebinds the name "a" to whatever inc(a) returns. In C, a variable
is more of a placeholder -- a real location in memory -- that's why
you need, or at least one of the reasons why you need, all those
tricks with pass-by-reference and whatnot. So I repeat my question:

Why do you want to write C code in Python?

YMMV, but wouldn't it be better just trying to get in the Pythonic
mindset? 

With my best regards,
G. Rodrigues

From thomi at imail.net.nz  Sat Oct  4 08:06:25 2003
From: thomi at imail.net.nz (Thomi Richards)
Date: Sat Oct  4 08:06:25 2003
Subject: [Tutor] pointers for python?
In-Reply-To: <qcbtnv844qji7m8bl8mfvtrths5ocuifrm@4ax.com>
References: <200310041210.01431.thomi@imail.net.nz>
	<200310041429.14843.thomi@imail.net.nz>
	<qcbtnv844qji7m8bl8mfvtrths5ocuifrm@4ax.com>
Message-ID: <200310050006.27441.thomi@imail.net.nz>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

>
> Why do you want to write C code in Python?
>
It was more for experimentation than anything else. I guess i *can* do 
anything with a return statement. I was playing with GUI toolkits in both C 
and python (the same toolkit as it turns out), and was looking at the ways 
the different languages did things.

> YMMV, but wouldn't it be better just trying to get in the Pythonic
> mindset?

Probably ;)

Thanks for your help ;)

- -- 
Thomi Richards,
http://once.sourceforge.net/


-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.3 (GNU/Linux)

iD4DBQE/frfD2tSuYV7JfuERAiDnAKCUoIphhm2X9EgKjb0WGnSKvPMdEgCXe5Fh
Qj1UxURKex4JVgqF0VnSbw==
=Rbob
-----END PGP SIGNATURE-----


From pythontutor at venix.com  Sat Oct  4 12:17:29 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Sat Oct  4 12:17:41 2003
Subject: [Tutor] friday night entertainment (a generator)
In-Reply-To: <3F7DD624.50907@aon.at>
References: <3F7DD624.50907@aon.at>
Message-ID: <3F7EF299.7010909@venix.com>

One hidden bug, if passed an r of 0, but n is not empty, the
script continues to iterate through the list elements with negative r's.
These do no produce results so you won't notice unless you put a print
statement into the function.  I added:
     print "n,r,result",n,r,result
at the top and got these results:
n,r,result (1, 2, 3, 4) 2 ()
n,r,result [2, 3, 4] 1 (1,)
n,r,result [3, 4] 0 (1, 2)
(1, 2)
n,r,result [4] -1 (1, 2, 3)
n,r,result [] -2 (1, 2, 3, 4)
n,r,result [3] -1 (1, 2, 4)
n,r,result [] -2 (1, 2, 4, 3)
n,r,result [2, 4] 0 (1, 3)
(1, 3)
n,r,result [4] -1 (1, 3, 2)
<clipped>

Here's your updated code with two other minor changes:
	force r to a reasonable value
	force t to be a list in the case that n is a tuple

from __future__ import generators
def perms(n,r,result=()):
     #print "n,r,result",n,r,result
     r = max(0, min(r, len(n)))  # r ranges from 0 to len(n)
                                 # change to raise an exception if you prefer
     if r == 0:
         yield result
     else:
         for element in n:
             t = list(n[:])      # n could be a tuple
             t.remove(element)
             for perm in perms(t,r-1,result+(element,)):
                 yield perm

if __name__ == '__main__':
     n = (1,2,3,4)
     for p in perms(n,0):
         print p
     for p in perms(n,2):
         print p


Hope this helps.

Gregor Lingl wrote:

> Hi,
> 
> I just wrote a generator which generates
> all the r-permutations of n distict objects,
> (this most probably is an old soup, newly cooked up -
> or a wheel reinvented):
> 
> def perms(n,r,result=()):
>    if r == 0:
>        yield result
>    for element in n:
>        t = n[:]
>        t.remove(element)
>        for perm in perms(t,r-1,result+(element,)):
>            yield perm
>           >>> for p in perms(range(4),2):
>    print p
> 
>   (0, 1)
> (0, 2)
> (0, 3)
> (1, 0)
> (1, 2)
> (1, 3)
> (2, 0)
> (2, 1)
> (2, 3)
> (3, 0)
> (3, 1)
> (3, 2)
>  >>>
> 
> Do any amendments (concerning efficiency and/or elegance)
> come to your mind?
> 
> Any hints or suggestions are highly appreciated
> 
> Gregor
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582


From jim_938 at hotmail.com  Sat Oct  4 12:35:44 2003
From: jim_938 at hotmail.com (Jimmy verma)
Date: Sat Oct  4 12:35:48 2003
Subject: [Tutor] pack module
Message-ID: <Sea1-F171VhYAUTsmSW0000a86e@hotmail.com>

Hello,

Can someone please give me some idea about the pack module. I have tried to 
read it from the documentation. But not clear about it.
Statements like pack('>L',0)

Where > indicates the endienness.

I will highly appriciate any kind of suggestion regarding pack.

Thanks in advance.

Regards,

James

_________________________________________________________________
Three simple steps. They guarantee your safety. 
http://server1.msn.co.in/features/general/SMBvirus/index.asp Protect 
yourself against the SMB.EXE virus.


From kalle at lysator.liu.se  Sat Oct  4 13:15:38 2003
From: kalle at lysator.liu.se (Kalle Svensson)
Date: Sat Oct  4 13:15:43 2003
Subject: [Tutor] pointers for python?
In-Reply-To: <qcbtnv844qji7m8bl8mfvtrths5ocuifrm@4ax.com>
References: <200310041210.01431.thomi@imail.net.nz>
	<6b8snv8odh9ve1n9a8n9v9anff5g758o4d@4ax.com>
	<200310041429.14843.thomi@imail.net.nz>
	<qcbtnv844qji7m8bl8mfvtrths5ocuifrm@4ax.com>
Message-ID: <20031004171538.GK9058@i92.ryd.student.liu.se>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

[Gon?alo Rodrigues on modifying function parameters]
> P. Brown in another reply gave you another answer involving the
> global keyword -- but it's ugly and unpythonic IMHO and it only
> works for global names (e.g. module-level). Right now I can't
> remember of any other solution -- and I suspect any such would
> involve some dangerous hackery.

Using some kind of mutable object to wrap the argument is one way to
get (most of) the desired behaviour.  Example:

>>> def inc(x):
...     x[0] += 1
... 
>>> a = [0]
>>> inc(a)
>>> a[0]
1

Something similar but better looking could probably be created by
defining a class.  Remember that the assignment operator can't be
used, though.  In code such as

  def set2(x):
      x[0] = 2

what looks as a variable assignment is really an item assignment.

Peace,
  Kalle
- -- 
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.7 (GNU/Linux)
Comment: Processed by Mailcrypt 3.5.6 <http://mailcrypt.sourceforge.net/>

iD8DBQE/fwAadNeA1787sd0RAss7AJ9X/ZGCakZys9BvgNKMUGxI1wvu+ACdHVxT
2zFcNFTlpRZh47RTBRuERAA=
=L2LE
-----END PGP SIGNATURE-----

From python at dhumketu.cjb.net  Sat Oct  4 11:51:51 2003
From: python at dhumketu.cjb.net (Shantanoo Mahajan)
Date: Sat Oct  4 13:50:54 2003
Subject: [Tutor] Re: Project Parallelport
In-Reply-To: <20030930111330.GC6822@liposerv.bluecher>
References: <20030930111330.GC6822@liposerv.bluecher>
Message-ID: <20031004155151.GA300@dhumketu.homeunix.net>

+-- Vadim Usenko [python-tutor] [30-09-03 16:43 IST]:
| Hi all,
| 
| I am searching for a module in python to connect a programm directly  
| with the parallel port to build a mini-crossway with some traffic  
| lights.
| Do you have some information for me, please?

	pyParallel is a module which will allow you
	communicate with parallel port
| 
| Thanks,
| 
| Vadim
| 
| 
| 
| ------------------------------

-- 
With Best Regards,
Shantanoo Mahajan

From pythontutor at venix.com  Sat Oct  4 14:25:05 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Sat Oct  4 14:26:16 2003
Subject: [Tutor] pack function
In-Reply-To: <Sea1-F171VhYAUTsmSW0000a86e@hotmail.com>
References: <Sea1-F171VhYAUTsmSW0000a86e@hotmail.com>
Message-ID: <3F7F1081.40209@venix.com>

(pack is actually in the struct module.)
This module allows you to manipulate binary data structures that typically
map to C structs, hence the name.  The binary structure for things like
integers will vary based upon the processor and system architecture.

On an Intel X86 processor the bytes that make up an integer are stored with
the least significant byte first (little endian) while many other processors
would store the most significant byte first (big endian).  This is very much
analogous to languages that read right-to-left versus left-to-right.

I've used struct to handle things like dBase files that have header information
that was (presumably) written from a C struct and specifies things like
record size, number of fields, and field names.

You need to know the specs for your target to know the right thing to do.  If
your target is a C program on the same kind of system, then Native, which is
the default, should generally do the right thing.  "Python in a Nutshell" has
a good description of struct, but it is not so very different from the module
documentation.

Jimmy verma wrote:

> Hello,
> 
> Can someone please give me some idea about the pack module. I have tried 
> to read it from the documentation. But not clear about it.
> Statements like pack('>L',0)
> 
> Where > indicates the endienness.
> 
> I will highly appriciate any kind of suggestion regarding pack.
> 
> Thanks in advance.
> 
> Regards,
> 
> James
> 
> _________________________________________________________________
> Three simple steps. They guarantee your safety. 
> http://server1.msn.co.in/features/general/SMBvirus/index.asp Protect 
> yourself against the SMB.EXE virus.
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582


From guillermo.fernandez at epfl.ch  Sat Oct  4 16:15:45 2003
From: guillermo.fernandez at epfl.ch (Guillermo Fernandez)
Date: Sat Oct  4 16:15:56 2003
Subject: [Tutor] global variables
Message-ID: <3F7F2A71.3060703@epfl.ch>


Hi,

Appended is a module I've written to interface to a sqlite database. My problem 
is I would like to make 'module variables' to address the database and cursor 
without passing them as arguments to the functions. I've done it with 'global', 
but:
1) I don't really get the global concept.
2) I feel there must be a cleaner way of doing it.

Furthermore, I don't understand why I can address clientmacs, apnames and ipaps 
  inside a function without making them global while I can't with the database, 
cursor and id variable.

If you have any explanation, advice or document I could read, I would be 
grateful to know it.

Thanks!

Guille


************************************************************
CODE:


#--- Imports
import sqlite       #Sqlite database interface, Python DB API 2.0 compatible


#--- Database

global database
global cursor
global id

# TODO: This is immediate operations, must implement security checks!
def open(databasename):
     """Open or create the database and prepares a cursor to operate"""
     global database
     global cursor
     global id
     database=sqlite.connect(databasename)
     cursor=database.cursor()

def create():
     """Create the database tables"""
     global database
     global cursor
     global id
     id=1
     cursor.execute('CREATE TABLE logs(id VARCHAR(10) PRIMARY KEY,\
                                         log VARCHAR(400),\
                                         mmonth VARCHAR(20),\
                                         mday VARCHAR(10),\
                                         mhour VARCHAR(10),\
                                         apname VARCHAR(50),\
                                         ipap VARCHAR(20),\
                                         messagenumber VARCHAR(20),\
                                         apmessage VARCHAR(300),\
                                         year VARCHAR(10),\
                                         apmonth VARCHAR(20),\
                                         apday VARCHAR(10),\
                                         aphour VARCHAR(10),\
                                         messagecode VARCHAR(20),\
                                         message VARCHAR(160),\
                                         clientname VARCHAR(50),\
                                         clientmac VARCHAR(20),\
                                         messageexplanation VARCHAR(200))')
     cursor.execute('CREATE TABLE clientmacs(clientmac VARCHAR(20))')
     cursor.execute('CREATE TABLE apnames(apname VARCHAR(200))')
     cursor.execute('CREATE TABLE ipaps(ipap VARCHAR(20))')


def execute(query):
     """Executes a query that *do not need* a commit over the database"""
     global database
     global cursor
     global id

     cursor.execute(query)
     return cursor.fetchall()

variables=['mmonth', 'mday', 'mhour', 'apname',
             'ipap', 'messagenumber', 'apmessage', 'year',
             'apmonth', 'apday', 'aphour', 'messagecode', 'message',
             'clientname', 'clientmac', 'messageexplanation']

clientmacs=[]
apnames=[]
ipaps=[]
def addentry(parser):
     """Inserts an entry to the database"""

     global database
     global cursor
     global id
     SQLbegin="INSERT INTO logs (id, log, mmonth, mday, mhour, apname, ipap,\
                                 messagenumber, apmessage, year, apmonth,\
                                 apday, aphour, messagecode, message,\
                                 clientname, clientmac, messageexplanation)\
                 VALUES ( '"+str(id)+"', '"
     id+=1
     SQLend="')"
     query=SQLbegin+parser.group(0)+"', '"
     for i in variables:
         query=query+str(parser.group(i))+"', '"
     query=query[:-4]+SQLend
     cursor.execute(query)
    # We make lists with all relevant data
     if parser.group('clientmac') not in clientmacs:
         query="INSERT INTO clientmacs (clientmac) VALUES ('"+\
             parser.group('clientmac')+SQLend
         cursor.execute(query)
         clientmacs.append(parser.group('clientmac'))
     if parser.group('apname') not in apnames:
         query="INSERT INTO apnames (apname) VALUES ('"+\
             parser.group('apname')+SQLend
         cursor.execute(query)
         clientmacs.append(parser.group('apname'))
     if parser.group('ipap') not in ipaps:
         query="INSERT INTO ipaps (ipap) VALUES ('"+\
             parser.group('ipap')+SQLend
         cursor.execute(query)
         clientmacs.append(parser.group('ipap'))


def close():
     """Closes the database"""

     global database
     global cursor
     global id
     id=1
     cursor.close()
     database.commit()
     database.close()



From guillermo.fernandez at epfl.ch  Sat Oct  4 16:15:59 2003
From: guillermo.fernandez at epfl.ch (Guillermo Fernandez)
Date: Sat Oct  4 16:16:13 2003
Subject: [Tutor] global variables
Message-ID: <3F7F2A7F.1020800@epfl.ch>


Hi,

Appended is a module I've written to interface to a sqlite database. My problem 
is I would like to make 'module variables' to address the database and cursor 
without passing them as arguments to the functions. I've done it with 'global', 
but:
1) I don't really get the global concept.
2) I feel there must be a cleaner way of doing it.

Furthermore, I don't understand why I can address clientmacs, apnames and ipaps 
  inside a function without making them global while I can't with the database, 
cursor and id variable.

If you have any explanation, advice or document I could read, I would be 
grateful to know it.

Thanks!

Guille


************************************************************
CODE:


#--- Imports
import sqlite       #Sqlite database interface, Python DB API 2.0 compatible


#--- Database

global database
global cursor
global id

# TODO: This is immediate operations, must implement security checks!
def open(databasename):
     """Open or create the database and prepares a cursor to operate"""
     global database
     global cursor
     global id
     database=sqlite.connect(databasename)
     cursor=database.cursor()

def create():
     """Create the database tables"""
     global database
     global cursor
     global id
     id=1
     cursor.execute('CREATE TABLE logs(id VARCHAR(10) PRIMARY KEY,\
                                         log VARCHAR(400),\
                                         mmonth VARCHAR(20),\
                                         mday VARCHAR(10),\
                                         mhour VARCHAR(10),\
                                         apname VARCHAR(50),\
                                         ipap VARCHAR(20),\
                                         messagenumber VARCHAR(20),\
                                         apmessage VARCHAR(300),\
                                         year VARCHAR(10),\
                                         apmonth VARCHAR(20),\
                                         apday VARCHAR(10),\
                                         aphour VARCHAR(10),\
                                         messagecode VARCHAR(20),\
                                         message VARCHAR(160),\
                                         clientname VARCHAR(50),\
                                         clientmac VARCHAR(20),\
                                         messageexplanation VARCHAR(200))')
     cursor.execute('CREATE TABLE clientmacs(clientmac VARCHAR(20))')
     cursor.execute('CREATE TABLE apnames(apname VARCHAR(200))')
     cursor.execute('CREATE TABLE ipaps(ipap VARCHAR(20))')


def execute(query):
     """Executes a query that *do not need* a commit over the database"""
     global database
     global cursor
     global id

     cursor.execute(query)
     return cursor.fetchall()

variables=['mmonth', 'mday', 'mhour', 'apname',
             'ipap', 'messagenumber', 'apmessage', 'year',
             'apmonth', 'apday', 'aphour', 'messagecode', 'message',
             'clientname', 'clientmac', 'messageexplanation']

clientmacs=[]
apnames=[]
ipaps=[]
def addentry(parser):
     """Inserts an entry to the database"""

     global database
     global cursor
     global id
     SQLbegin="INSERT INTO logs (id, log, mmonth, mday, mhour, apname, ipap,\
                                 messagenumber, apmessage, year, apmonth,\
                                 apday, aphour, messagecode, message,\
                                 clientname, clientmac, messageexplanation)\
                 VALUES ( '"+str(id)+"', '"
     id+=1
     SQLend="')"
     query=SQLbegin+parser.group(0)+"', '"
     for i in variables:
         query=query+str(parser.group(i))+"', '"
     query=query[:-4]+SQLend
     cursor.execute(query)
    # We make lists with all relevant data
     if parser.group('clientmac') not in clientmacs:
         query="INSERT INTO clientmacs (clientmac) VALUES ('"+\
             parser.group('clientmac')+SQLend
         cursor.execute(query)
         clientmacs.append(parser.group('clientmac'))
     if parser.group('apname') not in apnames:
         query="INSERT INTO apnames (apname) VALUES ('"+\
             parser.group('apname')+SQLend
         cursor.execute(query)
         clientmacs.append(parser.group('apname'))
     if parser.group('ipap') not in ipaps:
         query="INSERT INTO ipaps (ipap) VALUES ('"+\
             parser.group('ipap')+SQLend
         cursor.execute(query)
         clientmacs.append(parser.group('ipap'))


def close():
     """Closes the database"""

     global database
     global cursor
     global id
     id=1
     cursor.close()
     database.commit()
     database.close()



From glingl at aon.at  Sat Oct  4 16:58:48 2003
From: glingl at aon.at (Gregor Lingl)
Date: Sat Oct  4 17:00:38 2003
Subject: [Tutor] friday night entertainment (a generator)
In-Reply-To: <3F7EF299.7010909@venix.com>
References: <3F7DD624.50907@aon.at> <3F7EF299.7010909@venix.com>
Message-ID: <3F7F3488.8010309@aon.at>



Lloyd Kvam schrieb:

> One hidden bug, if passed an r of 0, but n is not empty, the
> ....
>
> Here's your updated code with two other minor changes:
>     force r to a reasonable value
>     force t to be a list in the case that n is a tuple

Thanks for your valuable comments. You pointed out a really
bad mistake. It came from transforming an ordinary function
with return statements into a generator. I overlooked that a
yield statement doesn't terminate the execution of a function/
generator. Have to be more careful next time.

Regards,

Gregor

>
> from __future__ import generators
> def perms(n,r,result=()):
>     #print "n,r,result",n,r,result
>     r = max(0, min(r, len(n)))  # r ranges from 0 to len(n)
>                                 # change to raise an exception if you 
> prefer
>     if r == 0:
>         yield result
>     else:
>         for element in n:
>             t = list(n[:])      # n could be a tuple
>             t.remove(element)
>             for perm in perms(t,r-1,result+(element,)):
>                 yield perm
>
> if __name__ == '__main__':
>     n = (1,2,3,4)
>     for p in perms(n,0):
>         print p
>     for p in perms(n,2):
>         print p
>
>
> Hope this helps. 


It did!


From alan.gauld at blueyonder.co.uk  Sat Oct  4 19:00:16 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Sat Oct  4 18:59:33 2003
Subject: [Tutor] pointers for python?
References: <200310041210.01431.thomi@imail.net.nz><6b8snv8odh9ve1n9a8n9v9anff5g758o4d@4ax.com><200310041429.14843.thomi@imail.net.nz>
	<qcbtnv844qji7m8bl8mfvtrths5ocuifrm@4ax.com>
Message-ID: <00dc01c38acb$47037930$6401a8c0@xp>

>> Why not the perfectly Pythonic solution
>>
>> >>> def inc(x):
>> ... return x + 1
>> ...
>
>I waned to do it without having to return a variable.... If it can't
be done.
>that's fine, but i was hoping to be able to do it without a
"return"....

Can you say why? The return method is by far the best technique,
its safe and makes the function reusable - it doesn't rely on a
variable called x existing somewhere. Its "the right way" to do it.

Using globals is possible but extremely bad practice and should be
avoided.




P. Brown in another reply gave you another answer involving the global
keyword -- but it's ugly and unpythonic IMHO and it only works for
global names (e.g. module-level). Right now I can't remember of any
other solution -- and I suspect any such would involve some dangerous
hackery.

Maybe the question should be: why do you want to write C code in
Python? In Python, variables are just names referencing an object
(said to be binded (bounded?) to that object). The line above

a = inc(a)

just rebinds the name "a" to whatever inc(a) returns. In C, a variable
is more of a placeholder -- a real location in memory -- that's why
you need, or at least one of the reasons why you need, all those
tricks with pass-by-reference and whatnot. So I repeat my question:

Why do you want to write C code in Python?

YMMV, but wouldn't it be better just trying to get in the Pythonic
mindset?

With my best regards,
G. Rodrigues




From thomi at imail.net.nz  Sat Oct  4 18:18:09 2003
From: thomi at imail.net.nz (Thomi Richards)
Date: Sat Oct  4 19:18:06 2003
Subject: [Tutor] pointers for python?
In-Reply-To: <00dc01c38acb$47037930$6401a8c0@xp>
References: <200310041210.01431.thomi@imail.net.nz>
	<qcbtnv844qji7m8bl8mfvtrths5ocuifrm@4ax.com>
	<00dc01c38acb$47037930$6401a8c0@xp>
Message-ID: <200310051118.09631.thomi@imail.net.nz>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

> Can you say why? The return method is by far the best technique,
> its safe and makes the function reusable - it doesn't rely on a
> variable called x existing somewhere. Its "the right way" to do it.

well, (for example), supposing you had a situation where a function was passed 
3 variables ("A", "B", and "C"). A is an empty pygtk Table element, B is a 
list of strings.

under C, you'd have to pass a pointer to A in order to modify it, correct? It 
just seemed neater doing someting like this:

table = gtk.Table(3,2,gtk.FALSE)
fill_table(table,["Label 1 text","label 2 text","Label 3 text"])

than something like this:
table = fill_table(gtk.table,["Label 1 text","label 2 text","Label 3 text"])

but that's just me ;)

As i said in an earlier mail, the question was purely one of discovery, which 
arose when comparing C++ and python code ;)
>
> Using globals is possible but extremely bad practice and should be
> avoided.
>
aye...
>

Thanks,

- -- 
Thomi Richards,
http://once.sourceforge.net/


-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.3 (GNU/Linux)

iD8DBQE/f0ch2tSuYV7JfuERAo70AJ9XzovN7Bks2pQwW88Sms5PEHzvqACdEQxP
EFvu57W/1AOyzfgGKsTT34s=
=GlW4
-----END PGP SIGNATURE-----


From idiot1 at netzero.net  Sun Oct  5 11:21:59 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Sun Oct  5 11:20:59 2003
Subject: [Tutor] Classes and the like...
In-Reply-To: <003001c37f92$79eb91a0$6401a8c0@xp>
References: <200309160039.19484.intatia@paradise.net.nz><002f01c37e32$435f00b0$6401a8c0@xp>	<200309201356.22820.intatia@paradise.net.nz>
	<003001c37f92$79eb91a0$6401a8c0@xp>
Message-ID: <3F803717.5050304@netzero.net>



Alan Gauld wrote:

>>Object? What's an object? 
> 
> 

This any help?
http://www.tinylist.org/cgi-bin/wikinehesa.py/ObjectOriented

BTW, the OOP series of pages in the wiki could use contributions and additional 
pages. Anyone at all intrested, click and jump in.


> :-)
> 
> 
>>Any ideas on a fairly simple project I could do next?
> 
> 
> THe ones I always use when trying out a new OO language 
> for the first time are:
> 
> 1) A Hello World program using a message object
> 
> Initialise it with no parameters it prints Hello World.
> Initialise it with a string parameter and it prints the string.
> Change the text attribute and it prints the new value.
> 
> 2) A switch. It can have state ON or OFF. You can Set it 
> to ON or OFF. It can tell you its state.
> 
> 3) A Toggle switch inheriting from the switch above.
> It only has 1 extra method which Toggles the state to 
> the opposite of whatever its current state is.
> 
> 4) A bank of switches that I can manipulate(to tst polymorphism)
> 
> Thats it, after doing that I usually have a good feel of basic 
> OO programming in whatever language it is.
> 
> Alan G.
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Prometheus
  +                              kniht                                +

Fnord.


From idiot1 at netzero.net  Sun Oct  5 11:27:25 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Sun Oct  5 11:26:23 2003
Subject: [Tutor] bug hunt
Message-ID: <3F80385D.6050104@netzero.net>

The servers do not respect ssi includes. Yet the modules list code to handle 
such, although I am not up to speed enough to debug them. As this is defined in 
the modules, I have the qurious duty to repport a possible bug in the 
cgiHTTPServer.py module.

Also, it does not know what to do with the standard .shtml extension, and 
confuses the browser.

Whom should I contact on this matter?
Again, here is the basic cgiserver script:


#!C:\Python22\pythonw.exe
# COPYRIGHT 2003 Steve Holden, free for personal use.
# Please visit http://www.holdenweb.com/ to learn more!
#
import CGIHTTPServer, BaseHTTPServer, os
os.chdir ('.\web')	# make the web directory current
httpd=BaseHTTPServer.HTTPServer(('',8080), CGIHTTPServer.CGIHTTPRequestHandler)
httpd.serve_forever()
#

It  handles regular HTML fine, and cgi, and .html files without a glitch.


-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Prometheus
  +                              kniht                                +

Fnord.



From tbstep at tampabay.rr.com  Sun Oct  5 13:17:35 2003
From: tbstep at tampabay.rr.com (Todd Stephens)
Date: Sun Oct  5 13:21:47 2003
Subject: [Tutor] Recursion confusion
Message-ID: <200310051317.35183.tbstep@tampabay.rr.com>

I am trying to learn Python better (and programming in general) and have 
come across something that I am having trouble getting my head around.  
Can someone tell me if my understanding of recursion is correct here?

>>> def factorial(n):
...   if n==0:
...     return 1
...   else:
...     return n*factorial(n-1)

>>> factorial(3)
6

So, what is going on here is this:
3 results in the function returning 3* the result of factorial(2), which 
results in 2 * the result of factorial(1), which results in 1 * the 
result of factorial(0) which results in 1.  So, we have 1*1*2*3.  Now, 
if I were to omit the first condition of n==0, I would get infinite 
recursion, correct?  So, along those lines, for recursion to work, I 
have to include some sort of conditional terminator.  Is that correct?  
If so, I guess I finally understand it (somewhat anyway :-))

-- 
Todd Stephens
"Good people do not need laws to tell them to act responsibly, 
while bad people will find a way around the laws." - Plato


From erikprice at mac.com  Sun Oct  5 14:09:11 2003
From: erikprice at mac.com (Erik Price)
Date: Sun Oct  5 13:47:16 2003
Subject: [Tutor] Recursion confusion
In-Reply-To: <200310051317.35183.tbstep@tampabay.rr.com>
Message-ID: <05556BC3-F75F-11D7-868C-00039351FE6A@mac.com>


On Sunday, October 5, 2003, at 01:17  PM, Todd Stephens wrote:

> Can someone tell me if my understanding of recursion is correct here?
>
>>>> def factorial(n):
> ...   if n==0:
> ...     return 1
> ...   else:
> ...     return n*factorial(n-1)
>
>>>> factorial(3)
> 6
>
> So, what is going on here is this:
> 3 results in the function returning 3* the result of factorial(2), 
> which
> results in 2 * the result of factorial(1), which results in 1 * the
> result of factorial(0) which results in 1.  So, we have 1*1*2*3.  Now,
> if I were to omit the first condition of n==0, I would get infinite
> recursion, correct?  So, along those lines, for recursion to work, I
> have to include some sort of conditional terminator.  Is that correct?
> If so, I guess I finally understand it (somewhat anyway :-))


That is all correct.




Erik


From sigurd at 12move.de  Sun Oct  5 14:19:44 2003
From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Sun Oct  5 14:25:13 2003
Subject: [Tutor] Recursion confusion
In-Reply-To: <200310051317.35183.tbstep@tampabay.rr.com> (Todd Stephens's
	message of "Sun, 5 Oct 2003 13:17:35 -0400")
References: <200310051317.35183.tbstep@tampabay.rr.com>
Message-ID: <m3brsvwo7r.fsf@hamster.pflaesterer.de>

On  5 Oct 2003, Todd Stephens <- tbstep@tampabay.rr.com wrote:

[...]
> So, what is going on here is this:
> 3 results in the function returning 3* the result of factorial(2), which 
> results in 2 * the result of factorial(1), which results in 1 * the 
> result of factorial(0) which results in 1.  So, we have 1*1*2*3.  Now, 
> if I were to omit the first condition of n==0, I would get infinite 
> recursion, correct?  So, along those lines, for recursion to work, I 

Yes.

> have to include some sort of conditional terminator.  Is that correct?  

Yes.  Never ever forget that.

> If so, I guess I finally understand it (somewhat anyway :-))

Fine.

But don't rely too much on recursion in Python.  Too deep recursion will
cause Python to complain.  Try factorial(999) with your code.  Python
does nothing like eg. Scheme which can optimize recursive algorithms
where the recursive function call is in tail position (the last function
call in the caller).  Better use an iterative version here.
(You could increase the maximal recursion depth in Python but than the
error would occur only later; I am not sure at the moment but I think
stackless Python does not have this problem).


   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


From wolf_binary at hotmail.com  Sun Oct  5 14:57:04 2003
From: wolf_binary at hotmail.com (Cameron Stoner)
Date: Sun Oct  5 14:57:08 2003
Subject: [Tutor] TCP/IP versions
Message-ID: <Law15-F35yvqSgnpvI400009ca9@hotmail.com>

I was going through the socket programming documentation and wanted to know 
what the differences in general are from IPv4 to IPv6?

Thanks,

Cameron

_________________________________________________________________
Help protect your PC.  Get a FREE computer virus scan online from McAfee. 
http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963


From mjekl at clix.pt  Sun Oct  5 16:15:07 2003
From: mjekl at clix.pt (mjekl@clix.pt)
Date: Sun Oct  5 16:13:27 2003
Subject: [Tutor] function local var problem :-((
Message-ID: <E1A6FFp-0003Ie-L4@mail.python.org>

Hi,

I'm new here and with programming. I've been learning on my own and cannot
understand what happens with this function I created.

The function is in it's own module that I import into shell.

###### module1.py ######

def printHierarchy(objecto, printList=[]):
   """Prints a class hierarchy given an object.
      Works only with single inheritance hierarchies."""

   if objecto.__class__.__bases__:
      printList.append(objecto.__class__.__name__)
      recurObjecto = objecto.__class__.__bases__[0]()
      return printHierarchy(recurObjecto, printList)
   else:
      printList.append(objecto.__class__.__name__)

      if not objecto.__class__.__bases__:
	 i = 0
	 for klass in printList:
	    print i * ' ' + klass
	    i += 1
      else:
	 return printList

####################

in shell I created a hierarchy of three classes:
class Sup; class Sub1(Sup); class Sub2(Sub1)

Then:
>>> oSub2 = Sub2()
>>> printHierarchy(oSub2)
Sup
   Sub1
      Sub2
>>>

The problem is that if I call the function again I get:
>>> printHierarchy(oSub2)
Sup
   Sub1
      Sub2
	 Sup
	    Sub1
	       Sub2
>>>

The problem to me is that I think that the var printList is local and that
it is initialized every time the function is called. But results contradict
this assumption. So I tried to investigate the namespaces and found no
references to var printList. I guess my investigation is bad (In shell I
issued dir() and dir(module1)
and got nothing. Also tried to use:
 from module1 import printHierarchy
But didn't work either. Can someone please help me?

Python 2.2 winXP

Txs,
Miguel

Clix Rapidix - Aumente até 6X a velocidade da sua Internet
Adira em http://acesso.clix.pt e comece logo a navegar

From amk at amk.ca  Sun Oct  5 16:28:35 2003
From: amk at amk.ca (A.M. Kuchling)
Date: Sun Oct  5 16:28:16 2003
Subject: [Tutor] TCP/IP versions
In-Reply-To: <Law15-F35yvqSgnpvI400009ca9@hotmail.com>
Message-ID: <7E8E471B-F772-11D7-933C-0003931BF218@amk.ca>

On Sunday, October 5, 2003, at 02:57  PM, Cameron Stoner wrote:
> I was going through the socket programming documentation and wanted to 
> know what the differences in general are from IPv4 to IPv6?

See http://www.opus1.com/ipv6/whatisipv6.html .

The only change that affects application programmers is the larger 
address size, from 32-bit to 128-bit addresses.

--amk


From amk at amk.ca  Sun Oct  5 16:31:37 2003
From: amk at amk.ca (A.M. Kuchling)
Date: Sun Oct  5 16:31:18 2003
Subject: [Tutor] bug hunt
In-Reply-To: <3F80385D.6050104@netzero.net>
Message-ID: <EB132CA4-F772-11D7-933C-0003931BF218@amk.ca>


On Sunday, October 5, 2003, at 11:27  AM, Kirk Bailey wrote:
> The servers do not respect ssi includes. Yet the modules list code to 
> handle such, although I am not up to speed enough to debug them. As 
> this is defined in the modules, I have the qurious duty to repport a 
> possible bug in the cgiHTTPServer.py module.

I don't believe anything in the Python core has ever supported 
server-side includes; they're mostly an Apache thing.

--amk


From pythontutor at venix.com  Sun Oct  5 16:36:37 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Sun Oct  5 16:37:13 2003
Subject: [Tutor] function local var problem :-((
In-Reply-To: <E1A6FFp-0003Ie-L4@mail.python.org>
References: <E1A6FFp-0003Ie-L4@mail.python.org>
Message-ID: <3F8080D5.9030901@venix.com>

This is a common pitfall in Python.  The initial empty list is created
ONCE, when the function is defined.  It is NOT created each time
the function is called and that argument is not specified.

Since lists are mutable, the default list changes as it is used.  The most
common solution is usually:
def printHierarchy(objecto, printList=None):
	if printList is None:
		printList = []

None is immutable so the default value can't be changed.  Now we create
a new empty list every time no list is supplied.


mjekl@clix.pt wrote:

> Hi,
> 
> I'm new here and with programming. I've been learning on my own and cannot
> understand what happens with this function I created.
> 
> The function is in it's own module that I import into shell.
> 
> ###### module1.py ######
> 
> def printHierarchy(objecto, printList=[]):
>    """Prints a class hierarchy given an object.
>       Works only with single inheritance hierarchies."""
> 
>    if objecto.__class__.__bases__:
>       printList.append(objecto.__class__.__name__)
>       recurObjecto = objecto.__class__.__bases__[0]()
>       return printHierarchy(recurObjecto, printList)
>    else:
>       printList.append(objecto.__class__.__name__)
> 
>       if not objecto.__class__.__bases__:
> 	 i = 0
> 	 for klass in printList:
> 	    print i * ' ' + klass
> 	    i += 1
>       else:
> 	 return printList
> 
> ####################
> 
> in shell I created a hierarchy of three classes:
> class Sup; class Sub1(Sup); class Sub2(Sub1)
> 
> Then:
> 
>>>>oSub2 = Sub2()
>>>>printHierarchy(oSub2)
> 
> Sup
>    Sub1
>       Sub2
> 
> 
> The problem is that if I call the function again I get:
> 
>>>>printHierarchy(oSub2)
> 
> Sup
>    Sub1
>       Sub2
> 	 Sup
> 	    Sub1
> 	       Sub2
> 
> 
> The problem to me is that I think that the var printList is local and that
> it is initialized every time the function is called. But results contradict
> this assumption. So I tried to investigate the namespaces and found no
> references to var printList. I guess my investigation is bad (In shell I
> issued dir() and dir(module1)
> and got nothing. Also tried to use:
>  from module1 import printHierarchy
> But didn't work either. Can someone please help me?
> 
> Python 2.2 winXP
> 
> Txs,
> Miguel
> 
> Clix Rapidix - Aumente at? 6X a velocidade da sua Internet
> Adira em http://acesso.clix.pt e comece logo a navegar
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582


From pythontutor at venix.com  Sun Oct  5 16:39:56 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Sun Oct  5 16:39:54 2003
Subject: [Tutor] function local var problem :-((
In-Reply-To: <E1A6FFp-0003Ie-L4@mail.python.org>
References: <E1A6FFp-0003Ie-L4@mail.python.org>
Message-ID: <3F80819C.9060907@venix.com>

A good site that lists some other Python pitfalls:

http://zephyrfalcon.org/labs/python_pitfalls.html
zephyrfalcon.org :: labs :: 10 Python pitfalls

#5 is using a mutable variable as a function default.

mjekl@clix.pt wrote:

> Hi,
> 
> I'm new here and with programming. I've been learning on my own and cannot
> understand what happens with this function I created.
> 
> The function is in it's own module that I import into shell.
> 
> ###### module1.py ######
> 
> def printHierarchy(objecto, printList=[]):
>    """Prints a class hierarchy given an object.
>       Works only with single inheritance hierarchies."""
> 
>    if objecto.__class__.__bases__:
>       printList.append(objecto.__class__.__name__)
>       recurObjecto = objecto.__class__.__bases__[0]()
>       return printHierarchy(recurObjecto, printList)
>    else:
>       printList.append(objecto.__class__.__name__)
> 
>       if not objecto.__class__.__bases__:
> 	 i = 0
> 	 for klass in printList:
> 	    print i * ' ' + klass
> 	    i += 1
>       else:
> 	 return printList
> 
> ####################
> 
> in shell I created a hierarchy of three classes:
> class Sup; class Sub1(Sup); class Sub2(Sub1)
> 
> Then:
> 
>>>>oSub2 = Sub2()
>>>>printHierarchy(oSub2)
> 
> Sup
>    Sub1
>       Sub2
> 
> 
> The problem is that if I call the function again I get:
> 
>>>>printHierarchy(oSub2)
> 
> Sup
>    Sub1
>       Sub2
> 	 Sup
> 	    Sub1
> 	       Sub2
> 
> 
> The problem to me is that I think that the var printList is local and that
> it is initialized every time the function is called. But results contradict
> this assumption. So I tried to investigate the namespaces and found no
> references to var printList. I guess my investigation is bad (In shell I
> issued dir() and dir(module1)
> and got nothing. Also tried to use:
>  from module1 import printHierarchy
> But didn't work either. Can someone please help me?
> 
> Python 2.2 winXP
> 
> Txs,
> Miguel
> 
> Clix Rapidix - Aumente at? 6X a velocidade da sua Internet
> Adira em http://acesso.clix.pt e comece logo a navegar
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582


From erikprice at mac.com  Sun Oct  5 17:13:03 2003
From: erikprice at mac.com (Erik Price)
Date: Sun Oct  5 16:51:10 2003
Subject: [Tutor] function local var problem :-((
In-Reply-To: <E1A6FFp-0003Ie-L4@mail.python.org>
Message-ID: <B4B7650C-F778-11D7-A036-00039351FE6A@mac.com>


On Sunday, October 5, 2003, at 04:15  PM, mjekl@clix.pt wrote:

> The problem to me is that I think that the var printList is local and 
> that
> it is initialized every time the function is called. But results 
> contradict
> this assumption. So I tried to investigate the namespaces and found no
> references to var printList. I guess my investigation is bad (In shell 
> I
> issued dir() and dir(module1)
> and got nothing. Also tried to use:
>  from module1 import printHierarchy
> But didn't work either. Can someone please help me?

Very tricky, very subtle.  I found a relevant quote in Python Essential 
Reference 2nd Ed by David Beazley (p. 63):
<snip>
Default parameter values are always set to the objects that were 
supplied as values when the function was defined.  For example:

   a = 10
   def foo(x=a):
     print x

   a = 5			# reassign 'a'
   foo()			# prints '10' (default value not changed)

However, the use of mutable objects as default values can lead to 
unintended behavior:

   a = [10]
   def foo(x=a):
     print x
   a.append(20)
   foo()			# prints '[10, 20]'
</snip>

I follow this logic -- the variable is stored in the scope of the 
function definition itself (the scope where the function is defined).  
But that would strike me as being your module, and you said that the 
dir(your module) function didn't display the variable.  So I don't know.

Hopefully some guru can shed more light on that.


Erik


From glingl at aon.at  Sun Oct  5 16:49:29 2003
From: glingl at aon.at (Gregor Lingl)
Date: Sun Oct  5 16:51:19 2003
Subject: [Tutor] function local var problem :-((
In-Reply-To: <E1A6FFp-0003Ie-L4@mail.python.org>
References: <E1A6FFp-0003Ie-L4@mail.python.org>
Message-ID: <3F8083D9.4020501@aon.at>

Hi Miguel,

you ran into a well known pitfall, which you can observe
in a very simple case here:

 >>> def test(l=[]):
    l.append(1)
    print l
 
 >>> test()
[1]
 >>> for i in range(3):
    test()
  
[1, 1]
[1, 1, 1]
[1, 1, 1, 1]

it occurs if you use an object as default argument
which is *mutable*, for instance a list.

then l points to an object, which is created
only when the function is *defined*, notwhen it
is called.

As long as there is no new assignment to l, this object
is retained  and can be changed if it's mutable.
This is done in your  example  and in the one above.
Every new function call uses the actual state of l.

Remark: As far as I see you could solve your problem
by deleting the defaultargument in the definition and then
call

 >>> printHierarchy(oSub2, [])

Hope that helps,
Gregor


mjekl@clix.pt schrieb:

>Hi,
>
>I'm new here and with programming. I've been learning on my own and cannot
>understand what happens with this function I created.
>
>The function is in it's own module that I import into shell.
>
>###### module1.py ######
>
>def printHierarchy(objecto, printList=[]):
>   """Prints a class hierarchy given an object.
>      Works only with single inheritance hierarchies."""
>
>   if objecto.__class__.__bases__:
>      printList.append(objecto.__class__.__name__)
>      recurObjecto = objecto.__class__.__bases__[0]()
>      return printHierarchy(recurObjecto, printList)
>   else:
>      printList.append(objecto.__class__.__name__)
>
>      if not objecto.__class__.__bases__:
>	 i = 0
>	 for klass in printList:
>	    print i * ' ' + klass
>	    i += 1
>      else:
>	 return printList
>
>####################
>
>in shell I created a hierarchy of three classes:
>class Sup; class Sub1(Sup); class Sub2(Sub1)
>
>Then:
>  
>
>>>>oSub2 = Sub2()
>>>>printHierarchy(oSub2)
>>>>        
>>>>
>Sup
>   Sub1
>      Sub2
>  
>
>
>The problem is that if I call the function again I get:
>  
>
>>>>printHierarchy(oSub2)
>>>>        
>>>>
>Sup
>   Sub1
>      Sub2
>	 Sup
>	    Sub1
>	       Sub2
>  
>
>
>The problem to me is that I think that the var printList is local and that
>it is initialized every time the function is called. But results contradict
>this assumption. So I tried to investigate the namespaces and found no
>references to var printList. I guess my investigation is bad (In shell I
>issued dir() and dir(module1)
>and got nothing. Also tried to use:
> from module1 import printHierarchy
>But didn't work either. Can someone please help me?
>
>Python 2.2 winXP
>
>Txs,
>Miguel
>
>Clix Rapidix - Aumente at? 6X a velocidade da sua Internet
>Adira em http://acesso.clix.pt e comece logo a navegar
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>
>  
>


From project5 at redrival.net  Sun Oct  5 17:45:16 2003
From: project5 at redrival.net (Andrei)
Date: Sun Oct  5 17:47:23 2003
Subject: [Tutor] Re: function local var problem :-((
In-Reply-To: <3F80819C.9060907@venix.com>
References: <E1A6FFp-0003Ie-L4@mail.python.org> <3F80819C.9060907@venix.com>
Message-ID: <blq3h3$ilg$1@sea.gmane.org>

Lloyd Kvam wrote:

> A good site that lists some other Python pitfalls:
> 
> http://zephyrfalcon.org/labs/python_pitfalls.html
> zephyrfalcon.org :: labs :: 10 Python pitfalls
> 
> #5 is using a mutable variable as a function default.

Miguel's sample had me completely puzzled too - more so than when I started with 
Python and assigned the "a" to "a[3]" and ended up with a list where I could 
"print a[3][3][3][3][3][3]" - it's easy to notice that the argument in the 
topmost recursion gets "preserved", but there's no obvious reason. I'd expected 
this bug to have bitten me when I wasn't looking, but doing a search through my 
code I noticed I've never used lists as default params - either I was lucky or I 
read this at some point and it stuck in the back of my head. Reading about the 
pitfall, I still see no reason for this behaviour, only "This behavior can 
occasionally be useful. In general, just watch out for unwanted side effects."
When is it useful?

Btw, Miguel, when I pasted your code in my shell, I got a mix of tabs and spaces 
(pitfall #1 :)). You could also move "printList.append()" outside the if-else 
because you do it regardless of the condition and you could get rid of the "if 
not obejcto.__class__.__bases__", because it's in the else clause which is 
*only* executed if not objecto.__class__.__bases__ anyway. Result:

def doprint(objecto, pl=[]):
     """Prints a class hierarchy given an object.
       Works only with single inheritance hierarchies."""
     printList = pl[:] # make copy instead of modifying in-place
     printList.append(objecto.__class__.__name__)
     if objecto.__class__.__bases__:
         recurObjecto = objecto.__class__.__bases__[0]()
         doprint(recurObjecto, printList[:])
     else:
         i = 0
         for klass in printList:
             print i * ' ' + klass
             i += 1

Seems to work ok, though given the circumstances I'd avoid using the list 
altogether and making the default param None, converting that to an empty list 
internally.

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur 
yvfg, fb gurer'f ab arrq gb PP.



From mjekl at clix.pt  Sun Oct  5 17:57:32 2003
From: mjekl at clix.pt (mjekl@clix.pt)
Date: Sun Oct  5 17:55:47 2003
Subject: [Tutor] function local var problem :-((
Message-ID: <E1A6Gqu-0003RT-9u@mail.python.org>

Thank you all for the clear explanations.

I checked-out the link supplied by Lloyd Kvam. Many Txs Lloyd for the
suberb explanation and on-the-spot great link!


Hi Gregor,

Your right about everything, except that:

>>> printHierarchy(oSub2, []) # is a sintax error

Best Regards,
Miguel

> Hi Miguel,
> 
> you ran into a well known pitfall, which you can observe
> in a very simple case here:
> 
>  >>> def test(l=[]):
>     l.append(1)
>     print l
>  
>  >>> test()
> [1]
>  >>> for i in range(3):
>     test()
>   
> [1, 1]
> [1, 1, 1]
> [1, 1, 1, 1]
> 
> it occurs if you use an object as default argument
> which is *mutable*, for instance a list.
> 
> then l points to an object, which is created
> only when the function is *defined*, notwhen it
> is called.
> 
> As long as there is no new assignment to l, this object
> is retained  and can be changed if it's mutable.
> This is done in your	example  and in the one above.
> Every new function call uses the actual state of l.
> 
> Remark: As far as I see you could solve your problem
> by deleting the defaultargument in the definition and then
> call
> 
>  >>> printHierarchy(oSub2, [])
> 
> Hope that helps,
> Gregor
> 
> 
> mjekl@clix.pt schrieb:
> 
> >Hi,
> >
> >I'm new here and with programming. I've been learning on my own and
cannot
> >understand what happens with this function I created.
> >
> >The function is in it's own module that I import into shell.
> >
> >###### module1.py ######
> >
> >def printHierarchy(objecto, printList=[]):
> >   """Prints a class hierarchy given an object.
> >	 Works only with single inheritance hierarchies."""
> >
> >   if objecto.__class__.__bases__:
> >	 printList.append(objecto.__class__.__name__)
> >	 recurObjecto = objecto.__class__.__bases__[0]()
> >	 return printHierarchy(recurObjecto, printList)
> >   else:
> >	 printList.append(objecto.__class__.__name__)
> >
> >	 if not objecto.__class__.__bases__:
> >	 i = 0
> >	 for klass in printList:
> >	    print i * ' ' + klass
> >	    i += 1
> >	 else:
> >	 return printList
> >
> >####################
> >
> >in shell I created a hierarchy of three classes:
> >class Sup; class Sub1(Sup); class Sub2(Sub1)
> >
> >Then:
> >  
> >
> >>>>oSub2 = Sub2()
> >>>>printHierarchy(oSub2)
> >>>>	      
> >>>>
> >Sup
> >   Sub1
> >	 Sub2
> >  
> >
> >
> >The problem is that if I call the function again I get:
> >  
> >
> >>>>printHierarchy(oSub2)
> >>>>	      
> >>>>
> >Sup
> >   Sub1
> >	 Sub2
> >	 Sup
> >	    Sub1
> >	       Sub2
> >  
> >
> >
> >The problem to me is that I think that the var printList is local and
that
> >it is initialized every time the function is called. But results
contradict
> >this assumption. So I tried to investigate the namespaces and found no
> >references to var printList. I guess my investigation is bad (In shell I

> >issued dir() and dir(module1)
> >and got nothing. Also tried to use:
> > from module1 import printHierarchy
> >But didn't work either. Can someone please help me?
> >
> >Python 2.2 winXP
> >
> >Txs,
> >Miguel
> >
> >Clix Rapidix - Aumente até 6X a velocidade da sua Internet
> >Adira em http://acesso.clix.pt e comece logo a navegar
> >
> >_______________________________________________
> >Tutor maillist  -  Tutor@python.org
> >http://mail.python.org/mailman/listinfo/tutor
> >
> >
> >  
> >
> 


Clix Rapidix - Aumente até 6X a velocidade da sua Internet
Adira em http://acesso.clix.pt e comece logo a navegar

From mjekl at clix.pt  Sun Oct  5 18:16:20 2003
From: mjekl at clix.pt (mjekl@clix.pt)
Date: Sun Oct  5 18:14:35 2003
Subject: [Tutor] function local var problem :-((
Message-ID: <E1A6H96-0001yv-5G@mail.python.org>

Hi Gregor,

I was just in the process of writting an apologie mail.
I confused function def with function call, so I tested (the wrong
statement):

def printHierarchy(objecto, []): # this is wrong

And you where talking about the call:

>>> printHierarchy(oSub2, []) # this is right

I'm sorry for making this mistake.

Sincerely,
Miguel
> 
> mjekl@clix.pt schrieb:
> 
> >...
> >Hi Gregor,
> >
> >Your right about everything, except that:
> >
> >  
> >
> >>>>printHierarchy(oSub2, []) # is a sintax error
> >>>>	      
> >>>>
> >
> >Best Regards,
> >Miguel
> >  
> >
> Hello Miguel?
> When I wrote
> 
> >>Remark: As far as I see you could solve your problem
> >>by deleting the defaultargument in the definition 
> >>
> I meant that you could write
> 
> def printHierarchy(objecto, printList):
>   """Prints a class hierarchy given an object.
>	 Works only with single inheritance hierarchies."""
>   ...
> 
> deleting the default argument for the second parameter but keeping the 
> parameter itself.
> What is wrong the with
> 
> >>and then
> >>call
> >>
> >> >>> printHierarchy(oSub2, [])
> >>
> Regards, Gregor
> 
> 


Clix Rapidix - Aumente até 6X a velocidade da sua Internet
Adira em http://acesso.clix.pt e comece logo a navegar

From alan.gauld at blueyonder.co.uk  Sun Oct  5 18:38:51 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Sun Oct  5 18:37:48 2003
Subject: [Tutor] pointers for python?
References: <200310041210.01431.thomi@imail.net.nz><qcbtnv844qji7m8bl8mfvtrths5ocuifrm@4ax.com><00dc01c38acb$47037930$6401a8c0@xp>
	<200310051118.09631.thomi@imail.net.nz>
Message-ID: <010b01c38b91$734004c0$6401a8c0@xp>

> under C, you'd have to pass a pointer to A in order to modify it,
> correct?

It is one solution but is not even good practice in C. The reason
why it's sometimes necessary is that C can only return a single value
from a function so where multiple return values might be needed
(like scanf say) then passing pointers (or references in C++) is
the only solution.

But C (unlike Pascal or ADA) does not have a "procedure" construct
only a functuion  - which by definition has a return value - and
pre ANSI didn't even encourage void returns, so that all the
standard library functions return a value (even printf - the
number of characters printed)

So that:

> table = gtk.Table(3,2,gtk.FALSE)
> fill_table(table,["Label 1 text","label 2 text","Label 3 text"])

Is not good C style either(you are ignoring the return value of
fill_table), its just unfortunately one that has become common.
(This is why tools like lint will complain about printf() statements
where the return value is not used.)

> table = fill_table(table,["Label 1 text","label 2 text","Label 3
text"])

This is good style and practice from a computing science point of
view regardless of language. Its a matter of improving reliability
and reusability if functions don't have side effects - and that
includes changing the parameters passed to them.

> As i said in an earlier mail, the question was purely one of
> discovery, which arose when comparing C++ and python code ;)

Incidentally, this is the first time you mentioned C++ instead of C.
C++ introduced the concept of references specifically to help deal
with this issue and reduce the need to pass pointers.

Thus in C++ it is considered preferable to define:

void foo(int& i){...}

to

void foo(int* ip){...}


Anyway, these are largely niceties of style and of no real
significance in Python where you have no such choices, and you
can also define multiple return values (actually a tuple) and
so avoid even the scanf problem.

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


From idiot1 at netzero.net  Sun Oct  5 20:21:44 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Sun Oct  5 20:20:48 2003
Subject: [Tutor] bug hunt
In-Reply-To: <EB132CA4-F772-11D7-933C-0003931BF218@amk.ca>
References: <EB132CA4-F772-11D7-933C-0003931BF218@amk.ca>
Message-ID: <3F80B598.4070809@netzero.net>

Pity. The cgiserver module builds a dictionary with all the environment 
variables in it for a script to use. THEY EXIST ALREADY. But there is no 
provision for parsing a .shtml script, detecting ssi tags, and replacing them 
with the required output. Therefore, this server could not handle an imbedded 
hit counter in a webpage, nor imbed script output as part of a page. And quite a 
number of servers apart from apache honor ssi.

So close, and yet so far...

A.M. Kuchling wrote:

> 
> On Sunday, October 5, 2003, at 11:27  AM, Kirk Bailey wrote:
> 
>> The servers do not respect ssi includes. Yet the modules list code to 
>> handle such, although I am not up to speed enough to debug them. As 
>> this is defined in the modules, I have the qurious duty to repport a 
>> possible bug in the cgiHTTPServer.py module.
> 
> 
> I don't believe anything in the Python core has ever supported 
> server-side includes; they're mostly an Apache thing.
> 
> --amk
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Prometheus
  +                              kniht                                +

Fnord.


From tony at tcapp.com  Mon Oct  6 02:08:46 2003
From: tony at tcapp.com (Tony Cappellini)
Date: Mon Oct  6 02:12:14 2003
Subject: [Tutor] Instantiating a derived class:Does the constructor need the
 same args as the parent class ?
Message-ID: <5.1.0.14.0.20031005224821.01bc0e40@smtp.sbcglobal.net>



Danny-

One of your previous posts almost addresses my question, but .....
Re: [Tutor] Classes
by Daniel Yoo
Apr 4 2001 1:45AM


When instantiating an instance of a derived class, should the derived class 
constructor
have the same args as the parent class constructor, as a minimum, as well 
as any args specifically required by the derived class ?

The derive class is specializing the class Definition, by adding a class 
member to the
Macro class, but still needs to have access to the members in the parent 
class.


 From what I can see, The only way to instantiate the subclass, is to pass 
the arguments to the derived class constructor, and in turn,pass them to 
the parent class constructor (even though my code below doesn't explicitly 
do this yet).

However, something feels wrong with having the same args for the derived 
class, as those of the parent class.

################################################ 

class   Definition:

        def __init__(self,MacroFilename,Linenum,Context):

            self.Filename    = MacroFilename
            self.FileLinenum = Linenum
            self.Context     = Context


################################################ 

class  Macro(Definition):

        def __init__(self,MacroName):

            self.MacroName = MacroName

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20031005/6787c2b7/attachment.html
From jim_938 at hotmail.com  Mon Oct  6 04:10:15 2003
From: jim_938 at hotmail.com (Jimmy verma)
Date: Mon Oct  6 04:10:25 2003
Subject: [Tutor] Private and Public variables
Message-ID: <Sea1-F39skKwaenTosf0000dcaa@hotmail.com>

Hello,

I hope this must have been discussed already on the list. Can some one point 
me towards some stuff where i can know about ''Private and public 
variables'' in a class in python.


Thanks in advance for this one and also thanks for the previous responses 
from the tutor.

With best regards,

James

_________________________________________________________________
Get Married!  http://www.bharatmatrimony.com/cgi-bin/bmclicks1.cgi?74 Search 
from 7 lakh Brides & Grooms.


From james_royus at eudoramail.com  Mon Oct  6 04:27:59 2003
From: james_royus at eudoramail.com (james roy)
Date: Mon Oct  6 04:28:21 2003
Subject: [Tutor] conversion to a fixed_no
Message-ID: <MGDHJMBMHLEOJFAA@whowhere.com>

Hello,

I am new to python and is having some problem while writing some module in python. Actually i am writing a code in which i am needed to convert a no. into a fixed_no where the fixed_no's specification is like this:


fixed_no is a 32-bit representation of a binary fraction. A fixed_no is a signed quantity, with the two's complement of the entire word used to represent negation. Of the 32 bits in a fixed_no, exactily 12 are to the left of the binary point; thus the largest fixed_no value is 2048-2^(-20), and the smallest is -2048.

Can someone suggest me sthing regarding writing a module to convert a no.into a fixed_no according to the way i have written above.

I'll be highly thankful for this.

Thanks a lot.

Regards,

Jimmy roy



Need a new email address that people can remember
Check out the new EudoraMail at
http://www.eudoramail.com

From glingl at aon.at  Mon Oct  6 04:36:01 2003
From: glingl at aon.at (Gregor Lingl)
Date: Mon Oct  6 04:37:52 2003
Subject: [Tutor] Private and Public variables
In-Reply-To: <Sea1-F39skKwaenTosf0000dcaa@hotmail.com>
References: <Sea1-F39skKwaenTosf0000dcaa@hotmail.com>
Message-ID: <3F812971.4020201@aon.at>



Jimmy verma schrieb:

> Hello,
>
> I hope this must have been discussed already on the list. Can some one 
> point me towards some stuff where i can know about ''Private and 
> public variables'' in a class in python.

Hi Jimmy,

for a first answer have a look at
http://diveintopython.org/object_oriented_framework/private_functions.html
including the footnote.
(It's part of the "dive into python" - book:  
http://diveintopython.org/index.html)

Does this suffice?
If not, feel free to ask more questions
Regards, Gregor

>
>


From op73418 at mail.telepac.pt  Mon Oct  6 10:06:33 2003
From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=)
Date: Mon Oct  6 10:05:07 2003
Subject: [Tutor] Private and Public variables
In-Reply-To: <Sea1-F39skKwaenTosf0000dcaa@hotmail.com>
References: <Sea1-F39skKwaenTosf0000dcaa@hotmail.com>
Message-ID: <ofs2ovsodni9ph8esnech8g63up344404e@4ax.com>

>Hello,
>
>I hope this must have been discussed already on the list. Can some one point 
>me towards some stuff where i can know about ''Private and public 
>variables'' in a class in python.
>
>

This is not a direct answer to J. Verma (G. Lingl already did that) ut
to make a general question to the Tutor's Python list:

What are your experiences in using protected and private attributes?

I want to frame the discussion in the context of one article by H.
Nowak

http://zephyrfalcon.org/labs/beginners_mistakes.html

where one of the Beginner's mistakes is, and I quote:

"Mistake 2: writing "language X" code in Python

[text snipped]

-You're really paranoid about data hiding (some would call this
"encapsulation"),  and/or write getters and setters for all object
attributes. (Java, C++, Delphi)"

I tend to make this "mistake" a lot. I started using Python when
Python 2.2 came out, when, in particular, properties became available.
My experience was mostly in Java where I really was paranoid about
data hiding. These Java habits were carried along and made their
imprint on my Python code, but what's more important, after 2 years
they are still with me. I think one of the reason's why is because I
tend to favor (following the gang of 4) composition to inheritance. As
such, it is very important that my classes have clean and small
interfaces, leaking as little as possible to the outside world. These
interfaces should also be "recognizable", e.g. they follow the
interfaces of the Python objects as much as possible. A simple
example: whenever I have an iterable container that I want to make
mutable I had methods:

def append(self, elem):
    """Append an element."""
    <whatever>

def remove(self, elem):
    """Remove an element."""
    <whatever>

So, what do you guys think?

With my best regards,
G. Rodrigues

From project5 at redrival.net  Mon Oct  6 10:46:44 2003
From: project5 at redrival.net (Andrei)
Date: Mon Oct  6 10:48:50 2003
Subject: [Tutor] Combobox - SetValue based on selection
Message-ID: <blrvcc$lkn$1@sea.gmane.org>

Hello,

I have a combobox with a number of predefined items. When an item is chosen, I 
don't want that item itself to be set as value in the text field of the 
combobox, but a text *associated* with that item (using a dictionary). E.g. if 
item "1" is chosen, the text field should say "one". I tried EVT_COMBOBOX, but 
after my function is processed, the associated text is replaced by the selected 
item again in the text field of the combobox.

How can I solve this?

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur 
yvfg, fb gurer'f ab arrq gb PP.



From project5 at redrival.net  Mon Oct  6 10:48:45 2003
From: project5 at redrival.net (Andrei)
Date: Mon Oct  6 11:10:38 2003
Subject: [Tutor] Re: Combobox - SetValue based on selection
In-Reply-To: <blrvcc$lkn$1@sea.gmane.org>
References: <blrvcc$lkn$1@sea.gmane.org>
Message-ID: <blrvg5$lkn$2@sea.gmane.org>

Oops, this one was meant to go to the wxPython list :).

> Hello,
> 
> I have a combobox with a number of predefined items. When an item is 
> chosen, I don't want that item itself to be set as value in the text 
> field of the combobox, but a text *associated* with that item (using a 
> dictionary). E.g. if item "1" is chosen, the text field should say 
> "one". I tried EVT_COMBOBOX, but after my function is processed, the 
> associated text is replaced by the selected item again in the text field 
> of the combobox.
> 
> How can I solve this?
> 
> Andrei
> 
> =====
> Mail address in header catches spam. Real contact info (decode with rot13):
> cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V 
> ernq gur yvfg, fb gurer'f ab arrq gb PP.

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur 
yvfg, fb gurer'f ab arrq gb PP.



From irridian at canada.com  Mon Oct  6 12:17:44 2003
From: irridian at canada.com (irridian@canada.com)
Date: Mon Oct  6 12:17:51 2003
Subject: [Tutor] (no subject)
Message-ID: <20031006091744.1973.h020.c009.wm@mail.canada.com.criticalpath.net>


From irridian at canada.com  Mon Oct  6 12:32:00 2003
From: irridian at canada.com (irridian@canada.com)
Date: Mon Oct  6 12:32:14 2003
Subject: [Tutor] Time tuple comparison
Message-ID: <20031006093200.12457.h011.c009.wm@mail.canada.com.criticalpath.net>

Hi I'm a newbie to python and am trying to write a
program that takes user input and compares it to a time
signal which I find out is a tuple.How can you take the
year,month date from the time tuple and commpair to
interger values from user input?I have dived into the
black hole of pythhon.org but come up empty.
import time 
YourDate = input("Enter your date
eg.(year,month,day)(2003,10,6 )")
Rdate = time.localtime(time.time())

From glingl at aon.at  Mon Oct  6 12:59:32 2003
From: glingl at aon.at (Gregor Lingl)
Date: Mon Oct  6 13:02:38 2003
Subject: [Tutor] Time tuple comparison
In-Reply-To: <20031006093200.12457.h011.c009.wm@mail.canada.com.criticalpath.net>
References: <20031006093200.12457.h011.c009.wm@mail.canada.com.criticalpath.net>
Message-ID: <3F819F74.9010508@aon.at>



irridian@canada.com schrieb:

>Hi I'm a newbie to python and am trying to write a
>program that takes user input and compares it to a time
>signal which I find out is a tuple.How can you take the
>year,month date from the time tuple and commpair to
>interger values from user input?I have dived into the
>black hole of pythhon.org but come up empty.
>import time 
>YourDate = input("Enter your date
>eg.(year,month,day)(2003,10,6 )")
>Rdate = time.localtime(time.time())
>
In your example you have:

 >>> YourDate
(2003, 10, 6)
 >>> Rdate
(2003, 10, 6, 18, 52, 34, 0, 279, 1)

In Python you can use slices of sequances, for instance of tuples:

 >>> Rdate[2:7]
(6, 18, 52, 34, 0)
 >>> Rdate[5:]
(34, 0, 279, 1)
 >>> Rdate[:3]
(2003, 10, 6)

So you can compare the slice from the last example with YourDate:

 >>> YourDate == Rdate[:3]
True

This certainly is nicer than the classical clumsy

 >>> YourDate[0] == Rdate[0] and YourDate[1] == Rdate[1] and YourDate[2] 
== Rdate[2]
True

HTH, Gregor



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


From bgailer at alum.rpi.edu  Mon Oct  6 17:18:00 2003
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Mon Oct  6 17:20:20 2003
Subject: [Tutor] conversion to a fixed_no
In-Reply-To: <MGDHJMBMHLEOJFAA@whowhere.com>
References: <MGDHJMBMHLEOJFAA@whowhere.com>
Message-ID: <6.0.0.22.0.20031006151112.034f1c30@66.28.54.253>

At 02:27 AM 10/6/2003, james roy wrote:

>Hello,
>
>I am new to python and is having some problem while writing some module in 
>python. Actually i am writing a code in which i am needed to convert a no. 
>into a fixed_no where the fixed_no's specification is like this:
>
>
>fixed_no is a 32-bit representation of a binary fraction. A fixed_no is a 
>signed quantity, with the two's complement of the entire word used to 
>represent negation. Of the 32 bits in a fixed_no, exactily 12 are to the 
>left of the binary point; thus the largest fixed_no value is 2048-2^(-20), 
>and the smallest is -2048.
>
>Can someone suggest me sthing regarding writing a module to convert a 
>no.into a fixed_no according to the way i have written above.

In what form is the input to this process?

For the sake of discussion I will assume you start with 2 integers (L,R), 
one representing the part to the left and the other the part to the right. 
Ignoring sign for now, the desired result is L<<12 + R.

How will you express the sign? Will either L or R be negative or is there a 
third parameter to indicate the sign?

Bob Gailer
bgailer@alum.rpi.edu
303 442 2625
-------------- next part --------------

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.521 / Virus Database: 319 - Release Date: 9/23/2003
From pythontutor at venix.com  Mon Oct  6 17:33:13 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Mon Oct  6 17:33:47 2003
Subject: [Tutor] translating some python code to perl
In-Reply-To: <Pine.LNX.4.44.0308281720340.318-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0308281720340.318-100000@hkn.eecs.berkeley.edu>
Message-ID: <3F81DF99.3010501@venix.com>

Thanks to Danny, the Perl folks who wanted my transformed python-to-perl code
are happy.  (I just got the email saying so.)  However, I thought I should
post a followup.  I'm not sure how Danny was able to avoid typing a YIKES!
when he saw my class.

Overriding __repr__ to emit perl code is a very bad idea.  In general, you
want x = eval( repr( x)) to be true.  Clearly emitting perl code breaks
that expectation very badly.

I've mangled Danny's code slightly (e.g.sorting the dictionary keys), but if
anyone else finds the need to generate perl data from python data, this could
be a useful starting point.

####
def renderObject(obj):
	if isinstance(obj, dict):
		return renderDictionary(obj)
	elif isinstance(obj, str):
		return renderString(obj)
	raise Exception, ("I don't know how to handle %s" % obj)

def renderDictionary(d):
	rendered_items = []
	keys = d.keys()
	keys.sort()
	for key in keys:
		rendered_items.append("%s => %s," % (renderObject(key),
											renderObject(d[key])))
	return "{\n%s\n}" % (indent(rendered_items))

def renderString(s):
	return repr(s)

def indent(s):
	indented_lines = ['    ' + l for l in s]
	indented_lines = [l.replace('\n','\n    ') for l in indented_lines]
	return '\n'.join(indented_lines)

# remember to add the semicolon
print "$perl_dict = %s;" % (renderObject(pydict))
####

Danny Yoo wrote:

> 
> On Thu, 28 Aug 2003, Lloyd Kvam wrote:
> 
> 
>>This did not generate any responses, but I thought I'd post my solution
>>anyway.
>>My python code (version 2.2) follows:
>>#!/usr/bin/python
>># py2perl.py
>>'''module to handle some python to perl transformations.
>>'''
>>class Py2perl_dict(dict):
>>
>>	def __init__(self, arg):
>>	    super(Py2perl_dict, self).__init__(arg)
>>	    for key,val in self.items():
>>		if isinstance(val, dict) and not isinstance(val, Py2perl_dict):
>>		    self[key] = Py2perl_dict(val)
>>
>>	def __repr__(self):
>>	    keylist = self.keys()
>>	    keylist.sort()
>>	    return ''.join(['{',
>>                 ','.join(["%s => %s" % (repr(key),repr(self[key])) for key in keylist]),
>>                 '}'])
> 
> This code works, but also does modifications to our original dictionary.
> Seems a harsh price to pay for compatibility.  *grin*

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582


From missive at hotmail.com  Mon Oct  6 18:07:34 2003
From: missive at hotmail.com (Lee Harr)
Date: Mon Oct  6 18:07:39 2003
Subject: [Tutor] Re: Instantiating a derived class
Message-ID: <BAY2-F40OEvpx7U24rV0001c586@hotmail.com>

>Does the constructor need the same args as the parent class ?
>
>When instantiating an instance of a derived class, should the derived class
>constructor
>have the same args as the parent class constructor, as a minimum, as well
>as any args specifically required by the derived class ?
>


I would say... not necessarily, although that is certainly one way to do it.

Basically, until you know that you do not need to, you should be calling
the parent class's constructor in your child class.  Like this:


class Definition:
    def __init__(self, MacroFilename, Linenum, Context):
        self.Filename = MacroFilename
        self.FileLinenum = Linenum
        self.Context = Context


class Macro(Definition):
    def __init__(self, MacroName):
        mf = 'the_macrofilename'
        ln = 43
        ct = foo # not sure where you get this
        Definition.__init__(self, mf, ln, ct)
        self.MacroName = MacroName

_________________________________________________________________
Add photos to your e-mail with MSN 8. Get 2 months FREE*. 
http://join.msn.com/?page=features/featuredemail


From dyoo at hkn.eecs.berkeley.edu  Mon Oct  6 20:02:33 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Oct  6 20:02:38 2003
Subject: [Tutor] pointers for python?
In-Reply-To: <6b8snv8odh9ve1n9a8n9v9anff5g758o4d@4ax.com>
Message-ID: <Pine.LNX.4.44.0310032122150.21195-100000@hkn.eecs.berkeley.edu>


> >def inc(x):
> >	x+=1
> >
> >a=1
> >inc(a)
> >print a
> >
> >prints "1"
> >
> >is there a way to get the inc() function to modify the original
> >variable, even though it's not in the function's scope?

Hello!

Not this way.  This may seem like a limitation, but it's consistant and
forces Python functions to be more useful for arbitrary expressions.
This isn't obvious, so let's talk about it a little more.



What should happen if we do something like this?

    inc(42)      ## what happens here?


Since you're familiar with C/C++, let's use a C++ example:

///
using namespace std;

#include <iostream>

// Increments reference variable x.
void inc(int &x) {
  x++;
}

int main() {
  int number = 42;
  inc(number);
  cout << number << endl;
  //   inc(42);    <-- this won't work!
}
///

The commented-out line actually doesn't work --- it's a compile-time error
--- because our inc() definition above can only work with variables.


If we have to think about references, we now have to make this weird
distinction between expressions and variables.  So the reference-passing
model --- distinguishing between references and values --- is just more
unnecessarily involved than the simpler pass-by-value system in Python.



Hope this helps!


From bvg.pythontutor at freemail.hu  Mon Oct  6 20:37:12 2003
From: bvg.pythontutor at freemail.hu (Gabor Borgulya)
Date: Mon Oct  6 20:36:37 2003
Subject: [Tutor] pointers for python?
In-Reply-To: <Pine.LNX.4.44.0310032122150.21195-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0310032122150.21195-100000@hkn.eecs.berkeley.edu>
Message-ID: <1065487031.3626.120.camel@catv-d5de952e.bp04catv.broadband.hu>

> > >def inc(x):
> > >	x+=1
> > >
> > >a=1
> > >inc(a)
> > >print a
> > >
> > >prints "1"
> > >
> > >is there a way to get the inc() function to modify the original
> > >variable, even though it's not in the function's scope?

In this solution a and x are lists, which are mutable types. You could
choose any mutable types.

def inc(x):
    x[0]+=1

a=[1]
inc(a)
print a[0]

G?bor

From dyoo at hkn.eecs.berkeley.edu  Mon Oct  6 21:32:17 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Oct  6 21:32:27 2003
Subject: [Tutor] pointers for python?
In-Reply-To: <200310051118.09631.thomi@imail.net.nz>
Message-ID: <Pine.LNX.4.44.0310061822570.29258-100000@hkn.eecs.berkeley.edu>



On Sun, 5 Oct 2003, Thomi Richards wrote:

> > Can you say why? The return method is by far the best technique,
> > its safe and makes the function reusable - it doesn't rely on a
> > variable called x existing somewhere. Its "the right way" to do it.
>
> well, (for example), supposing you had a situation where a function was
> passed 3 variables ("A", "B", and "C"). A is an empty pygtk Table
> element, B is a list of strings.
>
> under C, you'd have to pass a pointer to A in order to modify it,
> correct? It just seemed neater doing someting like this:
>
> table = gtk.Table(3,2,gtk.FALSE)
> fill_table(table,["Label 1 text","label 2 text","Label 3 text"])
>
> than something like this:
> table = fill_table(gtk.table,["Label 1 text","label 2 text","Label 3 text"])


Hi Thomi,


Ok, good, a concrete example!  *grin*



Question: is gtk.table mutable?  If so, then good news: it's perfectly
possible to write the code you'd expect to write in Python.


I'm not familiar enough with PyGTK to decipher:

    http://www.gnome.org/~james/pygtk-docs/class-gtktable.html

yet --- I'm more familiar with Tkinter.  But if we pass a mutable object
to Python, we're perfectly set to do changes to it:


###
## Small demonstration of sending a function a mutable object
from Tkinter import *

def fill_frame_with_labels(frame, label_strings):
    for s in label_strings:
        Label(frame, text=s).pack()

if __name__ == '__main__':
    root = Tk()
    frame = Frame(root)
    fill_frame_with_labels(frame, ['label1', 'label2', 'label3'])
    frame.pack()
    mainloop()
###


Is this simliar to what you're looking for?


What we're talking about, then, is just a matter of "mutability" and
"immutability".  Maybe we should refocus the subject away from pointers
and to immutability concepts.



Talk to you later!


From dyoo at hkn.eecs.berkeley.edu  Mon Oct  6 21:34:47 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Oct  6 21:34:53 2003
Subject: [Tutor] Recursion confusion
In-Reply-To: <m3brsvwo7r.fsf@hamster.pflaesterer.de>
Message-ID: <Pine.LNX.4.44.0310061832490.29258-100000@hkn.eecs.berkeley.edu>



> Fine.
>
> But don't rely too much on recursion in Python.  Too deep recursion will
> cause Python to complain.  Try factorial(999) with your code.  Python
> does nothing like eg. Scheme which can optimize recursive algorithms
> where the recursive function call is in tail position (the last function
> call in the caller).


By the way, there's a nice paper by the Scheme folks from the 1970's
that's actually quite fun to read:

    ftp://publications.ai.mit.edu/ai-publications/pdf/AIM-443.pdf
    http://library.readscheme.org/page1.html

It explains in good detail what a "tail call" means, and how modern
compilers can optimize procedure calls into fast GOTO's.


From dyoo at hkn.eecs.berkeley.edu  Tue Oct  7 01:26:52 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Oct  7 01:26:58 2003
Subject: [Tutor] ANN: BayPIGgies meeting for Thursday, October 9,
	2003: GUI Programming
Message-ID: <Pine.LNX.4.44.0310062224140.6644-100000@hkn.eecs.berkeley.edu>

When: Thursday, October 9, 2003
Where: Carnegie Institute of Washington
       at Stanford University; Palo Alto
Agenda: GUI programming
Speaker: Jimmy Retzlaff


Note: our regular meeting times have been rescheduled: we are now meeting
on the second Thursday of each month.


The topic of this month's BayPIGgies meeting is GUI programming, with an
emphasis on the use of Model-View-Controller and Model-View-Presenter
architectures.  There will be a short presentation, followed by an open
discussion.

Jimmy Retzlaff will present a simple RPN calculator application, written
in wxPython, that demonstrates MVC decoupling between the GUI and other
program logic.  This will lead to discussion of people's experiences using
MVC or MVP with Python's GUI toolkits.  Bring your questions and
experiences to help contribute.  Discussion on other GUI concepts or
toolkits are welcome.


For driving directions, please see:

    http://baypiggies.net/



From dyoo at hkn.eecs.berkeley.edu  Tue Oct  7 01:59:52 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Oct  7 01:59:57 2003
Subject: [Tutor] Code critique?  [Red-Black balanced binary trees]
Message-ID: <Pine.LNX.4.44.0310062240340.6947-100000@hkn.eecs.berkeley.edu>

Hi everyone,


I had some time today, and I wanted to understand Red-Black trees a little
more.  I ran into them a few times on Tutor before, especially whenever
asked for a sorted Dictionary.

    http://mail.python.org/pipermail/tutor/2002-November/018864.html

They're a neat data structure.  I have to admit, though, that I didn't
really quite get how red-black trees worked.  So I spent this afternoon
coding another red-black tree module.  *grin*


I also wanted to get a lot more familiar with the 'unittest' module,

    http://www.python.org/doc/lib/module-unittest.html

so the code comes with a few unit tests.  Can anyone help me by critiquing
the implementation and suggesting other good things to test?


The code is here at the moment:

    http://hkn.eecs.berkeley.edu/~dyoo/python/red_black/red_black.py

and as soon as it's more stable and useful (and is better documented), I
can package it up using distutils.


Thanks again!


From thomi at imail.net.nz  Tue Oct  7 04:24:54 2003
From: thomi at imail.net.nz (Thomi Richards)
Date: Tue Oct  7 04:24:52 2003
Subject: [Tutor] pointers for python?
In-Reply-To: <Pine.LNX.4.44.0310061822570.29258-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0310061822570.29258-100000@hkn.eecs.berkeley.edu>
Message-ID: <200310072124.54876.thomi@imail.net.nz>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

>
> Question: is gtk.table mutable?  If so, then good news: it's perfectly
> possible to write the code you'd expect to write in Python.
>
pass.. i guess there's only one way top find out though:
>>> import gtk
>>> def fill_table(table,strings):
...     for i in range(len(strings)):
...             table.attach(gtk.Label(strings[i]),0,1,i,i+1)
... 

>>> window = gtk.Window()
>>> table = gtk.Table(4,2,gtk.FALSE)
>>> fill_table(table,['one','two','three'])
>>> window.add(table)
>>> window.show_all()
>>> gtk.main()     
>>> 

does indeed display a window with 3 labels in it....


>
> Is this simliar to what you're looking for?
>

this is *exactly* what I'm looking for... It almost adds to the confusion 
however.

>
> What we're talking about, then, is just a matter of "mutability" and
> "immutability".  Maybe we should refocus the subject away from pointers
> and to immutability concepts.
>

AFAIK (And I'm no expert), in C, whenever a function is called, a *copy* of 
the variables passed to it are made, and the function uses that copy, like 
this:

void test(int a)
{
	a++;
	printf("Integer value + 1 is: %d\n",a);
}

if you were to call this like so:

int t = 42;
test(t);

this would print 43, but the variable "t" (in the main scope of the program) 
would remain 42, because the function test() was operating on a copy of the 
variable, not the variable itself. is this basically correct?

However, when you use pointers in C, you are passing an address in memory, 
which can be used like a variable. However, because you are passing the 
original address, the function operates on the original varibale, not a copy 
(this can of course be useful when you're dealing with larger structures, as 
it saves the program chewing memory and CPU cycles to copy something which 
you were effectively going to change anyway).

...which brings us back to python. Evidently, python doesn't do this, with 
*some* types...which is supreemly wierd.. IMO anyway...


can someone offer a sensible explination as to why this happens?

- -- 
Thomi Richards,
http://once.sourceforge.net/


-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.3 (GNU/Linux)

iD8DBQE/gnhW2tSuYV7JfuERAswEAJ41KZJG/qWN5omZp2KOQEb7LPuCzACffWX8
9SQz2AqEVFHQsEegjZTmvsE=
=Oaw/
-----END PGP SIGNATURE-----


From krier115 at student.liu.se  Tue Oct  7 04:50:11 2003
From: krier115 at student.liu.se (Kristoffer Erlandsson)
Date: Tue Oct  7 04:50:29 2003
Subject: [Tutor] pointers for python?
In-Reply-To: <200310072124.54876.thomi@imail.net.nz>
References: <Pine.LNX.4.44.0310061822570.29258-100000@hkn.eecs.berkeley.edu>
	<200310072124.54876.thomi@imail.net.nz>
Message-ID: <20031007085011.GA2953@n14.ryd.student.liu.se>

On Tue, Oct 07, 2003 at 09:24:54PM +1300, Thomi Richards wrote:
[snip]
> AFAIK (And I'm no expert), in C, whenever a function is called, a *copy* of 
> the variables passed to it are made, and the function uses that copy, like 
> this:
> 
> void test(int a)
> {
> 	a++;
> 	printf("Integer value + 1 is: %d\n",a);
> }
> 
> if you were to call this like so:
> 
> int t = 42;
> test(t);
> 
> this would print 43, but the variable "t" (in the main scope of the program) 
> would remain 42, because the function test() was operating on a copy of the 
> variable, not the variable itself. is this basically correct?
> 
> However, when you use pointers in C, you are passing an address in memory, 
> which can be used like a variable. However, because you are passing the 
> original address, the function operates on the original varibale, not a copy 
> (this can of course be useful when you're dealing with larger structures, as 
> it saves the program chewing memory and CPU cycles to copy something which 
> you were effectively going to change anyway).
> 
> ...which brings us back to python. Evidently, python doesn't do this, with 
> *some* types...which is supreemly wierd.. IMO anyway...
> 
> 
> can someone offer a sensible explination as to why this happens?

I think the Python reference manual says things better than if I would
try to explain them :). First some things about object identity and
such: http://www.python.org/doc/current/ref/objects.html. And then onto
the type hierarchy which lists which types are immutable and mutable
among other things: http://www.python.org/doc/current/ref/types.html.

Hope this helps.

Regards,

-- 
Kristoffer Erlandsson                               http://errl.info

From kalle at lysator.liu.se  Tue Oct  7 05:57:22 2003
From: kalle at lysator.liu.se (Kalle Svensson)
Date: Tue Oct  7 05:57:27 2003
Subject: [Tutor] pointers for python?
In-Reply-To: <200310072124.54876.thomi@imail.net.nz>
References: <Pine.LNX.4.44.0310061822570.29258-100000@hkn.eecs.berkeley.edu>
	<200310072124.54876.thomi@imail.net.nz>
Message-ID: <20031007095722.GM9058@i92.ryd.student.liu.se>

[Thomi Richards]
> ...which brings us back to python. Evidently, python doesn't do this, with 
> *some* types...which is supreemly wierd.. IMO anyway...
> 
> can someone offer a sensible explination as to why this happens?

Well, Python is really quite consistent in only passing references.
You might find
http://216.239.59.104/search?q=cache:YeykRsylhJAJ:starship.python.net/crew/mwh/hacks/objectthink.html
interesting (the starship or mwh's pages seem to be having some
problems, the original page gives me a 500 error).

Peace,
  Kalle
-- 
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.

From magnus at thinkware.se  Tue Oct  7 07:19:11 2003
From: magnus at thinkware.se (Magnus Lycka)
Date: Tue Oct  7 07:19:25 2003
Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gQ29tYm9ib3ggLSBTZXRWYWx1ZSBiYXNlZCBvbiBzZWxlY3Rpb24=?=
Message-ID: <think001_3f829c1438f0e@webmail.thinkware.se>

Andrei <project5@redrival.net> wrote:
> I have a combobox with a number of predefined items. When an item is chosen, I 
> don't want that item itself to be set as value in the text field of the 
> combobox, but a text *associated* with that item (using a dictionary). E.g. if 
> item "1" is chosen, the text field should say "one". I tried EVT_COMBOBOX, but 
> after my function is processed, the associated text is replaced by the selected 
> item again in the text field of the combobox.

I guess you are discussing the wxPython toolkit, even if I
didn't find an explicit reference. In that case I would 
suggest that you use the wxCallAfter function. (See wx.py, 
or google, it's a Python function, and thus not in the 
wxWindows docs.)

I assume that your code in the event handling changes the
combobox too early, and the standard widget processing
overwrites you change. What you have to do then, is to
define a separate function or method that sets the value 
you want. In the event handling, you use wxCallAfter to make
sure that this function is called after the event processing
for the combobox event is finished.

-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se

From op73418 at mail.telepac.pt  Tue Oct  7 08:51:17 2003
From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=)
Date: Tue Oct  7 08:49:58 2003
Subject: [Tutor] pointers for python?
In-Reply-To: <200310072124.54876.thomi@imail.net.nz>
References: <Pine.LNX.4.44.0310061822570.29258-100000@hkn.eecs.berkeley.edu>
	<200310072124.54876.thomi@imail.net.nz>
Message-ID: <l5a5ovsfi0bec1ujaf16o4uvb2c42g8d7d@4ax.com>

On Tue, 7 Oct 2003 21:24:54 +1300, you wrote:

>-----BEGIN PGP SIGNED MESSAGE-----
>Hash: SHA1

[text snnipped]

>> What we're talking about, then, is just a matter of "mutability" and
>> "immutability".  Maybe we should refocus the subject away from pointers
>> and to immutability concepts.
>>
>
>AFAIK (And I'm no expert), in C, whenever a function is called, a *copy* of 
>the variables passed to it are made, and the function uses that copy, like 
>this:
>
>void test(int a)
>{
>	a++;
>	printf("Integer value + 1 is: %d\n",a);
>}
>
>if you were to call this like so:
>
>int t = 42;
>test(t);
>
>this would print 43, but the variable "t" (in the main scope of the program) 
>would remain 42, because the function test() was operating on a copy of the 
>variable, not the variable itself. is this basically correct?
>
>However, when you use pointers in C, you are passing an address in memory, 
>which can be used like a variable. However, because you are passing the 
>original address, the function operates on the original varibale, not a copy 
>(this can of course be useful when you're dealing with larger structures, as 
>it saves the program chewing memory and CPU cycles to copy something which 
>you were effectively going to change anyway).
>
>...which brings us back to python. Evidently, python doesn't do this, with 
>*some* types...which is supreemly wierd.. IMO anyway...
>

Python treats *every* object in the same way. Repeat after me: Python
treats every object in the same way. 

 Whenever you do an assignment as in

my_var = <some Python object>

Python just adds an entry to the current namespace. Namespaces are
essentially dictionaries, so you can view the above as, in Python
syntax,

current_namespace["my_var"] = reference_to_<some Python object>

You can think of reference_to_<some Python object> as a pointer (and
under the hoods it is). Take notice though, that you can never get a
hold of the pointer itself, because Python automatically dereferences,
so that whenever you have

my_var

Python substitutes my_var by (mixing Python and C syntax freely) 

*current_namespace["my_var"]

Now, when you call a function

some_function(my_var)

Part of the function call is just adding entrance my_var in the
*local* namespace of the function, that is

some_function_namespace["my_var"] = my_var

The rhs my_var evaluated according to the rule above. So in your
example

>t = 42;
>test(t);

Python does the following (once again mixing Python and C syntax):

. Create the object 42 (in the heap)

. Stick a reference to it in the current namespace:

current_namespace["t"] = &<42>

. In calling the function test add an entry to test's namespace as in

test_namespace["t"] = &<t>

But this is, since Python automatically dereferences, 

test_namespace["t"] = &<42>

So what you have in your local namespace is just another reference to
42. No copies of objects are involved - only copies of pointers if you
want to think in terms of the above model.

Now this mental model works for *any* Python object. So suppose we
have 

>t = [];
>test(t);

So you end up, in the local namespace of test, with reference to the
*same list* referenced by t in the outer namespace. But a list is a
mutable object. This means that there are methods that change the
object inplace in contrast to immutable objects (such as numbers and
strings) where *every* method returns a *new* object -- and therefore
you can't change the original object, thus the immutability. Since a
list is mutable you can, within the body of test, do

t.append(<whatever>)

and since the outer t references the *same* list, the changes will be
visible. That is, in the outer namespace t is [<whatever>].

I hope I have made myself understood. Any other question, just holler.

With my best regards,
G. Rodrigues

From dyoo at hkn.eecs.berkeley.edu  Tue Oct  7 11:47:29 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Oct  7 11:47:36 2003
Subject: [Tutor] pointers for python?
In-Reply-To: <200310072124.54876.thomi@imail.net.nz>
Message-ID: <Pine.LNX.4.44.0310070820130.1660-100000@hkn.eecs.berkeley.edu>


> void test(int a)
> {
> 	a++;
> 	printf("Integer value + 1 is: %d\n",a);
> }
>
> if you were to call this like so:
>
> int t = 42;
> test(t);



Hi Thomi,


Ok, looks like we can talk C code then.  *grin*


When we say something like this in Python:

###
def test(a):
    a = a + 1
    print a

if __name__ == '__main__':
    a = 42
    test(a)
    print a
###



A really rough translation to C code might be something like this:

###
int* makeIntObject(int number) {
    int* result = (int*)(malloc(sizeof(int)));
    *result = number;
    return result;
}


void test(int *a) {
    a = makeIntObject(*a + 1);
    printf("%d\n", *a);
}


void main() {
    int* a = makeIntObject(42);
    test(a);
    printf("%d\n", *a);
}
###


In Python, all names are actually represented as pointers to objects on
the heap --- none of the Python objects are actually on the stack!



What's important to see is that Python treats certain types as
"immutable": the language provides no way of mutating an immutable object.
For example, when we say:

###
a = a + 1
###

what is actually happening is the construction of a new integer, not the
overwriting of an old one.  '+' is defined as an operation that constructs
a new integer object, given two integer operands.



To see this more clearly, we can use a builtin() function called id()
that's equivalent to the 'address-of' (&) operator in C:

###
>>> a = 42
>>> b = a
>>> id(a)
135364256
>>> id(b)
135364256
###

The object pointed to by both 'a' and 'b' are identical: the integer "box"
lives at location 135364256.  But when we start doing arithmetic:

###
>>> a = a + 1
>>> id(a)
135364184
>>> id(b)
135364256
###

the object that 'a' points to now is distinct from what it originally
pointed to.




> this would print 43, but the variable "t" (in the main scope of the
> program)  would remain 42, because the function test() was operating on
> a copy of the variable, not the variable itself. is this basically
> correct?

Not exactly: what's happening is that arithmetic in Python constructs a
whole new integer.  You're probably thinking:


    a
  ------
  | 42 |
  ------


But what Python is actually doing is more like:

                     ------
    a -------------->| 42 |
                     ------


It's all uniform, which is what allows Python lists to contain all kinds
of things without wackiness.  When we say:

###
l = [1, 'two']
###


we can model this as:


    l --------------->  ---------
                        | . | . |
                        --+---+--
                          |   \
                          |    \
                          |     \
                          V      V
                       -----    ---------
                       | 1 |    | "two" |
                       -----    ---------

It has to be pointers, or else Python lists wouldn't be able to hold
different types of objects.



Integers manipulation is all "immutable" because the language provides no
way of mutating a number.  This idea might be clearer with tuples, which
are also immutable:

###
>>> t = (1, 2, 3)
>>> t[0] = 42
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: object doesn't support item assignment
###


Same idea --- the type doesn't allow internal mutation, although it's
perfectly ok to redirect 't' by constructing another tuple out of the
pieces of the old one:

###
>>> t = (42,) + t[1:]
>>> t
(42, 2, 3)
###



Anyway, hope this clears some of the confusion!  (Or at least, doesn't
contribute to the confusion... *grin*)  Please feel free to ask more
questions about this; it is a slightly confusing topic if you're coming
from a C background, but it should make sense very soon.


Good luck!


From jim_938 at hotmail.com  Tue Oct  7 15:22:52 2003
From: jim_938 at hotmail.com (Jimmy verma)
Date: Tue Oct  7 15:22:56 2003
Subject: [Tutor] conversion to a fixed_no
Message-ID: <Sea1-F158yRkUHgTVdB00012819@hotmail.com>

I am intending to give the input in the form of a floating point no.  So if 
u are considering

L, R to be

12.099994020394 sthing like this.

L be given the value 12 and R be given the value towards the right of 
decimal point.

I hope i am interpreting L,R rightly.

Can you please elaborate a bit more about your suggestion.

Also what will this code do?? just for the sake of discussing further:

def fix_num(input):
	   # To convert a no into a fixed one.
	   val=input*16*(1<<16)
	   return val

Thanks a lot for discussing my problem.

With best regards,

J+



At 02:27 AM 10/6/2003, james roy wrote:

Hello,

I am new to python and is having some problem while writing some module in 
python. Actually i am writing a code in which i am needed to convert a no. 
into a fixed_no where the fixed_no's specification is like this:


fixed_no is a 32-bit representation of a binary fraction. A fixed_no is a 
signed quantity, with the two's complement of the entire word used to 
represent negation. Of the 32 bits in a fixed_no, exactily 12 are to the 
left of the binary point; thus the largest fixed_no value is 2048-2^(-20), 
and the smallest is -2048.

Can someone suggest me sthing regarding writing a module to convert a 
no.into a fixed_no according to the way i have written above.

In what form is the input to this process?

For the sake of discussion I will assume you start with 2 integers (L,R), 
one representing the part to the left and the other the part to the right. 
Ignoring sign for now, the desired result is L<<12 + R.

How will you express the sign? Will either L or R be negative or is there a 
third parameter to indicate the sign?

Bob Gailer
bgailer@alum.rpi.edu
303 442 2625

_________________________________________________________________
Buy now! Receive a gold coin on Dhan Teras. 
http://server1.msn.co.in/features/general/dhanteras/index.asp Celebrate 
prosperity!


From erikprice at mac.com  Tue Oct  7 22:58:25 2003
From: erikprice at mac.com (Erik Price)
Date: Tue Oct  7 22:36:57 2003
Subject: [Tutor] Private and Public variables
In-Reply-To: <ofs2ovsodni9ph8esnech8g63up344404e@4ax.com>
Message-ID: <491E1DD1-F93B-11D7-824C-00039351FE6A@mac.com>


On Monday, October 6, 2003, at 10:06  AM, Gon?alo Rodrigues wrote:

> I tend to make this "mistake" a lot. I started using Python when
> Python 2.2 came out, when, in particular, properties became available.
> My experience was mostly in Java where I really was paranoid about
> data hiding. These Java habits were carried along and made their
> imprint on my Python code, but what's more important, after 2 years
> they are still with me. I think one of the reason's why is because I
> tend to favor (following the gang of 4) composition to inheritance. As
> such, it is very important that my classes have clean and small
> interfaces, leaking as little as possible to the outside world. These
> interfaces should also be "recognizable", e.g. they follow the
> interfaces of the Python objects as much as possible. A simple
> example: whenever I have an iterable container that I want to make
> mutable I had methods:
>
> def append(self, elem):
>     """Append an element."""
>     <whatever>
>
> def remove(self, elem):
>     """Remove an element."""
>     <whatever>
>
> So, what do you guys think?

I am the exact same way.  Also a Java programmer primarily (who covets 
Python and is attempting to convert his cow-orkers from Perl), I 
definitely use too many getters and setters in Python due to Java 
habits.  And I also tend to use a lot of delegation and composition, so 
I end up masking everything behind an interface.  Basically I need to 
learn to relax more when I'm using Python.


Erik


From erikprice at mac.com  Wed Oct  8 06:55:55 2003
From: erikprice at mac.com (Erik Price)
Date: Wed Oct  8 06:33:56 2003
Subject: [Tutor] Code critique?  [Red-Black balanced binary trees]
In-Reply-To: <Pine.LNX.4.44.0310062240340.6947-100000@hkn.eecs.berkeley.edu>
Message-ID: <FE086F6A-F97D-11D7-824C-00039351FE6A@mac.com>


On Tuesday, October 7, 2003, at 01:59  AM, Danny Yoo wrote:

> so the code comes with a few unit tests.  Can anyone help me by 
> critiquing
> the implementation and suggesting other good things to test?

Hm.  I can't speak to anything about red black trees.  But I am curious 
why you did not make left_rotate and right_rotate methods of a Node 
rather than functions that accept a Node and perform a side effect upon 
it.  You chose the same approach with the tree_* functions (rather than 
putting them in Tree).  I can only assume you had a reason to choose 
this approach.



Erik

PS: thanks for providing an example of using unittest, I had been 
meaning to look at this module at some point but my scripts tended to 
be small enough to test using simple assert code in an "if __name__ == 
'__main__'" section.  But the unittest module is familiar, like JUnit, 
so I will probably use that from now on.


From del_dr at yahoo.com  Wed Oct  8 12:01:15 2003
From: del_dr at yahoo.com (D P)
Date: Wed Oct  8 12:01:21 2003
Subject: [Tutor] processing WSDL files
Message-ID: <20031008160115.26107.qmail@web40902.mail.yahoo.com>

hi all!

could someone explain why do I have this traceback
while trying to import an wsdl file?


>>> import WebService
>>> policy=WebService.ServiceProxy
(<link_to_wsdl_http_location>)

Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
  File "C:\Python22\Lib\site-packages\WebService.py",
line 58, in ServiceProxy
    return soap.get_proxy(cached_wsdl)
  File "C:\Python22\Lib\site-packages\soapy\soap.py",
line 245, in get_proxy
    return WSDLProxy(uri)
  File "C:\Python22\Lib\site-packages\soapy\soap.py",
line 304, in __init__
    self._get_methods(servicenode)
  File "C:\Python22\Lib\site-packages\soapy\soap.py",
line 412, in _get_methods
   
method.setRequestType(porttype[method_name]['input'])
  File "C:\Python22\Lib\site-packages\soapy\soap.py",
line 159, in setRequestType
    self.addParam(key,type.members[key])
  File "C:\Python22\Lib\site-packages\soapy\soap.py",
line 150, in addParam
    if not
(self.all_namespaces.has_key(type.namespace)):
AttributeError: 'NoneType' object has no attribute
'namespace'
>>> 


thanks in advance!
del

__________________________________
Do you Yahoo!?
The New Yahoo! Shopping - with improved product search
http://shopping.yahoo.com

From idiot1 at netzero.net  Wed Oct  8 12:20:21 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Wed Oct  8 12:19:26 2003
Subject: [Tutor] css in web software
Message-ID: <3F843945.80701@netzero.net>

OK, I am adding some css to my 2 wiki programs. Alas, it works fine in Internet 
Exploiter, but the hover effect will not operate on the Netscape Navelgator 
browser, no matter what I manage to do. Here is a sample of the header which is 
currently output by the software (I am using imbedded css):

<html><head><title>MiniWiki - WikiNature</title>
<style type="text/css">
body { margin-left: 5%; margin-right: 5%; }
A { text-decoration: none; }  A:link, A:visited,  A:active text-decoration:none; }
A:hover { background-color: #D0D0FF; }
</style></head>
<body bgcolor="FFFFFF" text="000000" links="0000FF">
<table width=100% bgcolor="FFE0C0" border="0" cellpadding="10"><tr><td>
<b><font size="4" color="FF0000">MiniWiki</font></b>
<center><font size="6"><a href="./MWbacksearch.py?WikiNature">Wiki 
Nature</a></font><br>
(Click for backsearch)<p></center></td></tr></table>

Everything works in ie; the hover does not work for NS. Anyone got some 
clueatude to share?

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Prometheus
  +                              kniht                                +

Fnord.


From glingl at aon.at  Wed Oct  8 11:55:13 2003
From: glingl at aon.at (Gregor Lingl)
Date: Wed Oct  8 12:29:46 2003
Subject: [Tutor] cross sum toying 
Message-ID: <3F843361.2060203@aon.at>

Hi!

Within one hour of cross sum toying with Python 2.3 ;-)
I came up with four functions for calculating the crossum
of a nonnegative integer:

def cross_sum1(a):
    # drawback: uses conversion to string
    return sum([int(digit) for digit in str(a)])

from math import log10
def cross_sum2(a):
    #drawback: uses math
    return sum([a%10**(i+1)//10**i for i in range(1+int(log10(1+a)))])

def cross_sum3(a):
    # drawback: uses recursion
    if a:
        return a%10 + cross_sum3(a//10)
    return 0

def cross_sum4(a):
    # drawback: (almost) classical
    s = 0
    while a:
        a, digit = divmod(a, 10)
        s += digit
    return s


Do you have a more beautiful, a substantially
different or even a more Pythonic one?

Gregor




From pythontutor at venix.com  Wed Oct  8 13:27:04 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Wed Oct  8 13:27:16 2003
Subject: [Tutor] cross sum toying
In-Reply-To: <3F843361.2060203@aon.at>
References: <3F843361.2060203@aon.at>
Message-ID: <3F8448E8.2060304@venix.com>

Not sure why you're unhappy with version 4.  It can be split into a
digit generator and a summer:

 >>> def digit_generator(a,base=10):
... 	a = abs(a)
... 	while a:
... 		a,d = divmod(a,base)
... 		yield d

(import operator)
 >>> def cross_sum(a):
... 	return reduce(operator.add,digit_generator(a),0)

Both versions 3 and 4 can be easily generalized to support other number bases.

I added a 0 to initialize reduce, the other alternative I considered was to
have an else with the while in the generator to always produce a (leading) zero.
	else:
		yield 0

Hope this helps.

Gregor Lingl wrote:

> Hi!
> 
> Within one hour of cross sum toying with Python 2.3 ;-)
> I came up with four functions for calculating the crossum
> of a nonnegative integer:
> 
> def cross_sum4(a):
>    # drawback: (almost) classical
>    s = 0
>    while a:
>        a, digit = divmod(a, 10)
>        s += digit
>    return s
> 
> 
> Do you have a more beautiful, a substantially
> different or even a more Pythonic one?
> 
> Gregor
> 
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582


From glingl at aon.at  Wed Oct  8 14:13:44 2003
From: glingl at aon.at (Gregor Lingl)
Date: Wed Oct  8 14:15:36 2003
Subject: [Tutor] cross sum toying
In-Reply-To: <3F8448E8.2060304@venix.com>
References: <3F843361.2060203@aon.at> <3F8448E8.2060304@venix.com>
Message-ID: <3F8453D8.1070902@aon.at>


Lloyd Kvam schrieb:

> Not sure why you're unhappy with version 4.  It can be split into a
> digit generator and a summer:
>
> >>> def digit_generator(a,base=10):
> ...     a = abs(a)
> ...     while a:
> ...         a,d = divmod(a,base)
> ...         yield d
>
> (import operator)
> >>> def cross_sum(a):
> ...     return reduce(operator.add,digit_generator(a),0)

Very interesting, very nice!

When working with Python 2.3, I can use the now built in  sum:

def cross_sum5(a):
    return sum([digit for digit in digit_generator(a)])

Thanks for the idea!
I've added this to my collection.
BTW, I was not really unhappy but interested in different
ways to handle this problem.

Maybe the cross sum zoo will continue growing ...
... although there should be one -- and preferably only one --
obvious way to do it? ;-)

Regards, Gregor



From bwalling at coastdental.com  Wed Oct  8 14:58:22 2003
From: bwalling at coastdental.com (Benjamin Walling)
Date: Wed Oct  8 14:58:28 2003
Subject: [Tutor] css in web software
Message-ID: <61119D047A3FE84E83EF2FFDA9A156A4862300@cstntexch01.coastdental.lan>

A:link, A:visited,  A:active { text-decoration:none; } 

You are missing the opening curly bracket for the text above.  Making
this change causes it to work for me in Mozilla Firebird.  I do not have
Netscape installed, but the rendering engine is (nearly) the same.

Netscape/Mozilla are not as forgiving as IE in terms of bad HTML.

-----Original Message-----
From: Kirk Bailey [mailto:idiot1@netzero.net] 
Sent: Wednesday, October 08, 2003 12:20 PM
To: Tutor
Subject: [Tutor] css in web software

OK, I am adding some css to my 2 wiki programs. Alas, it works fine in
Internet Exploiter, but the hover effect will not operate on the
Netscape Navelgator browser, no matter what I manage to do. Here is a
sample of the header which is currently output by the software (I am
using imbedded css):

<html><head><title>MiniWiki - WikiNature</title> <style type="text/css">
body { margin-left: 5%; margin-right: 5%; } A { text-decoration: none; }
A:link, A:visited,  A:active text-decoration:none; } A:hover {
background-color: #D0D0FF; } </style></head> <body bgcolor="FFFFFF"
text="000000" links="0000FF"> <table width=100% bgcolor="FFE0C0"
border="0" cellpadding="10"><tr><td> <b><font size="4"
color="FF0000">MiniWiki</font></b>
<center><font size="6"><a href="./MWbacksearch.py?WikiNature">Wiki
Nature</a></font><br>
(Click for backsearch)<p></center></td></tr></table>

Everything works in ie; the hover does not work for NS. Anyone got some
clueatude to share?

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Prometheus
  +                              kniht                                +

Fnord.


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

From pythontutor at venix.com  Wed Oct  8 15:47:15 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Wed Oct  8 15:47:22 2003
Subject: [Tutor] css in web software
In-Reply-To: <61119D047A3FE84E83EF2FFDA9A156A4862300@cstntexch01.coastdental.lan>
References: <61119D047A3FE84E83EF2FFDA9A156A4862300@cstntexch01.coastdental.lan>
Message-ID: <3F8469C3.1040803@venix.com>

http://validator.w3.org/
The W3C MarkUp Validation Service

While getting your HTML to be fully compliant can be a pain, my experience
is that it pretty much eliminates browser problems.

Benjamin Walling wrote:

> A:link, A:visited,  A:active { text-decoration:none; } 
> 
> You are missing the opening curly bracket for the text above.  Making
> this change causes it to work for me in Mozilla Firebird.  I do not have
> Netscape installed, but the rendering engine is (nearly) the same.
> 
> Netscape/Mozilla are not as forgiving as IE in terms of bad HTML.
> 
> -----Original Message-----
> From: Kirk Bailey [mailto:idiot1@netzero.net] 
> Sent: Wednesday, October 08, 2003 12:20 PM
> To: Tutor
> Subject: [Tutor] css in web software
> 
> OK, I am adding some css to my 2 wiki programs. Alas, it works fine in
> Internet Exploiter, but the hover effect will not operate on the
> Netscape Navelgator browser, no matter what I manage to do. Here is a
> sample of the header which is currently output by the software (I am
> using imbedded css):
> 
> <html><head><title>MiniWiki - WikiNature</title> <style type="text/css">
> body { margin-left: 5%; margin-right: 5%; } A { text-decoration: none; }
> A:link, A:visited,  A:active text-decoration:none; } A:hover {
> background-color: #D0D0FF; } </style></head> <body bgcolor="FFFFFF"
> text="000000" links="0000FF"> <table width=100% bgcolor="FFE0C0"
> border="0" cellpadding="10"><tr><td> <b><font size="4"
> color="FF0000">MiniWiki</font></b>
> <center><font size="6"><a href="./MWbacksearch.py?WikiNature">Wiki
> Nature</a></font><br>
> (Click for backsearch)<p></center></td></tr></table>
> 
> Everything works in ie; the hover does not work for NS. Anyone got some
> clueatude to share?
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582


From alan.gauld at blueyonder.co.uk  Wed Oct  8 16:02:34 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Wed Oct  8 16:01:47 2003
Subject: [Tutor] Private and Public variables
References: <Sea1-F39skKwaenTosf0000dcaa@hotmail.com>
	<ofs2ovsodni9ph8esnech8g63up344404e@4ax.com>
Message-ID: <001e01c38dd7$1d5153a0$6401a8c0@xp>

> What are your experiences in using protected and private attributes?

In C++ you choose. In Smalltalk all attributes are private.
In early OO LISP and DElphi all attributes were public by default.
In Python all attributes are public by default but tricks exist
to make them private(ish).


In practice I don't find any difference in any of the approaches
because as a matter of good practice I access data via methods.
That is I do not use methods like getXXX very often but manipulate
data via behaviour of the object. In al;most every case where a lot of
getXXX/setXXX methods are being used then the law of demeter is
being broken and the basic OOD should be revisited.

> My experience was mostly in Java where I really was paranoid about
> data hiding. These Java habits were carried along

I'm not sure why Java is so paranoid but it does produice an
extremely verbose style of programming. This is one reason
why Java programmers nearly always wind up writing more code
that C++ programmers for the same project! (IMHO)

> they are still with me. I think one of the reason's why is because I
> tend to favor (following the gang of 4) composition to inheritance.

What does that have to do with data hiding (the correct term
for private data)?

> such, it is very important that my classes have clean and small
> interfaces, leaking as little as possible to the outside world.

Clean an small is a good principle, but has nothing(much) to do with
data hiding. It only becomes significant when you define the interface
as being anything that is technically accessible rather than the
published set of methods. If the class author tells you not to use
methods other that X,Y or Z then those are the inteface, use
anything else and you have broken it. Do you want a police state
or one where you can exercise free concience?

> interfaces should also be "recognizable", e.g. they follow the
> interfaces of the Python objects as much as possible.

Again an excellent design principle.

> So, what do you guys think?

I think your design ideas are correct, the need for data hiding
and the implied distrust of your fellow programmers is perhaps
more questionable.

But if you design classes to expose a behavioural interface
then the ability or lack of to directly access data will not
be of any concern to your users.

For example how often do you even think about accessing the
internal data of a file object? Do you even know what
attributes are there? Do you care?

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


From alan.gauld at blueyonder.co.uk  Wed Oct  8 16:16:23 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Wed Oct  8 16:15:33 2003
Subject: [Tutor] Private and Public variables
References: <491E1DD1-F93B-11D7-824C-00039351FE6A@mac.com>
Message-ID: <005001c38dd9$0bcfc010$6401a8c0@xp>

> definitely use too many getters and setters in Python due to Java
> habits.  And I also tend to use a lot of delegation and composition,
> so I end up masking everything behind an interface.

It sounds like you use too many getters and setters period!
:-)

You should very rarely need to get data from an object.
The object is responsible for managing its own data, if you
are pulling the data out and manipulating it *in any way*
outside of the object then that is bad OOD. Get the object
to do it to itself via a descriptively named method.

If you want the data to feed to another object's method then
again there's something wrong and that methjod probably should
be taking an object as parameter not a primitive value.
Unfortunately this is where languages like Javca/C++ become
unstick because their static type system requires specific
types to be passed so we wind up being forced to extract
more data than should be necessary...

The other broken feature of Java which encourages this
getter/setter business is the fact that Java breans are
defined in terms of a getter/setter inteface to allow
IDEs to build data discovery/introspection mechanisms.

Unfortunately these methods then get mistakenly considered
to be part of the geneal class interface. It might have been
better if Java had used some kind of a IDE keyword to indicate
that these methods should only be used by tool builders! :-(

> learn to relax more when I'm using Python.

That and focussing on defining class behaviours, both in Python
and in Java. Every time you write a metod called getXXX or setXXX
consider why you need it. Could the class itself be doing it
internally via a higher level interface function?

BTW The book "The Pragmatic Programmer" by Hunt and Thomas
covers this topic in more depth. As do many of the writings
of Peter Coad.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


From erikprice at mac.com  Wed Oct  8 23:32:16 2003
From: erikprice at mac.com (Erik Price)
Date: Wed Oct  8 23:10:20 2003
Subject: [Tutor] Private and Public variables
In-Reply-To: <005001c38dd9$0bcfc010$6401a8c0@xp>
Message-ID: <2DC744E0-FA09-11D7-AF86-00039351FE6A@mac.com>


On Wednesday, October 8, 2003, at 04:16  PM, Alan Gauld wrote:

> It sounds like you use too many getters and setters period!
> :-)

You're probably right but...

> You should very rarely need to get data from an object.
> The object is responsible for managing its own data, if you
> are pulling the data out and manipulating it *in any way*
> outside of the object then that is bad OOD. Get the object
> to do it to itself via a descriptively named method.

I understand this in principle and I agree.  However, it seems to me 
that in some situations, this creates a tight coupling between the 
object that contains the data and the object making use of it.  For 
instance, say you have a DatabaseRecord object that has been returned 
by the database API (and say it is a 3rd party API, and the support 
contract is invalidated if you modify the source code).  If you need to 
get the content of the DatabaseRecord, you probably want to call 
getValue or something.  This can be used portably in many different 
parts of the application, because there might be many aspects of the 
application that need a String from the database -- however, if you try 
to add a method to DatabaseRecord for every case where you need to do 
something with the data, then DatabaseRecord becomes clunky and tightly 
coupled to the client code that calls it.

In many cases, I agree -- get the object itself to perform the 
appropriate behavior.  But there are times when you simply want to get 
some element of the data contained by an object.

> The other broken feature of Java which encourages this
> getter/setter business is the fact that Java breans are
> defined in terms of a getter/setter inteface to allow
> IDEs to build data discovery/introspection mechanisms.

Good observation.

> Unfortunately these methods then get mistakenly considered
> to be part of the geneal class interface. It might have been
> better if Java had used some kind of a IDE keyword to indicate
> that these methods should only be used by tool builders! :-(

A great idea -- I never really thought of this before, btw.

>
>> learn to relax more when I'm using Python.
>
> That and focussing on defining class behaviours, both in Python
> and in Java. Every time you write a metod called getXXX or setXXX
> consider why you need it. Could the class itself be doing it
> internally via a higher level interface function?
>
> BTW The book "The Pragmatic Programmer" by Hunt and Thomas
> covers this topic in more depth. As do many of the writings
> of Peter Coad.

Your advice is good, and reminds me of another good book on writing 
better code that I am still reading: "Refactoring" by Fowler.  I will 
have to check out the Pragmatic Programmer sometime, but I am not in a 
hurry to learn Ruby (though someday I would like to).


Erik


From alan.gauld at blueyonder.co.uk  Thu Oct  9 03:26:46 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Thu Oct  9 03:28:07 2003
Subject: [Tutor] Private and Public variables
References: <2DC744E0-FA09-11D7-AF86-00039351FE6A@mac.com>
Message-ID: <006401c38e36$b23a01b0$6401a8c0@xp>

> > The object is responsible for managing its own data,
>
> instance, say you have a DatabaseRecord object that has been
returned
> by the database API

OK, Good example of a special case. In these situations you
should probably be hiding the database record object inside
an application specific class which provides the behaviour.

Thus most code will talk to the "customer" object or "order"
object or whatever and only the entity objects will use the
database API internally.

> get the content of the DatabaseRecord, you probably want to call
> getValue or something..... because there might be many aspects of
the
> application that need a String from the database

And even here, as you have just pointed out, the getValue method
is a valid description of behaviour( especially in Java) since
the actual data inside the record will be a float, int or String.
"getValue" is in fact not a data access method but a generic
behaviour that just happens to have "get" in its name, it could
have been just as validly called just "value"

foo = record.value()

as opposed to

foo = record.getValue()

> to add a method to DatabaseRecord for every case where you need to
do
> something with the data, then DatabaseRecord becomes clunky and
tightly
> coupled to the client code that calls it.

Yes, the generic behaviour getValue requires that you provide a method
per type (possibly via polymorphism and/or subclassing) but not one
for
every application level access.

> appropriate behavior.  But there are times when you simply want to
get
> some element of the data contained by an object.

And your example is a good one, but only in so far as the internals
of a single object go. Really using databases is a way of providing
persistence to objects, if you had an OO database you wouldn't need
these record objects at all you'd simply instantiate the objects
directly from the database. Indeed you should still do that but in
the constructor do all the database access stuff. Unfortunately
with an RDBMS that often results in inefficient code... so we
compromise with database APIs etc.

> have to check out the Pragmatic Programmer sometime, but I am not in
a
> hurry to learn Ruby (though someday I would like to).

PP doesn't have a lot of Ruby in it, in fact it has more C++
and Java than Ruby code. In fact from a quick  flick through
I couldn't see *any* Ruby...

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


From erikprice at mac.com  Thu Oct  9 06:14:41 2003
From: erikprice at mac.com (Erik Price)
Date: Thu Oct  9 05:52:42 2003
Subject: [Tutor] Private and Public variables
In-Reply-To: <006401c38e36$b23a01b0$6401a8c0@xp>
Message-ID: <654DD218-FA41-11D7-AF86-00039351FE6A@mac.com>


On Thursday, October 9, 2003, at 03:26  AM, Alan Gauld wrote:

> PP doesn't have a lot of Ruby in it, in fact it has more C++
> and Java than Ruby code. In fact from a quick  flick through
> I couldn't see *any* Ruby...

Oh.  I must be thinking of some other book -- I could have sworn they 
had a book like this that only used Ruby.



Erik


From alan.gauld at blueyonder.co.uk  Thu Oct  9 06:09:58 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Thu Oct  9 06:11:41 2003
Subject: [Tutor] Private and Public variables
References: <654DD218-FA41-11D7-AF86-00039351FE6A@mac.com>
Message-ID: <007d01c38e4d$7e9e37b0$6401a8c0@xp>

> Oh.  I must be thinking of some other book -- I could have sworn
they
> had a book like this that only used Ruby.

The same two authors wrote the first significant English book
on Ruby (now available online too*) and are huge Ruby advocates,
but the Pragmatic Programmer is largely not about languages
per se but about general good software practice.

Alan G.

(*)
http://www.rubycentral.com/book/index.html


From tbstep at tampabay.rr.com  Thu Oct  9 06:28:50 2003
From: tbstep at tampabay.rr.com (Todd Stephens)
Date: Thu Oct  9 06:32:52 2003
Subject: [Tutor] Private and Public variables
In-Reply-To: <654DD218-FA41-11D7-AF86-00039351FE6A@mac.com>
References: <654DD218-FA41-11D7-AF86-00039351FE6A@mac.com>
Message-ID: <200310090628.50206.tbstep@tampabay.rr.com>

On Thursday 09 October 2003 06:14 am, Erik Price wrote:

>  Oh.  I must be thinking of some other book -- I could have sworn
> they had a book like this that only used Ruby.

Easily confused as the book you are thinking of is "Programming Ruby - 
The Pragmatic Programmer's Guide".


-- 
Todd Stephens
"Good people do not need laws to tell them to act responsibly, 
while bad people will find a way around the laws." - Plato


From ronan at melim.com.br  Thu Oct  9 07:53:23 2003
From: ronan at melim.com.br (Ronan Lucio)
Date: Thu Oct  9 07:52:40 2003
Subject: [Tutor] Web development
Message-ID: <200310090853.23429.ronan@melim.com.br>

Hello folks,

Does someone develop web applications in Python?

I'd like to know how can I manipulate users in a web application.
Should I use cookies?
I have read about cookies but I seems that cookies works
with expiration time. So, if it's true, if a user closes its browser,
isn't it be loged on automatcly, once the expiration time didn't
end up?

And if I set a little expiration time, will the user be loged for
the next page?

If some could point me to a documentation that clarify my mind,
it also would be great.

Thanks,
Ronan

From bwalling at coastdental.com  Thu Oct  9 08:07:30 2003
From: bwalling at coastdental.com (Benjamin Walling)
Date: Thu Oct  9 08:08:42 2003
Subject: [Tutor] Web development
Message-ID: <61119D047A3FE84E83EF2FFDA9A156A4862303@cstntexch01.coastdental.lan>

There are two types of cookies: session and (semi) permanent.  Session
cookies are good for the extent of time that a user is visiting your
site.  In some browsers, this includes the entire length of time the
browser is open, so if they visit your site, go somewhere else and come
back, the cookie is still valid.  If you do not set an expiration date,
what you get is a session cookie.  Permanent cookies will stay on the
user's machine until the expiration date that you set.  This means that
if they close the browser, reboot, etc, your cookie is still there.

Generally, web applications are stateless, and you do not know who is
really on your website, you would only know the last time each user
requested a page.  You could then infer who you considered to be on your
site by assuming that anyone that has requested a page in the last 5
minutes is on your website.

As far as logging, you can find the cookie information in your
webserver's logs (IIS, Apache, etc), or you can log page requests
yourself.

You have little to no visibility that they have closed their browser or
navigated to another site.  You can attempt some magic here with
JavaScript, but I don't find it to be reliable.

-----Original Message-----
From: Ronan Lucio [mailto:ronan@melim.com.br] 
Sent: Thursday, October 09, 2003 7:53 AM
To: tutor@python.org
Subject: [Tutor] Web development

Hello folks,

Does someone develop web applications in Python?

I'd like to know how can I manipulate users in a web application.
Should I use cookies?
I have read about cookies but I seems that cookies works with expiration
time. So, if it's true, if a user closes its browser, isn't it be loged
on automatcly, once the expiration time didn't end up?

And if I set a little expiration time, will the user be loged for the
next page?

If some could point me to a documentation that clarify my mind, it also
would be great.

Thanks,
Ronan

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

From ronan at melim.com.br  Thu Oct  9 09:12:42 2003
From: ronan at melim.com.br (Ronan Lucio)
Date: Thu Oct  9 09:11:59 2003
Subject: [Tutor] Web development
In-Reply-To: <61119D047A3FE84E83EF2FFDA9A156A4862303@cstntexch01.coastdental.lan>
References: <61119D047A3FE84E83EF2FFDA9A156A4862303@cstntexch01.coastdental.lan>
Message-ID: <200310091012.42245.ronan@melim.com.br>

Benjamin,

Thank you very much by the good answer... :-)

Ronan

Em Qui 09 Out 2003 09:07, Benjamin Walling escreveu:
> There are two types of cookies: session and (semi) permanent.  Session
> cookies are good for the extent of time that a user is visiting your
> site.  In some browsers, this includes the entire length of time the
> browser is open, so if they visit your site, go somewhere else and come
> back, the cookie is still valid.  If you do not set an expiration date,
> what you get is a session cookie.  Permanent cookies will stay on the
> user's machine until the expiration date that you set.  This means that
> if they close the browser, reboot, etc, your cookie is still there.
>
> Generally, web applications are stateless, and you do not know who is
> really on your website, you would only know the last time each user
> requested a page.  You could then infer who you considered to be on your
> site by assuming that anyone that has requested a page in the last 5
> minutes is on your website.
>
> As far as logging, you can find the cookie information in your
> webserver's logs (IIS, Apache, etc), or you can log page requests
> yourself.
>
> You have little to no visibility that they have closed their browser or
> navigated to another site.  You can attempt some magic here with
> JavaScript, but I don't find it to be reliable.
>
> -----Original Message-----
> From: Ronan Lucio [mailto:ronan@melim.com.br]
> Sent: Thursday, October 09, 2003 7:53 AM
> To: tutor@python.org
> Subject: [Tutor] Web development
>
> Hello folks,
>
> Does someone develop web applications in Python?
>
> I'd like to know how can I manipulate users in a web application.
> Should I use cookies?
> I have read about cookies but I seems that cookies works with expiration
> time. So, if it's true, if a user closes its browser, isn't it be loged
> on automatcly, once the expiration time didn't end up?
>
> And if I set a little expiration time, will the user be loged for the
> next page?
>
> If some could point me to a documentation that clarify my mind, it also
> would be great.
>
> Thanks,
> Ronan
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 

Ronan Lucio
Melim Internet Provider
 

From python at rcn.com  Thu Oct  9 09:35:41 2003
From: python at rcn.com (Raymond Hettinger)
Date: Thu Oct  9 09:36:21 2003
Subject: [Tutor] cross sum toying
In-Reply-To: <3F8448E8.2060304@venix.com>
Message-ID: <000001c38e6a$3c2a7980$e841fea9@oemcomputer>


Here is one more version to play with:

>>> from itertools import imap
>>> def cross_sum(n, codezero=ord('0')):
	s = str(n)
	return sum(imap(ord, s)) - len(s) * codezero

>>> cross_sum(9851)
23


Raymond Hettinger




#################################################################
#################################################################
#################################################################
#####
#####
#####
#################################################################
#################################################################
#################################################################

#################################################################
#################################################################
#################################################################
#####
#####
#####
#################################################################
#################################################################
#################################################################

From dyoo at hkn.eecs.berkeley.edu  Thu Oct  9 12:28:27 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Oct  9 12:28:33 2003
Subject: [Tutor] Code critique?  [Red-Black balanced binary trees]
In-Reply-To: <FE086F6A-F97D-11D7-824C-00039351FE6A@mac.com>
Message-ID: <Pine.LNX.4.44.0310090902100.13023-100000@hkn.eecs.berkeley.edu>



On Wed, 8 Oct 2003, Erik Price wrote:

> > so the code comes with a few unit tests.  Can anyone help me by
> > critiquing the implementation and suggesting other good things to
> > test?
>
> Hm.  I can't speak to anything about red black trees.  But I am curious
> why you did not make left_rotate and right_rotate methods of a Node
> rather than functions that accept a Node and perform a side effect upon
> it.

Hi Erik,

No particular reason, actually.  I agree with you: it does make sense to
rearrange the code so that the node-rotation function are actual members
of the Node class.



> You chose the same approach with the tree_* functions (rather than
> putting them in Tree).  I can only assume you had a reason to choose
> this approach.

Nope.  *grin*


On the other hand, I'm thinking of wrapping the red-black trees using a
higher level interface, to make them look like dictionaries.  I think my
original plan was to write the base using plain old functions, and show
how one can write a nice OOP layer on top of it.



> PS: thanks for providing an example of using unittest, I had been
> meaning to look at this module at some point but my scripts tended to be
> small enough to test using simple assert code in an "if __name__ ==
> '__main__'" section.  But the unittest module is familiar, like JUnit,
> so I will probably use that from now on.

Unit testing is actually pretty fun, once you get into a diabolical frame
of mind.  *grin* It's definitely mandatory for anything serious I write
now, now that I've seen how many bugs actually get stomped by good unit
tests!


As a concrete example, when I read the initial pseudocode for doing
insertion into the Red-Black tree, I actually misread some of the
indentation.  The pseudocode in "Introduction to Algorithms" looked
something like this:

    else if z = right[p[z]]
         then z <- p[z]
              left-rotate(T, z)
         color[p[z]] <- BLACK
         color[p[p[z]]] <- RED
         right-rotate(T, p[p[z]])


And even though the pseudocode looks remarkably like Python code, I had
incorrectly transcribed this in Python as:

     elif x == x.p.right:
         x = x.p
         left_rotate(tree, x)
         x.p.color = BLACK
         x.p.p.color = RED
         right_rotate(tree, x.p.p)

Silly indentation bug.  *grin*


Thankfully, the error in this code immediately showed up as soon as I
tried inserted three elements into my structure, so I was able to pick out
the offending bug in a few minutes.



Talk to you later!


From rafael.sousa at netcabo.pt  Thu Oct  9 13:25:18 2003
From: rafael.sousa at netcabo.pt (rafael.sousa)
Date: Thu Oct  9 13:28:26 2003
Subject: [Tutor] How can I convert a bin string to a hex string?
Message-ID: <2305CFC39C15AA4896E06E5C91C509EF0299832F@VS2.hdi.tvcabo>

Such as the binary contents of a jpeg image?
 
I'm writing the code to dynamically create a RTF (Rich Text Format) document. In order to insert a picture, it's recommended in the specification that its contents are written in hex.
 
I read the binary content to a regular python string, but then I would need to convert it to another string, this time in hex (which would naturally have the double of the length of the original bin string).
 
Can anyone help?
 
Thanks in advance!

From erikprice at mac.com  Thu Oct  9 13:44:22 2003
From: erikprice at mac.com (Erik Price)
Date: Thu Oct  9 13:44:36 2003
Subject: [Tutor] Web development
Message-ID: <668593.1065721462012.JavaMail.erikprice@mac.com>

 
On Thursday, October 09, 2003, at 07:53AM, Ronan Lucio <ronan@melim.com.br> wrote:

>Hello folks,
>
>Does someone develop web applications in Python?

Sure, an interesting project for web app development is Webware.
<http://webware.sourceforge.net/>

>I'd like to know how can I manipulate users in a web application.
>Should I use cookies?

Cookies can be a convenient way of letting your webapp know which user is making that particular HTTP request.  Another way to do it is to embed an identification string into the URI of all hyperlinks in your webapp.  I would be surprised if webware did not provide a mechanism for automatically generating these kinds of URIs.

>I have read about cookies but I seems that cookies works
>with expiration time. So, if it's true, if a user closes its browser,
>isn't it be loged on automatcly, once the expiration time didn't
>end up?

You should read more about how cookies work, you can limit the lifetime of a cookie to only last as long as the current session (until the user quits the browser instance):
<http://wp.netscape.com/newsref/std/cookie_spec.html>


>And if I set a little expiration time, will the user be loged for
>the next page?
>
>If some could point me to a documentation that clarify my mind,
>it also would be great.

Hopefully the above will help answer some questions about cookies in web application development.


Erik

From dyoo at hkn.eecs.berkeley.edu  Thu Oct  9 14:02:07 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Oct  9 14:02:13 2003
Subject: [Tutor] How can I convert a bin string to a hex string?
In-Reply-To: <2305CFC39C15AA4896E06E5C91C509EF0299832F@VS2.hdi.tvcabo>
Message-ID: <Pine.LNX.4.44.0310091100270.20399-100000@hkn.eecs.berkeley.edu>



On Thu, 9 Oct 2003, rafael.sousa wrote:

> Such as the binary contents of a jpeg image?
>  I'm writing the code to dynamically create a RTF (Rich Text Format)
> document. In order to insert a picture, it's recommended in the
> specification that its contents are written in hex.
>  I read the binary content to a regular python string, but then I would
> need to convert it to another string, this time in hex (which would
> naturally have the double of the length of the original bin string).


Hi Rafael,


Ah, then the 'binascii' module should be suitable for this:

    http://www.python.org/doc/lib/module-binascii.html

The binascii.hexlify() function should be exactly what you're looking for.



Good luck!


From dyoo at hkn.eecs.berkeley.edu  Thu Oct  9 14:13:22 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Oct  9 14:13:34 2003
Subject: [Tutor] processing WSDL files
In-Reply-To: <20031008160115.26107.qmail@web40902.mail.yahoo.com>
Message-ID: <Pine.LNX.4.44.0310081312160.14940-100000@hkn.eecs.berkeley.edu>



On Wed, 8 Oct 2003, D P wrote:

> hi all!
>
> could someone explain why do I have this traceback
> while trying to import an wsdl file?
>
>
> >>> import WebService
> >>> policy=WebService.ServiceProxy(<link_to_wsdl_http_location>)


Hi D P,


I'd suspect that there's a bug in the WSDL module; it looks like part of
the software is sending the None object over to a method that doesn't
expect it.  From the traceback:


>   File "C:\Python22\Lib\site-packages\soapy\soap.py",
> line 150, in addParam
>     if not
> (self.all_namespaces.has_key(type.namespace)):
> AttributeError: 'NoneType' object has no attribute


The 'soapy' module is saying that something is not right --- 'type' here
is set to None.  But at the moment, I can't figure out the real cause of
this without more information.  In particular, you mention:


###
>>> import WebService
>>> policy=WebService.ServiceProxy(<link_to_wsdl_http_location>)
###

Can you tell us the link to the wsdl location?  If so, that'll help
enormously, since then we'll be better equipped to replicate the situation
and test a solution.



Still, you may really want to talk to the Python Web Services folks for
your question:

    http://pywebsvcs.sourceforge.net/

I'm not sure how many of us are familiar with WSDL.  But I'm positive the
Python web services folks there know what they are doing.  They have a
mailing list that you can use:

    http://sourceforge.net/mailarchive/forum.php?forum_id=1729


Good luck to you!


From camartin at snet.net  Thu Oct  9 18:11:14 2003
From: camartin at snet.net (camartin@snet.net)
Date: Thu Oct  9 18:08:19 2003
Subject: [Tutor] skipping lines
Message-ID: <3F85DD02.4060109@snet.net>

I have a piece of code that reads in a file line by line into lists. It 
then processes the file list by list and writes out the file processed 
line by processed line.  This works fine unless I have a blank line.  An 
example of the code (the actual code is more complicated but it works 
unless there are blank lines) is shown below,

# file to open CSV files or plain delimited text. As one reads
# each line convert the date to ordinal number, then write out
# the line into a CSV file
from datetime import date
import string
from string import *


filename = raw_input("Enter the filename(make sure you enter the full 
path): ")
f = open(filename,'r')
g = open("c:\python23\outtest3.txt", 'w')

   
for line in f.xreadlines():
    words = line.rstrip().split()
    S = words[9]
    print >>g,S
   

f.close()
g.close()

As I said above this writes what I expect but the error message I get is 
what one expects for a blank line namely there is no index S[9].

Traceback (most recent call last):
  File 
"C:\Python23\lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", 
line 310, in RunScript
    exec codeObject in __main__.__dict__
  File "C:\Python23\Script2.py", line 16, in ?
    S = words[9]
IndexError: list index out of range

I've tried using an  if statement on not empty line(like I can do in 
MatLab) and I've tried a bunch of other things but I've not been 
successful.  This seems so trivial but I'm not getting it.

Thanks in advance.

Cliff







   



From brian_ashley99 at hotmail.com  Fri Oct  3 01:16:03 2003
From: brian_ashley99 at hotmail.com (brian ashley)
Date: Thu Oct  9 20:18:03 2003
Subject: [Tutor] Can you clarify these terms
Message-ID: <Sea2-F9YVlLwpnkFyVX00002b3d@hotmail.com>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20031003/8582e7c1/attachment.html
From DLLBIA001 at mail.uct.ac.za  Sun Oct  5 07:30:52 2003
From: DLLBIA001 at mail.uct.ac.za (UCT Student - DLLBIA001)
Date: Thu Oct  9 20:18:09 2003
Subject: [Tutor] Random numbers
Message-ID: <3F8000EC.5C49E947@mail.uct.ac.za>

Hi!
i was just wandring if you could not help me to generate 25 random
numbers in the range of 0 to 24 without any number repeating.
if i were then to put this numbers onto a grid with 25 squares how would
i go about it. the grid and squares have already been made but how to
place the numbers i am uncertain of.
thank you 
Bianca

From gulasachet at hotmail.com  Sun Oct  5 12:26:43 2003
From: gulasachet at hotmail.com (cordillia contessa)
Date: Thu Oct  9 20:18:14 2003
Subject: [Tutor] barcode creation
Message-ID: <LAW12-OE270WDg88nN600002cb0@hotmail.com>

I have to create barcode but have no slight idea of what is needed and how to create it. Help... Anyone...
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20031006/a4c5867f/attachment.html
From James.McCarney at bnc.ca  Mon Oct  6 14:11:57 2003
From: James.McCarney at bnc.ca (James.McCarney@bnc.ca)
Date: Thu Oct  9 20:18:17 2003
Subject: [Tutor] Traceback error in os.remove
Message-ID: <OF0F81D500.1BB0B008-ON85256DB7.00638FD8@bnc.ca>

In my script I get the following error....

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in -toplevel-
    os.remove("Z:/Foo & D?ploiement/Foo/Rel?ve foo/Fooooooo/Foo de 
rel?ve/foo_de_rel?ve_chm.bak")
OSError: [Errno 2] No such file or directory: 'Z:/Foo & 
D\xe9ploiement/Foo/Rel\xe8ve foo/Fooooooo/Foo de 
rel\xe8ve/foo_de_rel\xe8ve_chm.bak'

It appears that Python is having difficulty interpreting diacritical 
marks.... Any way to get it to behave?

Thanks all
Merci et meilleures salutations.

James Alexander (Alex) McCarney, conseiller CGI
s/GRT & CMI, Banque Nationale du Canada 
mailto:james.mccarney@bnc.ca
mailto:james.mccarney@cgi.com
T?l. : (514) 394-5000, poste 5197
Fax  : (514) 394-6888
700, rue de la Gaucheti?re ouest, 23e ?tage
Montr?al (Qu?bec)
H3B 4L1
Avis de confidentialit? : ce message peut contenir des renseignements 
confidentiels appartenant exclusivement au Groupe CGI inc. ou ? ses 
filiales. Si vous n'?tes pas le destinataire indiqu? ou pr?vu dans ce 
message (ou responsable de livrer ce message ? la personne indiqu?e ou 
pr?vue) ou si vous pensez que ce message vous a ?t? adress? par erreur, 
vous ne pouvez pas utiliser ou reproduire ce message, ni le livrer ? 
quelqu'un d'autre. Dans ce cas, vous devez le d?truire et vous ?tes pri? 
d'avertir l'exp?diteur en r?pondant au courriel.

From TLLITU001 at mail.uct.ac.za  Tue Oct  7 04:42:14 2003
From: TLLITU001 at mail.uct.ac.za (TLLITU001@mail.uct.ac.za)
Date: Thu Oct  9 20:18:19 2003
Subject: [Tutor] Placing other widgets on a frame
Message-ID: <3F827C66.CF12A95D@mail.uct.ac.za>

To whom it may concern

For the past two weeks i've been working on this project were I have to
design a sorting puzzle game. I'm finding it very difficult to connect
everything together. Yesterday I spend the whole day trying to place a
button on a frame, i couldn't do it ! I need some help on whole thing ,
CAN YOU PLEASE HELP ME!!

TUMI,UCT,SA

From surfinserpent at yahoo.com  Wed Oct  8 22:19:58 2003
From: surfinserpent at yahoo.com (joseph reaves)
Date: Thu Oct  9 20:18:22 2003
Subject: [Tutor] help
Message-ID: <20031009021958.50203.qmail@web80504.mail.yahoo.com>

how do i get started?



---------------------------------
Do you Yahoo!?
The New Yahoo! Shopping - with improved product search
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20031008/ced457db/attachment.html
From anna at aleax.it  Thu Oct  9 18:39:13 2003
From: anna at aleax.it (Anna Ravenscroft)
Date: Thu Oct  9 20:18:24 2003
Subject: [Tutor] skipping lines
In-Reply-To: <3F85DD02.4060109@snet.net>
References: <3F85DD02.4060109@snet.net>
Message-ID: <200310100039.13287.anna@aleax.it>

On Friday 10 October 2003 12:11 am, camartin@snet.net wrote:
> I have a piece of code that reads in a file line by line into lists. It
> then processes the file list by list and writes out the file processed
> line by processed line.  This works fine unless I have a blank line.  An
> example of the code (the actual code is more complicated but it works
> unless there are blank lines) is shown below,
>
> # file to open CSV files or plain delimited text. As one reads
> # each line convert the date to ordinal number, then write out
> # the line into a CSV file
> from datetime import date
> import string
> from string import *
>
>
> filename = raw_input("Enter the filename(make sure you enter the full
> path): ")
> f = open(filename,'r')
> g = open("c:\python23\outtest3.txt", 'w')
>
>
> for line in f.xreadlines():
>     words = line.rstrip().split()
>     S = words[9]
>     print >>g,S
>
>
> f.close()
> g.close()
>
>
> As I said above this writes what I expect but the error message I get is
> what one expects for a blank line namely there is no index S[9].
>
> Traceback (most recent call last):
>   File
> "C:\Python23\lib\site-packages\Pythonwin\pywin\framework\scriptutils.py",
> line 310, in RunScript
>     exec codeObject in __main__.__dict__
>   File "C:\Python23\Script2.py", line 16, in ?
>     S = words[9]
> IndexError: list index out of range
>

What about this:
(untested)

 for line in f.xreadlines():
     words = line.rstrip().split()
     try:
         S = words[9]:
         print >>g,S
    except IndexError:
        pass

The idea is to catch the exception so you can pass (ignore) it and go on to  
do the next line in your for loop. 

Anna
-- 
There is a type 3 error in which your mind goes totally blank whenever you try 
to remember which is which of type 1 and type 2.
                                                 -Richard Dawkins


From dyoo at hkn.eecs.berkeley.edu  Thu Oct  9 20:21:33 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Oct  9 20:21:43 2003
Subject: [Tutor] Limit on number of characters in a string?
In-Reply-To: <FEEJIIBACBNLOLKGBFLEKEFJCAAA.jeff@truedatapartners.com>
Message-ID: <Pine.LNX.4.44.0310091718340.16697-100000@hkn.eecs.berkeley.edu>



On Sun, 21 Sep 2003, Jeffery Chin wrote:

> Is there a limit on how many characters can be in a string?  I'm using
> pythonwin with python 2.3 and there seems to be a limit.
>
> I'm trying to concatenate lines from a file to make one continuous string
> and it won't grow beyond a certain length.
> I think it cuts it off around 3800 characters, but this was not consistent,
> but looking at the screen output, it certainly would not add more to the
> string.


Hi Jeffery,

There shouldn't be any hardcoded limit to the number of characters a
string can contain -- I've often had strings that were several megabytes
long.  *grin*


Your code snippet:


>     elif (record_check == ','):
>         interim_list.append(logline_path + entry + '.txt;')


is a little confusing, though: as far as I can tell, there's no string
concatentation going on!  Can you show us where you actually generate the
string?


Good luck to you.


From dyoo at hkn.eecs.berkeley.edu  Thu Oct  9 20:25:06 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Oct  9 20:25:24 2003
Subject: [Tutor] I need help with Python  [repeated message is dyoo's
	fault]
In-Reply-To: <001301c381c5$07328e40$d60d7bca@angel>
Message-ID: <Pine.LNX.4.44.0310091722410.16697-100000@hkn.eecs.berkeley.edu>



On Tue, 23 Sep 2003, Vickram wrote:

> Hello there,
>
> Python is really an excellent programming language, in terms of
> mathematical calculations. I have had a first hand experience of the
> power of python while using the Mayalib source code for python to
> calculate mayan dates.

[text cut]

Doh.  The repeated message here is my fault and not Vickram's.  As one of
the list admins, I just verified/rejected a batch of messages that had
been waiting in Python-tutor's queue, and didn't realize this one was
already answered a few days ago.


My apologies!


From jeff at ccvcorp.com  Thu Oct  9 20:29:24 2003
From: jeff at ccvcorp.com (Jeff Shannon)
Date: Thu Oct  9 20:25:55 2003
Subject: [Tutor] skipping lines
References: <3F85DD02.4060109@snet.net>
Message-ID: <3F85FD64.8090700@ccvcorp.com>

camartin@snet.net wrote:

>   for line in f.xreadlines():
>    words = line.rstrip().split()
>    S = words[9]
>    print >>g,S

> Traceback (most recent call last):
>  File 
> "C:\Python23\lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", 
> line 310, in RunScript
>    exec codeObject in __main__.__dict__
>  File "C:\Python23\Script2.py", line 16, in ?
>    S = words[9]
> IndexError: list index out of range

You could always explicity catch the IndexError --

for line in f.xreadlines():
     words = line.rstrip().split()
     try:
         S = words[9]
         print >>g, S
     except IndexError:
         pass

This should have the effect of ignoring empty lines.  Another 
possibility is to test line itself, as you said you tried.

for line in f.xreadlines():
     if line.strip():
         words = line.rstrip().split()
         # ...

The key here is that Python considers an empty string ("") to be 
equivalent to 'false'.  We can't just test line directly, because it 
will contain at least a newline, and possibly other whitespace. 
line.strip() will get rid of all of that, leaving an empty string for 
a blank line.

This could perhaps be rearranged to be a tiny bit more efficient --

for line in f.xreadlines():
     line = line.strip()
     if line:
         words = line.split()
         # ...

The difference here is that you're only strip()ing once, but this will 
also strip off leading whitespace.  This could be an issue if leading 
whitespace is significant (as it is in, say, Python sourcecode files). 
  For the purpose you seem to be describing, though, it should be fine.

Jeff Shannon
Technician/Programmer
Credit International


From dyoo at hkn.eecs.berkeley.edu  Thu Oct  9 20:29:05 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Oct  9 20:29:13 2003
Subject: [Tutor] barcode creation
In-Reply-To: <LAW12-OE270WDg88nN600002cb0@hotmail.com>
Message-ID: <Pine.LNX.4.44.0310091725530.16697-100000@hkn.eecs.berkeley.edu>



On Mon, 6 Oct 2003, cordillia contessa wrote:

> I have to create barcode but have no slight idea of what is needed and
> how to create it. Help... Anyone...

Hi Cordillia,



You can find out about barcode generation from the GNU Barcode project:

    http://www.gnu.org/software/barcode/barcode.html


According to the documentation in GNU Barcode, there is a Python program
to generate ISBN bar codes:

    http://www.cgpp.com/bookland/


The link to bookland has a few more links that may be helpful for you.
Good luck!


From dyoo at hkn.eecs.berkeley.edu  Thu Oct  9 20:31:55 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Oct  9 20:32:06 2003
Subject: [Tutor] Random numbers
In-Reply-To: <3F8000EC.5C49E947@mail.uct.ac.za>
Message-ID: <Pine.LNX.4.44.0310091729080.16697-100000@hkn.eecs.berkeley.edu>



On Sun, 5 Oct 2003, UCT Student - DLLBIA001 wrote:

> i was just wandring if you could not help me to generate 25 random
> numbers in the range of 0 to 24 without any number repeating.

Hello,


Take a close look at:

    http://www.python.org/doc/lib/module-random.html

In particular, the shuffle() function should be useful for you.


If you have more questions, please feel free to ask.  Because you are
working on a homework assignment, we are somewhat more restricted in
answering fully, but we'll try to direct you toward good resources.


Good luck to you.



From jeff at ccvcorp.com  Thu Oct  9 20:41:07 2003
From: jeff at ccvcorp.com (Jeff Shannon)
Date: Thu Oct  9 20:37:38 2003
Subject: [Tutor] Limit on number of characters in a string?
References: <FEEJIIBACBNLOLKGBFLEKEFJCAAA.jeff@truedatapartners.com>
Message-ID: <3F860023.2080400@ccvcorp.com>

Jeffery Chin wrote:
> Is there a limit on how many characters can be in a string?  I'm using
> pythonwin with python 2.3 and there seems to be a limit.
> 
> I'm trying to concatenate lines from a file to make one continuous string
> and it won't grow beyond a certain length.
> I think it cuts it off around 3800 characters, but this was not consistent,
> but looking at the screen output, it certainly would not add more to the
> string.

I've used Python to manipulate a file that uses 4K (4096 character) 
long lines, so that's not your problem.

However, *displaying* such long lines can frequently be a significant 
issue.  PythonWin starts to behave rather oddly when dealing with 
lines that are several kB long.  Instead of trying to display the 
entire string, try just displaying its len() before and after the 
concatenation.  This should demonstrate that the string is indeed growing.

Jeff Shannon
Technician/Programmer
Credit International


From jeff at ccvcorp.com  Thu Oct  9 20:50:29 2003
From: jeff at ccvcorp.com (Jeff Shannon)
Date: Thu Oct  9 20:47:42 2003
Subject: [Tutor] I need help with Python
References: <001301c381c5$07328e40$d60d7bca@angel>
Message-ID: <3F860255.2070802@ccvcorp.com>

Vickram wrote:

> I need to make calculations using very large numbers, unfortunately, i 
> am getting a "ZeroDivisionError: float division" error.

This would be easier to determine if you had included the rest of the 
traceback, which would tell us exactly *where* the error is.  But 
let's see what we can do.

The error means that you're dividing by zero.  Mathematics tells us 
that this yields an undefined result, but computers can't handle 
undefined numbers, so it's not allowed and is considered an error. 
The trick is to find out where in your program you might be dividing 
by zero.

> import cmath
> 
> a = 186282.397
> b = 1609.344
> c = 365.2421987817
> d = 99.9999999999999999995
> e = (d*a)/100
> beta = ((e*b)**2) / ((a*b)**2)
> gamma = 1/math.sqrt(1-beta)

All of this should be good.  You've got a set of floating point 
numbers, none of which approximate zero all that closely.

> ty = 100000
> td = ty*c
> print
> print "speed of light =",a,"mps"
> print "1 mile =",b,"metres"
> print "1 year =",c,"days"
> print
> print "% of c =",d,"%"
> print "gamma =",gamma
> print
> print "normal time = ",ty,"years"
> print " ",td,"days"
> print
> print "time dilation =",ty/round(gamma),"yrs"

Here's where I think your problem is.  You're rounding gamma to the 
nearest integer, and then dividing by it.  You previously defined 
gamma as a fraction -- it's somewhere between 0 and 1.  If gamma 
happens to be closer to 0, then round(gamma) will be equal to 0, and 
there you've got an illegal division by zero.

I'm not sure why you'd want to round off gamma for this calculation, 
anyhow.  Perhaps you meant to round off the results of ty/gamma, instead?

Jeff Shannon
Technician/Programmer
Credit International


From amk at amk.ca  Thu Oct  9 20:48:40 2003
From: amk at amk.ca (amk@amk.ca)
Date: Thu Oct  9 20:48:46 2003
Subject: [Tutor] re-directing print statements in exec
In-Reply-To: <000e01c38267$fab53d90$6501a8c0@bigduck>
References: <000e01c38267$fab53d90$6501a8c0@bigduck>
Message-ID: <20031010004840.GA2967@rogue.amk.ca>

On Tue, Sep 23, 2003 at 11:49:14PM -0700, Toby Donaldson wrote:
> I am wondering if there is any easy way to make a print statement in an
> exec statement get sent to a string instead of the console. For
> instance,

Use the StringIO/cStringIO modules.  (cStringIO is written in C,
theoretically making it faster, but unless you're writing lots of data it
probably won't make a significant difference.

Example:

from StringIO import StringIO
output = StringIO()
print >>output, 3.14*r**2
print >>output, 'blah blah blah'
str_value = output.getvalue()

--amk

From jeff at ccvcorp.com  Thu Oct  9 21:00:31 2003
From: jeff at ccvcorp.com (Jeff Shannon)
Date: Thu Oct  9 20:57:02 2003
Subject: [Tutor] re-directing print statements in exec
References: <000e01c38267$fab53d90$6501a8c0@bigduck>
Message-ID: <3F8604AF.2080308@ccvcorp.com>

Toby Donaldson wrote:
> Hi all,
> 
> I am wondering if there is any easy way to make a print statement in an 
> exec statement get sent to a string instead of the console. For instance,
> 
>>>>  prog = """
> r = 5
> print 3.14 * r ** 2
> """
>>>>  exec prog
> 78.5
> 
> The result gets printed to the console. But instead, I'd like it to be 
> in a string.
> 
> Any suggestions?

First off, I'd suggest just using a function instead of exec.  ;)

def prog():
     r = 5
     return 3.14 * r**2

result = prog()

Of course, it'd probably be better to pass r in as a parameter, and to 
rename the function so that it's meaningful...

def circle_area(r):
     return 3.14 * (r**2)

result = circle_area(5)

There are *very* few situations in which exec is truly the most 
desirable tool, and many situations in which it creates programs that 
are actively dangerous.  The use of exec and its cousin eval() should 
always be considered to be deep black magic -- it is not suitable (nor 
intended for) everyday use.  Unless you're writing an interactive 
shell replacement or a code debugger or some such, I *strongly* 
recommend against using exec.

Jeff Shannon
Technician/Programmer
Credit International



From SWidney at ci.las-vegas.nv.us  Thu Oct  9 21:03:05 2003
From: SWidney at ci.las-vegas.nv.us (Scott Widney)
Date: Thu Oct  9 21:05:09 2003
Subject: [Tutor] I need help with Python
Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC8861@sovereign.ci.las-vegas.nv.us>

> I need to make calculations using very large numbers, 
> unfortunately, i am getting a "ZeroDivisionError: float 
> division" error.
> 
> Can you please help me out?
> 
> What follows is my program. Its simple and brief, yet it is 
> actually calculating one of the best proven theories in 
> science - special relativity.
> 
> 
> import cmath

Should be 'import math' -- you don't use any complex math in the code that
follows, but you do request the math.sqrt() function.

> 
> a = 186282.397
> b = 1609.344
> c = 365.2421987817
> d = 99.9999999999999999995

This is where you are getting caught. If you look at the value in 'd' here,
you'll see that it is stored as 100.0 -- your precision is lost.

> e = (d*a)/100

So here 'e' ends up being the same value of 'a',

> beta = ((e*b)**2) / ((a*b)**2)

and 'beta' ends up being the equivalent of 186282.397 divided by 186282.397,
namely 1.0

> gamma = 1/math.sqrt(1-beta)

So the calculation for 'gamma' ends up being: 1 / math.sqrt( 1 - 1.0). This
is where you are getting the exception. Do you see the problem?


Best wishes!
Scott

From missive at hotmail.com  Thu Oct  9 21:34:48 2003
From: missive at hotmail.com (Lee Harr)
Date: Thu Oct  9 21:34:55 2003
Subject: [Tutor] Re: Can you clarify these terms
Message-ID: <BAY2-F170BdyFj9ZYht00000e89@hotmail.com>

>I have a number of questions.
>

Please do not send HTML to the list. Send only plain text.

>How do you call from the command prompt (in Python or windows)
>a script file you've successfully run compiled from the editor?
>

Python is an interpreted language. As such we do not usually
talk about compiling scripts or programs. That said, to run from
the DOS prompt, you would do something like:  python myscript.py
or from the python prompt, you would:  import myscript
although that is not usually the way you would run something...


That said, it really sounds to me like you have just typed or pasted
your homework assignment in to your mail program. That is not what
this list is about.  I think you will have better luck if you:

1. do not post html to the list
2. post only one question at a time
3. include some code you have written to illustrate your question
4, search google first, especially for things that are not python-specific

_________________________________________________________________
MSN 8 helps eliminate e-mail viruses. Get 2 months FREE*. 
http://join.msn.com/?page=features/virus


From carroll at tjc.com  Thu Oct  9 23:40:55 2003
From: carroll at tjc.com (Terry Carroll)
Date: Thu Oct  9 23:41:06 2003
Subject: [Tutor] Random numbers
In-Reply-To: <3F8000EC.5C49E947@mail.uct.ac.za>
Message-ID: <Pine.LNX.4.44.0310092034430.11638-100000@violet.rahul.net>

On Sun, 5 Oct 2003, UCT Student - DLLBIA001 wrote:

> i was just wandring if you could not help me to generate 25 random
> numbers in the range of 0 to 24 without any number repeating.
> if i were then to put this numbers onto a grid with 25 squares how would
> i go about it. the grid and squares have already been made but how to
> place the numbers i am uncertain of.

For only 25 numbers, my approach would be:

 1. create a list of numbers from 0 to 24.
 2. set up your grid with 25 spaces.
 3. get a random number between 0 and the length of the list minus 1 (24 
    when you start);
 4. pull that entry out of the list with pop() and put it into the first 
    open entry in the grid.  pop() will remove that entry from the list, 
    so the number of entries will be 24 after the first pass, 23 after the 
    second, etc.
 5. Repeat 3-4 until the list is empty.

Things to read up on:

 pop()
 random.uniform() (to generate a random number in a particular range)
 len() (to get the length of the list)


-- 
Terry Carroll
Santa Clara, CA
carroll@tjc.com 


From alan.gauld at blueyonder.co.uk  Fri Oct 10 01:12:01 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Fri Oct 10 01:13:47 2003
Subject: [Tutor] skipping lines
References: <3F85DD02.4060109@snet.net>
Message-ID: <00ac01c38eed$09dede20$6401a8c0@xp>

> for line in f.xreadlines():
>     words = line.rstrip().split()
 
      if len(words) >= 10:
          S = words[9]
          print >>g,S

Should fix it.

Alan g

From ronan at melim.com.br  Fri Oct 10 07:17:54 2003
From: ronan at melim.com.br (Ronan Lucio)
Date: Fri Oct 10 07:17:18 2003
Subject: [Tutor] Web development
In-Reply-To: <668593.1065721462012.JavaMail.erikprice@mac.com>
References: <668593.1065721462012.JavaMail.erikprice@mac.com>
Message-ID: <200310100817.54215.ronan@melim.com.br>

Erick,

> >Does someone develop web applications in Python?
>
> Sure, an interesting project for web app development is Webware.
> <http://webware.sourceforge.net/>

Webware realy seems to be a great option but, unfortunatly, I didn't
get to install it in a FreeBSD-4.8 box... :-/
It gave me some errors that couldn't got to solve.

> You should read more about how cookies work, you can limit the lifetime of
> a cookie to only last as long as the current session (until the user quits
> the browser instance):
> <http://wp.netscape.com/newsref/std/cookie_spec.html>

Very good!!!

> Hopefully the above will help answer some questions about cookies in web
> application development.

Great! Thank you very much.

Ronan

From bwalling at coastdental.com  Fri Oct 10 07:37:48 2003
From: bwalling at coastdental.com (Benjamin Walling)
Date: Fri Oct 10 07:40:23 2003
Subject: [Tutor] barcode creation
Message-ID: <61119D047A3FE84E83EF2FFDA9A156A4E58FB1@cstntexch01.coastdental.lan>

If you are on a Windows system, it is as easy as installing a new font.
Many barcodes, such as 3 of 9, are available as fonts.  This may be true
on other systems (Linux, etc), although I have not used barcoding on
those systems.

  _____  

From: cordillia contessa [mailto:gulasachet@hotmail.com] 
Sent: Sunday, October 05, 2003 12:27 PM
To: tutor@python.org
Subject: [Tutor] barcode creation


I have to create barcode but have no slight idea of what is needed and
how to create it. Help... Anyone...
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20031010/6cce7394/attachment.html
From aschmidt at fredericksburg.com  Fri Oct 10 08:10:09 2003
From: aschmidt at fredericksburg.com (Allen)
Date: Fri Oct 10 08:10:46 2003
Subject: [Tutor] Deciding on using Jython
In-Reply-To: <00ac01c38eed$09dede20$6401a8c0@xp>
References: <3F85DD02.4060109@snet.net> <00ac01c38eed$09dede20$6401a8c0@xp>
Message-ID: <3F86A1A1.2080001@fredericksburg.com>

So what are the feelings on using Jython?

I asked this list a while back about how to use DigestAuthentication to 
gain access to a URL from a company that changed how I accessed their 
data. I am not familiar with Python yet to dig deep enough to make it work.

But, the Java classes and API are available on SourceForge. I would like 
to be able to build out my own tools to get at this data and would still 
like to do it in Python. Wondering if anyone here has used Jython and 
what they thought about it before I did more investigating.

Thanks!!

Allen


From glingl at aon.at  Fri Oct 10 10:14:18 2003
From: glingl at aon.at (Gregor Lingl)
Date: Fri Oct 10 10:16:19 2003
Subject: [Tutor] cross sum toying
In-Reply-To: <000001c38e6a$3c2a7980$e841fea9@oemcomputer>
References: <000001c38e6a$3c2a7980$e841fea9@oemcomputer>
Message-ID: <3F86BEBA.4000002@aon.at>



Raymond Hettinger schrieb:

>Here is one more version to play with:
>
>  
>
>>>>from itertools import imap
>>>>def cross_sum(n, codezero=ord('0')):
>>>>        
>>>>
>	s = str(n)
>	return sum(imap(ord, s)) - len(s) * codezero
>  
>
Nice idea! I played with it, as you suggested and, interestingly, found
out that it is exactly as fast as:

def cross_sum7(n):
    s=str(n)
    return sum(map(ord, s)) - ord("0")*len(s)

So why use itertools in this case?

Regards, Gregor

>  
>


From op73418 at mail.telepac.pt  Fri Oct 10 10:25:50 2003
From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=)
Date: Fri Oct 10 10:24:27 2003
Subject: [Tutor] Private and Public variables
In-Reply-To: <001e01c38dd7$1d5153a0$6401a8c0@xp>
References: <Sea1-F39skKwaenTosf0000dcaa@hotmail.com>
	<ofs2ovsodni9ph8esnech8g63up344404e@4ax.com>
	<001e01c38dd7$1d5153a0$6401a8c0@xp>
Message-ID: <a5fdovkbflv9m1o30rr4d207dubaltl805@4ax.com>

On Wed, 8 Oct 2003 21:02:34 +0100, you wrote:

>> they are still with me. I think one of the reason's why is because I
>> tend to favor (following the gang of 4) composition to inheritance.
>
>What does that have to do with data hiding (the correct term
>for private data)?

Good question :-)

I guess this is one of those situations where by conflating the issues
in your head things just get more complicated and muddled.

[text snipped]

>> So, what do you guys think?
>
>I think your design ideas are correct, the need for data hiding
>and the implied distrust of your fellow programmers is perhaps
>more questionable.

The implied distrust is not towards my fellow programmers, is more
towards me...

But I guess I do need to relax a little more...

>
>But if you design classes to expose a behavioural interface
>then the ability or lack of to directly access data will not
>be of any concern to your users.

Exactly, that's what I try to do.

I believe the "we're all consenting adults" philosophy is the Right
Philosophy. The name-mangling feature for attributes of the form
__my_attribute is also very good IMHO, since nothing is really hidden
and a client can always work around bugs and/or missing features. At
the same time it gives a clear signal to the client that if he mucks
with this attribute he does so at his own risk.

With my best regards,
G. Rodrigues

From python at rcn.com  Fri Oct 10 13:15:06 2003
From: python at rcn.com (Raymond Hettinger)
Date: Fri Oct 10 13:15:45 2003
Subject: [Tutor] cross sum toying
In-Reply-To: <3F86BEBA.4000002@aon.at>
Message-ID: <000f01c38f52$0d632f00$e841fea9@oemcomputer>

> >>>>from itertools import imap
> >>>>def cross_sum(n, codezero=ord('0')):
> >>>>
> >>>>
> >	s = str(n)
> >	return sum(imap(ord, s)) - len(s) * codezero
> >
> >
> Nice idea! I played with it, as you suggested and, interestingly,
found
> out that it is exactly as fast as:
> 
> def cross_sum7(n):
>     s=str(n)
>     return sum(map(ord, s)) - ord("0")*len(s)
> 
> So why use itertools in this case?

I always use an iterator version unless a full listing is essential.
Likewise, I usually prefer xrange() to range().  sum() and imap() work
especially well together -- the memory consumption is constant rather
than linear as with map().  For small inputs, the performance difference
is negligible.  For bigger inputs, building a long list and throwing it
away after one use is not only wasteful of memory, but it kills cache
performance once the memory requirements grow beyond the cache size.
IOW, the habit of using iterators results in apps that scale-up nicely.

Aside from memory consumption and cache utilization, map() is also at a
disadvantage when its arguments are do not have a __len__() method.  In
the cross_sum() example, the string "s" dutifully reports its length so
that map can pre-allocate storage.  However, in other apps, the inputs
can be general iterables (generators for example) which only offer
__iter__() but not __len__().  In that case, map's performance drops-off
each time it has to do a memory reallocation as the sequence length
grows.

One other thought: pre-computing ord("0") into a local variable ought to
produce a measurable time savings for repeated calls to cross_sum().  If
you want to be an overachiever, change the function definition to:
  
 def cross_sum(n, sum=sum, imap=itertools.imap, codezero=ord("0"),
                  len=len, str=str):
     s = str(n)
     return sum(imap(ord, s)) - len(s) * codezero     


Bonus question:  Explain whether imap() would be preferred to map() in
the following definition:

  def dotproduct(v1, v2):
     return sum(imap(operator.mul, v1, v2))

For grins, time it against the more specialized function:

  def integer_dot_product(v1, v2, sum=sum, imap=imap, mul=int.__mul__):
     return sum(imap(mul, v1, v2))

Try repeated calls with short vector tuples.  Time it again with longer
iterator inputs like:  integer_dot_product(xrange(1,1000000,2),
xrange(0,1000000,2)).


Raymond Hettinger


From abli at freemail.hu  Fri Oct 10 15:09:43 2003
From: abli at freemail.hu (Abel Daniel)
Date: Fri Oct 10 15:09:24 2003
Subject: [Tutor] Re: Random numbers
In-Reply-To: <3F8000EC.5C49E947@mail.uct.ac.za> (UCT Student's message of
	"Sun, 05 Oct 2003 13:30:52 +0200")
References: <3F8000EC.5C49E947@mail.uct.ac.za>
Message-ID: <E1A82e1-0000DQ-00@hooloovoo>

UCT Student - DLLBIA001 <DLLBIA001@mail.uct.ac.za> writes:

> i was just wandring if you could not help me to generate 25 random
> numbers in the range of 0 to 24 without any number repeating.

Just a note: in this case you aren't 'generating random numbers' but
'shuffling numbers'.

Abel Daniel

From ATrautman at perryjudds.com  Fri Oct 10 15:21:48 2003
From: ATrautman at perryjudds.com (Alan Trautman)
Date: Fri Oct 10 15:25:12 2003
Subject: [Tutor] barcode creation
Message-ID: <06738462136C054B8F8872D69DA140DB01C08AA3@corp-exch-1.pjinet.com>

Are you trying to print or display a barcode. Some (usually better) printers
have a barcode font hard coded or programmable. This is easiest for creating
labels. 
 
Alan

-----Original Message-----
From: Benjamin Walling [mailto:bwalling@coastdental.com]
Sent: Friday, October 10, 2003 6:38 AM
To: tutor@python.org
Subject: RE: [Tutor] barcode creation


If you are on a Windows system, it is as easy as installing a new font.
Many barcodes, such as 3 of 9, are available as fonts.  This may be true on
other systems (Linux, etc), although I have not used barcoding on those
systems.

  _____  

From: cordillia contessa [mailto:gulasachet@hotmail.com] 
Sent: Sunday, October 05, 2003 12:27 PM
To: tutor@python.org
Subject: [Tutor] barcode creation


I have to create barcode but have no slight idea of what is needed and how
to create it. Help... Anyone...

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20031010/c67c5cff/attachment.html
From anna at aleax.it  Fri Oct 10 15:27:27 2003
From: anna at aleax.it (Anna Ravenscroft)
Date: Fri Oct 10 15:27:33 2003
Subject: [Tutor] Re: Random numbers
In-Reply-To: <E1A82e1-0000DQ-00@hooloovoo>
References: <3F8000EC.5C49E947@mail.uct.ac.za> <E1A82e1-0000DQ-00@hooloovoo>
Message-ID: <200310102127.27279.anna@aleax.it>

On Friday 10 October 2003 09:09 pm, Abel Daniel wrote:
> UCT Student - DLLBIA001 <DLLBIA001@mail.uct.ac.za> writes:
> > i was just wandring if you could not help me to generate 25 random
> > numbers in the range of 0 to 24 without any number repeating.
>
> Just a note: in this case you aren't 'generating random numbers' but
> 'shuffling numbers'.
>
> Abel Daniel
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

Okay - OP might want to look into the new "sample" function in module random.

>>> import random
>>> random.sample(range(25), 25)
[20, 8, 14, 4, 13, 10, 1, 21, 19, 7, 6, 23, 22, 16, 5, 17, 15, 2, 18, 12, 24, 
3, 0, 9, 11]
>>>

If you only want, say, 10 of the values from your range, you can do this:
>>> random.sample(range(25), 10)
[16, 15, 21, 24, 14, 17, 0, 7, 9, 11]
>>>

If you don't care about repetition in your samples, then just use 
randrange...:
To get one random number at a time:
>>> random.randrange(25)
11

Or, to get a list of them, use a list comprehension:

>>> [random.randrange(25) for i in range(10)]
[2, 21, 8, 3, 4, 23, 1, 21, 13, 11]
>>> [random.randrange(25) for i in range(10)]
[8, 6, 1, 21, 9, 24, 14, 5, 12, 3]
>>> [random.randrange(25) for i in range(10)]
[22, 19, 20, 20, 2, 13, 7, 3, 11, 7]
>>>

HTH
Anna Ravenscroft
-- 
There is a type 3 error in which your mind goes totally blank whenever you try 
to remember which is which of type 1 and type 2.
                                                 -Richard Dawkins


From anna at aleax.it  Fri Oct 10 15:32:59 2003
From: anna at aleax.it (Anna Ravenscroft)
Date: Fri Oct 10 15:33:05 2003
Subject: [Tutor] Re: Random numbers
In-Reply-To: <200310102127.27279.anna@aleax.it>
References: <3F8000EC.5C49E947@mail.uct.ac.za> <E1A82e1-0000DQ-00@hooloovoo>
	<200310102127.27279.anna@aleax.it>
Message-ID: <200310102132.59482.anna@aleax.it>

On Friday 10 October 2003 09:27 pm, Anna Ravenscroft wrote:

Oops... got carried away, I guess. Didn't realize this was somebody's homework 
assignment... He'll still need to figure out how to get them into the 
squares... 

I'll read more carefully before answering next time... Sorry.

Anna
-- 
There is a type 3 error in which your mind goes totally blank whenever you try 
to remember which is which of type 1 and type 2.
                                                 -Richard Dawkins


From erikprice at mac.com  Fri Oct 10 16:39:46 2003
From: erikprice at mac.com (Erik Price)
Date: Fri Oct 10 16:39:51 2003
Subject: [Tutor] __getitem__() and for loops
Message-ID: <1620007.1065818386317.JavaMail.erikprice@mac.com>

Quick question:

Is a for loop actually calling __getitem__() behind the scenes, and passing in the current index of the range of the for loop?


Thanks,

Erik

From rafael.sousa at netcabo.pt  Fri Oct 10 16:46:13 2003
From: rafael.sousa at netcabo.pt (Rafael Sousa)
Date: Fri Oct 10 16:49:42 2003
Subject: [Tutor] How can I convert a bin string to a hex string?
References: <Pine.LNX.4.44.0310091100270.20399-100000@hkn.eecs.berkeley.edu>
Message-ID: <001b01c38f6f$8be57b40$6800a8c0@mobile>

Thanks! That's exactly what I need!

I wonder: Is there anything that Python doesn't have a module for?


----- Original Message ----- 
From: "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu>
To: "rafael.sousa" <rafael.sousa@netcabo.pt>
Cc: <tutor@python.org>
Sent: Thursday, October 09, 2003 7:02 PM
Subject: Re: [Tutor] How can I convert a bin string to a hex string?


>
>
> On Thu, 9 Oct 2003, rafael.sousa wrote:
>
> > Such as the binary contents of a jpeg image?
> >  I'm writing the code to dynamically create a RTF (Rich Text Format)
> > document. In order to insert a picture, it's recommended in the
> > specification that its contents are written in hex.
> >  I read the binary content to a regular python string, but then I would
> > need to convert it to another string, this time in hex (which would
> > naturally have the double of the length of the original bin string).
>
>
> Hi Rafael,
>
>
> Ah, then the 'binascii' module should be suitable for this:
>
>     http://www.python.org/doc/lib/module-binascii.html
>
> The binascii.hexlify() function should be exactly what you're looking for.
>
>
>
> Good luck!
>
>



From op73418 at mail.telepac.pt  Fri Oct 10 16:52:12 2003
From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=)
Date: Fri Oct 10 16:50:45 2003
Subject: [Tutor] __getitem__() and for loops
In-Reply-To: <1620007.1065818386317.JavaMail.erikprice@mac.com>
References: <1620007.1065818386317.JavaMail.erikprice@mac.com>
Message-ID: <rr6eovsabnu7ptse5lvroq4jquahc309d8@4ax.com>

On Fri, 10 Oct 2003 16:39:46 -0400, you wrote:

>Quick question:
>
>Is a for loop actually calling __getitem__() behind the scenes, and passing in the current index of the range of the for loop?
>

Let us test:

>>> class Test(object):
... 	def __init__(self, n):
... 		self.n = int(n)
... 	def __getitem__(self, i):
... 		if 0 <= i < self.n:
... 			return i
... 		else:
... 			raise IndexError
... 
>>> t = Test(4)
>>> for i in t:
... 	print i
... 
0
1
2
3

So it seems...

Python looks first for __iter__ then tries __getitem__ -- also for
backwards compatibility. Before the iterator protocol (< 2.2) coding a
__getitem__ was the standard way to make classes cooperate with
for-loops.

With my best regards,
G. Rodrigues

From project5 at redrival.net  Fri Oct 10 18:41:58 2003
From: project5 at redrival.net (Andrei)
Date: Fri Oct 10 18:44:05 2003
Subject: [Tutor] Re: help
In-Reply-To: <20031009021958.50203.qmail@web80504.mail.yahoo.com>
References: <20031009021958.50203.qmail@web80504.mail.yahoo.com>
Message-ID: <bm7cng$ii8$1@sea.gmane.org>



joseph reaves wrote:
> how do i get started?

Beginner's guide to Python:
http://python.org/topics/learn/

If you have more specific questions, you can ask them here.

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur 
yvfg, fb gurer'f ab arrq gb PP.



From dyoo at hkn.eecs.berkeley.edu  Sat Oct 11 03:51:00 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat Oct 11 03:51:08 2003
Subject: [Tutor] __getitem__() and for loops
In-Reply-To: <rr6eovsabnu7ptse5lvroq4jquahc309d8@4ax.com>
Message-ID: <Pine.LNX.4.44.0310110024380.7302-100000@hkn.eecs.berkeley.edu>


> >Is a for loop actually calling __getitem__() behind the scenes, and
> >passing in the current index of the range of the for loop?
>
> Python looks first for __iter__ then tries __getitem__ -- also for
> backwards compatibility. Before the iterator protocol (< 2.2) coding a
> __getitem__ was the standard way to make classes cooperate with
> for-loops.

Hello!

Hmmm... Ideally, we'd be able to find out the specific details about the
'for' statement from the Language Reference:

    http://www.python.org/doc/current/ref/for.html

Although the text does mention "iterable" objects, for the most part, the
description emphasizes the idea that the for loop uses the 'sequence'
interface (__getitem__()) to reach every element in the 'expression list'.
So this part of the documentation may need to be freshened up a bit to
better reflect the current reality.  *grin*


Let's dig in a little bit more.  The documentation from the Iterator PEP:

    http://www.python.org/peps/pep-0234.html

seems to have a more up-to-date description on how 'for' loops are working
now:

"""For backwards compatibility, the PyObject_GetIter() function
   implements fallback semantics when its argument is a sequence that
   does not implement a tp_iter function: a lightweight sequence
   iterator object is constructed in that case which iterates over
   the items of the sequence in the natural order."""

There are some low-level C details in that paragraph, but it's not too
bad.  In general, for loops uses iter() now.  But if the thing we're
iterating across doesn't natively support iteration, the system generates
a iterable wrapper on-the-fly around that sequence.  And that wrapper is
responsible for doing the right __getitem__()'s to make the iteration
work.


So the subtle thing to see is that it's not 'for' loops themselves that
call __getitem__() anymore.  Instead, it's the result of that wrapper that
iter()  is generating on-the-fly:

###
>>> class Wrapper:
...     def __init__(self, obj):
...         self.obj = obj
...     def __getattr__(self, attr):
...         print "Debug: attribute", attr, "requested"
...         return getattr(self.obj, attr)
...
>>> class Foo: pass
...
>>> f = Wrapper(Foo())
>>> iter(f)
Debug: attribute __iter__ requested
Debug: attribute __getitem__ requested
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: iteration over non-sequence
###



Hope this helps!


From dyoo at hkn.eecs.berkeley.edu  Sat Oct 11 04:12:06 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat Oct 11 04:12:19 2003
Subject: [Tutor] How can I convert a bin string to a hex string? [Python
	Packages Index]
In-Reply-To: <001b01c38f6f$8be57b40$6800a8c0@mobile>
Message-ID: <Pine.LNX.4.44.0310110102410.7302-100000@hkn.eecs.berkeley.edu>



On Fri, 10 Oct 2003, Rafael Sousa wrote:

> Thanks! That's exactly what I need!
>
> I wonder: Is there anything that Python doesn't have a module for?

Hi Rafael,

If there's some functionality that's not in the Standard Library, we might
be able to find it in some third-party module.  Recently, the PyPI project
has kickstarted into action, collecting information on those third-party
modules!

    http://www.python.org/pypi

It's very nice and shiny.  (But why is Python 2.3.2:

    http://www.python.org/pypi?:action=display&name=Python&version=2.3.2

classified under both "Development Status :: 3 - Alpha" and "Development
Status :: 6 - Mature"?  That's somewhat disconcerting.  *grin*)


There's also the venerable Vaults of Parnassus:

    http://www.vex.net/parnassus/


Good luck to you!


From DataSoft2004 at netscape.net  Sat Oct 11 13:37:59 2003
From: DataSoft2004 at netscape.net (Data)
Date: Sat Oct 11 13:38:21 2003
Subject: [Tutor] Python
Message-ID: <3F883FF7.1060501@netscape.net>

I would like to learn this language but i am a complete beginner.
Can someone help me with this language?
Data.


From david at graniteweb.com  Sat Oct 11 15:43:44 2003
From: david at graniteweb.com (David Rock)
Date: Sat Oct 11 15:43:49 2003
Subject: [Tutor] Python
In-Reply-To: <3F883FF7.1060501@netscape.net>
References: <3F883FF7.1060501@netscape.net>
Message-ID: <20031011194344.GA749@wdfs.graniteweb.com>

* Data <DataSoft2004@netscape.net> [2003-10-11 19:37]:
> I would like to learn this language but i am a complete beginner.
> Can someone help me with this language?
> Data.

The best place to start is:
http://www.python.org/topics/learn/

-- 
David Rock
david@graniteweb.com
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20031011/a785366b/attachment.bin
From kp8 at mac.com  Sun Oct 12 03:20:15 2003
From: kp8 at mac.com (kevin parks)
Date: Sun Oct 12 03:20:28 2003
Subject: [Tutor] putting a short list of integers into a (specific) compact
	form
In-Reply-To: <E1A8ErP-0000Un-CV@mail.python.org>
Message-ID: <8683ADE5-FC84-11D7-BB7D-003065555ABC@mac.com>

Hi everyone,

I've got a question. It is a bit of a brain teaser for me and i am 
trying to figure out nice and pythonic way of going about things, but i 
just can't get my head round the problem so after staring and the 
screen for an eternity, i though that i would give a shout out and see 
if i can understand what comes back in response and hopefully i will 
have an 'a-ha' type moment. It is quite a complex process for my small 
brain so half the battle is understanding the steps and the other is 
figuring out how to code it up. As a way to help me get the problem 
straight in my pea-sized brain, i though that i would write out the 
process and now, since i am stuck, if anyone is bored, i would love 
some help, since this is actually being done for a purpose (in order to 
get some other work done).

here's what i'd like to do (it is quite complex, but it have tried to 
present the recipe as
clearly as possible):

Take a short list of small integers and put it into a very specific
compact form like so:

1. Initially, all duplicate elements should be eliminated and the 
elements should
    be written so that they are ascending in order (all integers are 
mapped mod 12).

2. Since there will be as many ways to order them as there are elements 
in
    the list, we want to choose the ordering that has the
    smallest interval from lowest element to highest one.

3. If there is still a tie under rule #2 we want to pick the list that 
is
   most packed to the left (by finding the intervals between the first 
element
   and the second to last element and comparing the intervals of each 
list in
   the tie, if there is still a tie, compare the intervals between first 
element
   in the lists and the third to last, etc.)

4. If this still results in a tie for each element, for example in the 
case of:
    [10,1,6] , [1,6,10] , and [6,10,1] we choose [1,6,10], since
    it's first element is 1.

(finally, and optionally, i'll likely need to transpose the answer so 
that
it starts on 0)

So in a set with the following five possible orderings (here already 
sorted low to high
and proceeding systematically (again %12)):

[0,4,8,9,11]
[4,8,9,11,0]
[8,9,11,0,4]
[9,11,0,4,8]
[11,0,4,8,9]

So the interval between the first element and the last is

[0,4,8,9,11] = 0-11 = 11
[4,8,9,11,0] = 0-4 = 12-4 = 8
[8,9,11,0,4] = 4-8 = 16 - 8 = 8
[9,11,0,4,8] = 9-8 = 20-9 = 11
[11,0,4,8,9] = 9-11 = 21-11 = 10

Here end up with a tie between the second and third orderings above. So 
we go to
rule #3: We compare the intervals btween the first and next to last 
elements:

second ordering: 11-4 = 7
third ordering: 0-8 = 4

Since 4 is smaller than 7 we conclude the third ordering [8,9,11,0,4] 
is more packed to the left and
what we want and there is no need for rule 4 in this case.

I hope that i have stated the question clearly. I would appreciate any 
help folks could give on this. Frankly it is beyond
what i can do at this point, but i would like to see how others 
approach this in the hopes that my code will work and that
i might learn something.

Best,

kevin


--^----------------------------------------

   kp8 @ mac . com


From kp8 at mac.com  Sun Oct 12 05:46:28 2003
From: kp8 at mac.com (kevin parks)
Date: Sun Oct 12 05:46:41 2003
Subject: [Tutor] Re: putting a short list of integers into a (specific)
	compact form
In-Reply-To: <8683ADE5-FC84-11D7-BB7D-003065555ABC@mac.com>
Message-ID: <F3F400EB-FC98-11D7-97B0-003065555ABC@mac.com>

> 1. Initially, all duplicate elements should be eliminated and the 
> elements should
>    be written so that they are ascending in order (all integers are 
> mapped mod 12).

I should say that i got this part (#1) (see below) and step 4 and my 
optional little step 5 is probably pretty
easy. It is the step 2 and 3 parts that i can't get my head round 
coding. I guess what i want is to generate
each list (as i have done below) and compare the intervals between each 
list element and between the
two list and i am 100000% sure there is some elegant way to do this in 
Python, it seems the kind of thing
python was born to handle, with something sexy like bisect or list 
comprehension... hmm.... i'll keep thinking
and hope that someone will lend a hand.... maybe once the list is made 
then a list of list can be built like:

[0,4,8,9,11]
[4,8,9,11,0]
[8,9,11,0,4]
[9,11,0,4,8]
[11,0,4,8,9]

and each interval can be taken and stored in a list? Hmmm... I just 
don't know. I guess that i am just reaching
so that i don't look to silly on the tutor list, but i really don't 
know so i should just shut up and see what folks
propose.

-kp--



--
--

#!/usr/bin/env python

import sys
import random

def unique(seq):
   try: # attempt fast algorithm
     d = {}
     for x in seq: d[x] = 0
     return d.keys()
   except TypeError: # have an unhashable object, use slow algorithm
     ret = []
     app = ret.append
     for x in seq:
       if x not in ret: app(x)
     return ret

def test():
	random.seed(720)
	x = range(0, 12, 1)
	print x; print
	random.shuffle(x)
	print x
	y= range(0, 12, 1)
	print y; print
	random.shuffle(y)
	print y; print
	x.extend(y)
	print x; print
	x.sort()
	print x; print
	z=unique(x)
	print z; print


if __name__ == "__main__":
	test()




> 2. Since there will be as many ways to order them as there are 
> elements in
>    the list, we want to choose the ordering that has the
>    smallest interval from lowest element to highest one.
>
> 3. If there is still a tie under rule #2 we want to pick the list that 
> is
>   most packed to the left (by finding the intervals between the first 
> element
>   and the second to last element and comparing the intervals of each 
> list in
>   the tie, if there is still a tie, compare the intervals between 
> first element
>   in the lists and the third to last, etc.)
>
> 4. If this still results in a tie for each element, for example in the 
> case of:
>    [10,1,6] , [1,6,10] , and [6,10,1] we choose [1,6,10], since
>    it's first element is 1.
>
> (finally, and optionally, i'll likely need to transpose the answer so 
> that
> it starts on 0)
>
> So in a set with the following five possible orderings (here already 
> sorted low to high
> and proceeding systematically (again %12)):
>
> [0,4,8,9,11]
> [4,8,9,11,0]
> [8,9,11,0,4]
> [9,11,0,4,8]
> [11,0,4,8,9]
>
> So the interval between the first element and the last is
>
> [0,4,8,9,11] = 0-11 = 11
> [4,8,9,11,0] = 0-4 = 12-4 = 8
> [8,9,11,0,4] = 4-8 = 16 - 8 = 8
> [9,11,0,4,8] = 9-8 = 20-9 = 11
> [11,0,4,8,9] = 9-11 = 21-11 = 10
>
> Here end up with a tie between the second and third orderings above. 
> So we go to
> rule #3: We compare the intervals btween the first and next to last 
> elements:
>
> second ordering: 11-4 = 7
> third ordering: 0-8 = 4
>
> Since 4 is smaller than 7 we conclude the third ordering [8,9,11,0,4] 
> is more packed to the left and
> what we want and there is no need for rule 4 in this case.
>
> I hope that i have stated the question clearly. I would appreciate any 
> help folks could give on this. Frankly it is beyond
> what i can do at this point, but i would like to see how others 
> approach this in the hopes that my code will work and that
> i might learn something.
>
> Best,
>
> kevin
>
>
> --^----------------------------------------
>
>   kp8 @ mac . com
>


From bvg.pythontutor at freemail.hu  Sun Oct 12 06:31:57 2003
From: bvg.pythontutor at freemail.hu (Gabor Borgulya)
Date: Sun Oct 12 06:31:05 2003
Subject: [Tutor] putting a short list of integers into a (specific)
	compact form
In-Reply-To: <8683ADE5-FC84-11D7-BB7D-003065555ABC@mac.com>
References: <8683ADE5-FC84-11D7-BB7D-003065555ABC@mac.com>
Message-ID: <1065954717.2063.9.camel@catv-d5de952e.bp04catv.broadband.hu>

2003-10-12, v keltez?ssel kevin parks ezt ?rta:
> 1. Initially, all duplicate elements should be eliminated and the 
> elements should
>     be written so that they are ascending in order 

>>> l=[1,8,5,3,7,8,2,11,1,2,0,5] # a list with duplicate elements
>>> wod=[] # this will be the new list without duplicates
>>> for i in l:       
...    if i not in wod: # we append only if it is not already there
...       wod.append(i)
...
>>> wod
[1, 8, 5, 3, 7, 2, 11, 0]
>>> wod.sort() # sort in place
>>> wod
[0, 1, 2, 3, 5, 7, 8, 11]

I couldn't understand the rest of your question.
Hope this helps.

G?bor

From kalle at lysator.liu.se  Sun Oct 12 07:55:28 2003
From: kalle at lysator.liu.se (Kalle Svensson)
Date: Sun Oct 12 07:55:33 2003
Subject: [Tutor] Re: putting a short list of integers into a (specific)
	compact form
In-Reply-To: <F3F400EB-FC98-11D7-97B0-003065555ABC@mac.com>
References: <8683ADE5-FC84-11D7-BB7D-003065555ABC@mac.com>
	<F3F400EB-FC98-11D7-97B0-003065555ABC@mac.com>
Message-ID: <20031012115528.GY9058@i92.ryd.student.liu.se>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

[kevin parks]
> >1. Initially, all duplicate elements should be eliminated and the 
> >elements should
> >   be written so that they are ascending in order (all integers are 
> >mapped mod 12).
> 
> It is the step 2 and 3 parts that i can't get my head round 
> coding.

I would try to put all the lists in a big list, and use the cmpfunc
argument of the list sort method.  Something like this:

def dist(lst, elem):
    if lst[0] < lst[elem]:
        return lst[elem] - lst[0]
    return 12 - lst[0] + lst[elem]
 
def funny_compare(l1, l2):
    end = -1
    while abs(end) < len(l1):
        d1, d2 = dist(l1, end), dist(l2, end)
        if d1 < d2:
            return -1
        if d2 < d1:
            return 1
        end -= 1
    return cmp(l1[0], l2[0])                                      

It seems to work for some data:

>>> x = [[0, 4, 8, 9, 11], [4, 8, 9, 11, 0],
... [8, 9, 11, 0, 4], [9, 11, 0, 4, 8], [11, 0, 4, 8, 9]]
>>> x.sort(funny_compare)
>>> for a in x:
...     print a
... 
[8, 9, 11, 0, 4]
[4, 8, 9, 11, 0]
[11, 0, 4, 8, 9]
[9, 11, 0, 4, 8]
[0, 4, 8, 9, 11]

The following example doesn't produce the results you wanted in your
original post, but I don't understand why e.g. [10,1,6] and [1,6,10]
should be equal in distances.  Isn't the distance from 10 to 6 == 8,
and the distance from 1 to 10 == 9?

>>> y = [[10,1,6],[1,6,10],[6,10,1]]
>>> y.sort(funny_compare)
>>> y
[[6, 10, 1], [10, 1, 6], [1, 6, 10]]

I think I have misunderstood some part of the algorithm.  Maybe you
can start with this solution and change it to correctly implement your
algorithm?

As an aside, this might not be the fastest way to implement the
algorithm (using cmpfunc is slow), but it is quite simple and clear in
my opinion.

Peace,
  Kalle
- -- 
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.7 (GNU/Linux)
Comment: Processed by Mailcrypt 3.5.6 <http://mailcrypt.sourceforge.net/>

iD8DBQE/iUEodNeA1787sd0RAnNMAJ43Rke4zGGWvd61fIA8XUpDZjxuWgCfT9OV
J+za0Jgdz+v1PihnJgg0NZs=
=BJ62
-----END PGP SIGNATURE-----

From gbrunet at sempersoft.com  Sun Oct 12 07:40:16 2003
From: gbrunet at sempersoft.com (Greg Brunet)
Date: Sun Oct 12 08:10:22 2003
Subject: [Tutor] Testing for punctuation in a string
Message-ID: <bmbej9$lug$1@sea.gmane.org>

I'm trying to process a string of 'new field names' that will be comma
separated, and want to make sure that there are no punctuation
characters present (except for commas and underscores).  Is there a
pythonic way to do this.  The list of characters that I DON'T want to
allow are (and even this might not be very efficient):

import string
badchar = string.punctuation.replace('_','').replace(',','')

If s is my list of fieldnames (s='fld1,fld2,fld-bad'), I'm not sure what
to do next.  I would probably split the string & test it a character at
a time, but I am hoping for something better.  Thanks,

-- 
Greg



From guillermo.fernandez at epfl.ch  Sun Oct 12 08:50:38 2003
From: guillermo.fernandez at epfl.ch (Guillermo Fernandez)
Date: Sun Oct 12 08:50:53 2003
Subject: [Tutor] CVS package
Message-ID: <3F894E1E.6020106@epfl.ch>

Hi,

Is there any CVS package in python?
I'm looking for something to interact with a CVS server.
I haven't find anything with google (other that CVS's of programs... :-)

Thanks!

Guille


From godoy at metalab.unc.edu  Sun Oct 12 10:05:00 2003
From: godoy at metalab.unc.edu (Jorge Godoy)
Date: Sun Oct 12 10:05:50 2003
Subject: [Tutor] CVS package
In-Reply-To: <3F894E1E.6020106@epfl.ch> (Guillermo Fernandez's message of
	"Sun, 12 Oct 2003 14:50:38 +0200")
References: <3F894E1E.6020106@epfl.ch>
Message-ID: <m3oewmimb7.fsf@ieee.org>

Guillermo Fernandez <guillermo.fernandez@epfl.ch> writes:

> Is there any CVS package in python?
> I'm looking for something to interact with a CVS server.
> I haven't find anything with google (other that CVS's of programs... :-)

One like the svn (subversion) module would be very interesting. 

-- 
Godoy.     <godoy@metalab.unc.edu>

From alan.gauld at blueyonder.co.uk  Sun Oct 12 12:41:25 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Sun Oct 12 12:43:09 2003
Subject: [Tutor] putting a short list of integers into a (specific)
	compactform
References: <8683ADE5-FC84-11D7-BB7D-003065555ABC@mac.com>
Message-ID: <002401c390df$ad9ab590$6401a8c0@xp>

> I've got a question. It is a bit of a brain teaser for me and i am
> trying to figure out nice and pythonic way of going about things,

I'm trying to think why on earth anyone would want to do such
a thing! Can you assuage my curiosity?


Whatever, a brute force approach follows:

OK, removing duplicates can be done in a brute force style by
just checking for pre-existence prior to insertion:

original =[<some data set here>]
unique = []
for item in original:
    if item not in unique: unique.append(item)

# Now we want all the lists possible:

possibles = [unique[:]]  # store a copy
for j in unique:
   previous = possibles[-1]
   possibles.append[previous[1:-1] + previous[0]]

# we now have a list of options.
# so define a function to calculate the delta
def getDelta(low,high,mod=12):
    # an exercise for the reader... :-)

# add the delta to the options as a tuple
candidates = []
for option in possibles:
    candidates.append((option, getDelta(option[0],option[-1]))

# now sort by delta
def sortByDelta(t1,t2):
    return cmp(t1[1],t2[1])

canditates.sort(sortByDelta)

lowest = candidates[0][1]
candidates = [option[0] for option in candidates if option[1] ==
lowest]

# At this point we have the list of lists with the
# lowest possible deltas.

At this point we can go through the candidates list applying
the 4 rules until we only have 1 canditate left... I'm sure
there are cleaner ways, and the code above is untested pseudo
code but it should be a basis for something...

HTH,

Alan G.


From alan.gauld at blueyonder.co.uk  Sun Oct 12 12:52:36 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Sun Oct 12 12:54:18 2003
Subject: [Tutor] Testing for punctuation in a string
References: <bmbej9$lug$1@sea.gmane.org>
Message-ID: <002f01c390e1$3d153ff0$6401a8c0@xp>

> If s is my list of fieldnames (s='fld1,fld2,fld-bad'), I'm not sure
what
> to do next.  I would probably split the string & test it a character
at
> a time, but I am hoping for something better.  Thanks,

Ultimately you will have to test each character but you want to
do it in C rather than Python. However the best I can think of
is a comprehension:

class Oops(Exception): pass

def checkName(name):
  # use comprehension to maximise use of C code
  if len([char for char in name if char in punctuation]) == 0
      raise Oops

ok = []
for name in names:
   try:
      checkName(name)
      ok.append(name)
   except Oops:
      pass

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


From bwalling at coastdental.com  Sun Oct 12 13:57:26 2003
From: bwalling at coastdental.com (Benjamin Walling)
Date: Sun Oct 12 13:57:31 2003
Subject: [Tutor] Report Writer
Message-ID: <61119D047A3FE84E83EF2FFDA9A156A486230D@cstntexch01.coastdental.lan>

I've started to evaluate moving to Python from ASP.NET.  One of the hurdles I have come across is Crystal Reports.  We use Crystal extensively.

I've found that there are a few open source projects for report writing, the best of which seems to be JasperReports.

Can either Crystal or Jasper be called from Python?  Linux or Windows?

From glingl at aon.at  Sun Oct 12 14:43:52 2003
From: glingl at aon.at (Gregor Lingl)
Date: Sun Oct 12 14:45:44 2003
Subject: [Tutor] Report Writer
In-Reply-To: <61119D047A3FE84E83EF2FFDA9A156A486230D@cstntexch01.coastdental.lan>
References: <61119D047A3FE84E83EF2FFDA9A156A486230D@cstntexch01.coastdental.lan>
Message-ID: <3F89A0E8.6030307@aon.at>



Benjamin Walling schrieb:

>I've started to evaluate moving to Python from ASP.NET.  One of the hurdles I have come across is Crystal Reports.  We use Crystal extensively.
>
>I've found that there are a few open source projects for report writing, the best of which seems to be JasperReports.
>
>Can either Crystal or Jasper be called from Python?  Linux or Windows?
>  
>
Hi Benjamin,

I don't konw, but I recommend to hava a look at

http://www.reportlab.org. especially

http://www.reportlab.org/rl_toolkit.html

another open source report toolkit which uses Python itself.

Regards, Gregor

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


From anna at aleax.it  Sun Oct 12 16:31:29 2003
From: anna at aleax.it (Anna Ravenscroft)
Date: Sun Oct 12 16:31:36 2003
Subject: [Tutor] CVS package
In-Reply-To: <m3oewmimb7.fsf@ieee.org>
References: <3F894E1E.6020106@epfl.ch> <m3oewmimb7.fsf@ieee.org>
Message-ID: <200310122231.29587.anna@aleax.it>

On Sunday 12 October 2003 04:05 pm, Jorge Godoy wrote:
> Guillermo Fernandez <guillermo.fernandez@epfl.ch> writes:
> > Is there any CVS package in python?
> > I'm looking for something to interact with a CVS server.
> > I haven't find anything with google (other that CVS's of programs... :-)

My understanding is that there isn't really any module for Python - folks 
manually open a shell or use os.system or os.open to run a command line. 
There is a project going on at cvshome.org... called libcvs, for perl and 
java.... but nobody yet appears to be working on a python version... 

> One like the svn (subversion) module would be very interesting.

Many folks apparently are more happy with moving to subversion, than 
continuing to support CVS. The PyPy project, for example, uses subversion. 
Building the server is said to be a bear, according to folks who ought to 
know, like AMK. But installing and using it as a client is quite easy.

Anna
-- 
There is a type 3 error in which your mind goes totally blank whenever you try 
to remember which is which of type 1 and type 2.
                                                 -Richard Dawkins


From anna at aleax.it  Sun Oct 12 17:35:34 2003
From: anna at aleax.it (Anna Ravenscroft)
Date: Sun Oct 12 17:35:40 2003
Subject: [Tutor] Testing for punctuation in a string
In-Reply-To: <002f01c390e1$3d153ff0$6401a8c0@xp>
References: <bmbej9$lug$1@sea.gmane.org> <002f01c390e1$3d153ff0$6401a8c0@xp>
Message-ID: <200310122335.34640.anna@aleax.it>

On Sunday 12 October 2003 06:52 pm, Alan Gauld wrote:
> > If s is my list of fieldnames (s='fld1,fld2,fld-bad'), I'm not sure

Make sure your list of fieldnames has quotes around each item, not just the 
beginning and end of the list... 

> what to do next.  I would probably split the string & test it a character
> at a time, but I am hoping for something better.  Thanks,

Ouch. Sounds long and unpleasant.

I like the nifty new sets module (available in 2.3). You can use a list 
comprehension (as Alan suggested) but if you have more than one type of "bad" 
punctuation in a particular fieldname, you'll get duplicates. If you use the 
new sets module, you can eliminate the duplicates. 

>>> import sets
>>> fieldnames=['fld1','fld2','fld-bad', 'fld-ba_d']
>>> bad = ['-'. '_']
>>> badfld = [f for f in fieldnames for b in bad if b in f]
>>> print badfld                            # will print any duplicates
['fld-bad', 'fld-ba_d', 'fld-ba_d']      
>>> setofbad = sets.Set(badfld)    # removes the duplicates
>>> print setofbad
Set(['fld-ba_d', 'fld-bad'])
>>>

Hope this gives you some ideas... Have fun.

Anna
-- 
There is a type 3 error in which your mind goes totally blank whenever you try 
to remember which is which of type 1 and type 2.
                                                 -Richard Dawkins


From python at rcn.com  Sun Oct 12 19:21:06 2003
From: python at rcn.com (Raymond Hettinger)
Date: Sun Oct 12 19:21:45 2003
Subject: [Tutor] putting a short list of integers into a (specific)
	compactform
In-Reply-To: <8683ADE5-FC84-11D7-BB7D-003065555ABC@mac.com>
Message-ID: <000d01c39117$83bec9e0$e841fea9@oemcomputer>

[kevin parks]
> here's what i'd like to do (it is quite complex, but it have tried to
> present the recipe as
> clearly as possible):


It is not so bad if you break in down functionally and use generators.
* rule1() applies the inital step
* rotations() returns a generator for each ordering
* orderings() prepends three values corresponding to rules 2, 3, and 4
* min() selects the best ordering based on rule2, falling back to 3
  in a tie, and back to four for a final tie breaker
* [3] throws away the ordering info leaving on the best sequence
* optional() applies to final transpose rule


def rule1(s):
    "Apply mod12, eliminate duplicates, and sort"
    set = {}
    for elem in s:
        set[elem%12] = True
    nodups = set.keys()
    nodups.sort()
    return nodups

def rotations(s):
    "generate all rotations of a sequence"
    for i in xrange(len(s)):
        yield s
        s = s[1:] + s[0:1]

def ordering(rots):
    "rules for deciding which rotation comes first"
    for s in rots:
        rule2 = (s[-1] - s[0]) % 12
        rule3 = (s[-2] - s[0]) % 12
        rule4 = s[0]
        yield rule2, rule3, rule4, s

def optional(s):
    "transpose the answer so it starts with zero"
    return [(x - s[0])%12 for x in s]
        

start = [4, 12, 20, 9, 11, 0, 8, 4]
print optional(min(ordering(rotations(rule1(start))))[3])


Raymond Hettinger


From kp8 at mac.com  Sun Oct 12 22:34:21 2003
From: kp8 at mac.com (kevin parks)
Date: Sun Oct 12 22:34:37 2003
Subject: [Tutor] putting a short list of integers into a (specific)
	compactform
In-Reply-To: <002401c390df$ad9ab590$6401a8c0@xp>
Message-ID: <C078FC1A-FD25-11D7-A51E-003065555ABC@mac.com>


On Sunday, October 12, 2003, at 12:41  PM, Alan Gauld wrote:

>> I've got a question. It is a bit of a brain teaser for me and i am
>> trying to figure out nice and pythonic way of going about things,
>
> I'm trying to think why on earth anyone would want to do such
> a thing! Can you assuage my curiosity?

Hi Alan. Thanks for your reply. I am still working on this and have the 
first few steps taken care of.
but, since you and a bunch of other folks are curious I ought to 
explain what this is needed for. I didn't
mean for it to be so mysterious, but i noticed my post was already 
getting quite convoluted so
i was trying to cut to the chase as best as i could.

I am trying to use this to form what is called the 'normal form' of a 
set of musical pitches. Here the pitches
are all represented as numbers 0-11. In order to compare sets and see 
if they are inversionally or
transpositionally related, or if they will have any common tones under 
transposition or inversion
it is helpful to put the sets in this compact form. There are lots of 
buggy little java applets that do this
on the web.

http://mail.rochester.edu/~af006m/Clock2.html
http://www.jaytomlin.com/music/settheory/
http://www.webcalc.net/calc/0515.php
http://gigue.peabody.jhu.edu/~pnelson/PCSets/setfinder.html
http://www.cosmoedu.net/DoctorFields/TTTBLow.html

but i want to do this from within python.

As i said i have the unique(), sort, and rotate() thing sort of 
working, but then i have to figure out how
work with that to get my steps 3,4 (and 5). Raymond Hettinger has 
replied as well an i am looking at
how he has broken the problem down and it is helping me understand a 
bit better.


-kevin





From idiot1 at netzero.net  Sun Oct 12 23:15:46 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Sun Oct 12 23:16:08 2003
Subject: [Tutor] Testing for punctuation in a string
In-Reply-To: <200310122335.34640.anna@aleax.it>
References: <bmbej9$lug$1@sea.gmane.org> <002f01c390e1$3d153ff0$6401a8c0@xp>
	<200310122335.34640.anna@aleax.it>
Message-ID: <3F8A18E2.5090805@netzero.net>

May I please jump in the thread?

I just wrote 2 wiki's, and had to sort things out, seperating sheep from goats 
just this way. And I had to do it a char at a time, and used recursion in doing 
it. You might not want to use recursion, but maybe you will...

My task was to return a 1 or a 0 for an if statement to swallow and genuflect 
at. A function looked at a word and nibbled through it char by char, using other 
functions, which were recursive, and decided if a word was a wiki word. ( a 
WikiWord is 2+ words RunTogetherLikeThis, each capitalized, and no punctuation 
within them. So 'WikiWord' is a wikiword, but 'Wiki-Word' is not. I used a lot 
of string slicing, IF statements, IN, and the string module's constants 
(string.uppercase, string.punctuation, etc).

Each function is rather simple in itself, and the total effect is a fairly 
powerful word chomper. And NO gang, this time I did NOT do any counting, which 
kept it from being a state engine in the first one I wrote.

Here is the stript I wrote using these functions. Note it is optimized for 
operation in a windows 9x environment.

BEWARE WORD WRAP! I edited this to minimize as much as possible, and inserted
a '\' wher a code line wraps around, but please be careful, make your screen as 
wide as possible, maybe use a narrow font?
------------------------------------------------------------------------------
#!C:\Python22\pythonw.exe
#
tablebgcolor="FFE0C0"
import os, os.path, sys, string, re, cgitb; cgitb.enable()
print "Content-Type: text/html\n"
#
try:
	pagename=os.environ['QUERY_STRING']	# try to get page name requested
except Exception, e:
	pagename="FrontPage"			# but default to FrontPage
#
path=os.getcwd()
path=path+'\\cgi-bin\\text'
os.chdir(path)		# make the pages dir current
if os.path.exists(pagename):			# if the page asked for exists,
	pass					# do nothing here;
else:						# BUT if it does NOT-
	f1=open(pagename,'w')			# CREATE it!
	f1.write('Please contribute to this webpage.\n')
	f1.close()
#
# header for webpage
print '<html><head><title>MiniWiki - '+ pagename +'</title>'
print '<style type="text/css">'
print 'body { margin-left: 5%; margin-right: 5%; }'
print 'A:link, A:visited,  A:active { text-decoration:none; }'
print 'A:hover { background-color: #D0D0FF; }'
print '</style></head>'
print '<body bgcolor="FFFFFF" text="000000" links="0000FF">'
print '<table width=100% bgcolor="'+tablebgcolor+'" border="0"
print 'cellpadding="10"><tr><td>'
print '<B><font size="4" color="FF0000">MiniWiki</font></B>'
print '<center><font size="6"><a href="./MWbacksearch.py?' + pagename+'">'
print string.join(re.split('([A-Z][a-z]*)',pagename)[1:-1]) + '</a></font><br>'
print '(Click for backsearch)<p></center></td></tr></table>'
f1=open(pagename,'r')
page=f1.readlines()
f1.close()
#
def isin( searchthis, forthis ):	# return a 1 or 0 to control IF statements
	value = 1 + string.find(searchthis, forthis)
	if value > 0:
		return 1
	else:
		return 0
#
#
# Now we try to hash out wiether or not a word is a wikiword...
# a WikiWord is in CamelCaps. it has a 'hump' in it.
# ThisIs a WikiWord,
# but ThisISNOT,
# ANDNEITHERISTHIS,
# NorisTHIS. Fun?
#
# these functions build wikiwords.
def buildwikilink(word):		# turns a word into a hyperlink
	word = '<a href="./MW.py?' + word + '">' + word + '</a>'
         # it's a hyperlink anchor, normal html.
	return word
#		
def potentialword(word):	#
	newword=''
	prefix=''
	suffix=''
	index=0
	while 1:			# loop processes the word 1 char at time
		if word[index] in string.ascii_letters:
			prefix, newword, suffix = mainbody(prefix, word[index:])
			return prefix, newword, suffix

		else:
			prefix=prefix+word[index]
			index=index+1
#
def mainbody(prefix, word,):
	newword=''
	suffix=''
	index=0
	for char in word:
		if char in string.ascii_letters:	
			newword=newword+char
		else:
			suffix=suffix+char	#
		index=index+1
	return prefix, newword, suffix
#
def makewikiword(word):				# combines processed link
	prefix=''
	suffix=''
	prefix, word, suffix=potentialword(word)
	return prefix + buildwikilink(word) + suffix
#
#
# these 2 words determine if a word is a wikiword.
def iswikiword(word):				# tests to see if is wikiword.
	if word:
		if word[0]in string.ascii_uppercase: # ALL start with capital.
			if (len(word)>1): 	# guard for 'A' word
				if word[1] in string.ascii_lowercase:	#
					if (len(word)>3):										# is there any more to process?
						if processword(word[2:]):									# is there another?
							return 1			# YES! it's a wikiword!
	return 0					# it's not a wikiword.
#
def processword(word):
	if word:					# it is possible to
# exaust a word and not find another capital letter
		if word[0] in string.ascii_lowercase:	# wikiwords CAN have
# several lowercase letters before the next capital, after all...
			value=processword(word[1:])		# so keep
# invoking this word until exaustion, or a capital is found
			return value
		else: 					# MIGHT be a capital!
			if word[0] in string.ascii_uppercase:
				if len(word)>1: 	
					if word[1] in string.ascii_lowercase:
						return 1
					else:
						return 0	
				else:
					return 0	
			else:
				return 0		
	else:
		return 0
#
#
#
# this group processes the raw page to convert it to html code- but not 
wikiwords or links.
index=0
for line in page:			# process the line for substrings
	line=string.rstrip(line)			# kill EOL stuff
	line=string.replace(line,'<','&lt;')		# kills html tag opener
	line=string.replace(line,'>','&gt;')		# kills html tag closer
	line=string.replace(line,'----','<hr>')		# create standard <hr>
	line=string.replace(line,'@!','<center>')	# open centering
	line=string.replace(line,'!@','</center>')	# close centering
	line=string.replace(line,"```","<b>")		# open BOLD
	line=string.replace(line,"'''","</b>")		# close BOLD
	line=string.replace(line,"``","<i>")		# open ITALIC
	line=string.replace(line,"''","</i>")		# Close Italic
	line=string.replace(line,"{{{","<pre>")		# open PREFORMATTED TEXT
	line=string.replace(line,"}}}","</pre>\n")	# close PREFORMATTED
	line=string.replace(line,'<br>','')		# remove any BR's.
	line=string.replace(line,'[=','<table border="0" cellpadding="5" \
width=100% bgcolor="'+tablebgcolor+'"><tr><td><B><big>') # create header bar
	line=string.replace(line,'=]','</big></b></td></tr></table>\n')	# end
	# header bar
	line=string.replace(line,'{{{','<pre>')	# start <pre> zone
	line=string.replace(line,'}}}','<pre>')	# END a <pre> zone with </pre>
	line=string.replace(line,'#! ','<img src="../images/')	# start img tag
	line=string.replace(line,' !#','"><br>\n')	# end an image tag
	line=string.replace(line,'-!','<small>')	# insert small tag
	line=string.replace(line,'!-','</small>')	# insert end small tag
	line=string.replace(line,'+!','<big>')	# insert <bigh> tag
	line=string.replace(line,'!+','</big>')	# insert END of BIG state
	if line == "":					# null line> with <P>
		line='<p>\n'
	page[index]=line				# save resulting line
	index=index+1					# and increase pointer.
#
# wordscanner routine
linecounter=0		# reset the linepointer we will use it again...
for line in page:					# see?
	wordcounter=0					# start the word pointer over at 0 again
	wordlist = string.split(line,' ') # split the line into a list of words.
	for word in wordlist:
		if ((isin(word,'http://')) or (isin(word,'mailto:'))):
		#if link:
			if isin(word,'"'):
			# DO NOT process a "http- it's imbedded code!
				pass
				# DO NOT process; leave the word alone!
			else:
				# otherwise, make a hyperlink for them to click.
				wordlist[wordcounter]='<a href="' + word + '">'\ + word + '</a>'
		else:
			if iswikiword(word):
				wordlist[wordcounter]=makewikiword(word)
			else:
				pass
		wordcounter=wordcounter+1
	line=string.join(wordlist,' ')
	page[linecounter]=line
	linecounter=linecounter+1
#
# print out the final highly modified page.
for line in page:
	print line
#
# Page footer follows
print '<p><table border="0" width=100% cellpadding="10" bgcolor="'+tablebgcolor+'">'
print '<tr>'
print '<td width=30% ><a href="./MWed1.py?'+pagename+'" >Edit this page</a></td>'
print '<td align="center" width=40% ><form method="GET" 
action="./MWbacksearch.py?">'
print '<input type="text" size="20" maxlength="24" name="">&nbsp;<input 
type=submit value="WORDSEARCH">'
print '</form></td>'
print '<td align="right" width=30% ><a href="./MWlistall.py">LIST ALL 
PAGES</a></td></tr>'
print '<tr><td><a href="http://www.tinylist.org/">MiniWiki V:1.3.0<br>&copy;2003 
Kirk D Bailey</a></td>'
print '<td>&nbsp;</td>'
print '<td align="right"><a 
href="./MW.py?FrontPage">FrontPage</a></td></tr></table>'
print '</body></html>'
------------------------------------------------------------------------------
BEWARE WORD WRAP!

That is the complete wiki browser engine. If you want the entire suite of 
several scripts I am using, I will email it to you off list- email me and ask 
for it.

Anna Ravenscroft wrote:

> On Sunday 12 October 2003 06:52 pm, Alan Gauld wrote:
> 
>>>If s is my list of fieldnames (s='fld1,fld2,fld-bad'), I'm not sure
> 
> 
> Make sure your list of fieldnames has quotes around each item, not just the 
> beginning and end of the list... 
> 
> 
>>what to do next.  I would probably split the string & test it a character
>>at a time, but I am hoping for something better.  Thanks,
> 
> 
> Ouch. Sounds long and unpleasant.
> 
> I like the nifty new sets module (available in 2.3). You can use a list 
> comprehension (as Alan suggested) but if you have more than one type of "bad" 
> punctuation in a particular fieldname, you'll get duplicates. If you use the 
> new sets module, you can eliminate the duplicates. 
> 
> 
>>>>import sets
>>>>fieldnames=['fld1','fld2','fld-bad', 'fld-ba_d']
>>>>bad = ['-'. '_']
>>>>badfld = [f for f in fieldnames for b in bad if b in f]
>>>>print badfld                            # will print any duplicates
> 
> ['fld-bad', 'fld-ba_d', 'fld-ba_d']      
> 
>>>>setofbad = sets.Set(badfld)    # removes the duplicates
>>>>print setofbad
> 
> Set(['fld-ba_d', 'fld-bad'])
> 
> 
> Hope this gives you some ideas... Have fun.
> 
> Anna

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Prometheus
  +                              kniht                                +

Fnord.


From tony at tcapp.com  Sun Oct 12 23:40:05 2003
From: tony at tcapp.com (Tony Cappellini)
Date: Sun Oct 12 23:43:28 2003
Subject: [Tutor] Auto login of website
Message-ID: <5.1.0.14.0.20031012203457.01bda8d8@smtp.sbcglobal.net>



Would anyone happen to have a small python program (with or without gui) 
that can

log a user into a website, at regular intervals ?

The program would have to take the following as input (can be hard-coded, 
or on the cmd line)

1. the URL of a website (http)
2. the user ID
3. the user pasword
4. click (simulate a keypress or mouse click) on the button to log the user in

if the user could not be logged in, due to the website being overloaded, 
then it would do a retry at the next interval (where the interval can be
supplied by the user, preferably in seconds)

I've already checked the Python Cookbook, didn't find a match for the 
keywords I used


From gbrunet at sempersoft.com  Mon Oct 13 04:21:47 2003
From: gbrunet at sempersoft.com (Greg Brunet)
Date: Mon Oct 13 04:33:34 2003
Subject: [Tutor] Re: Testing for punctuation in a string
References: <bmbej9$lug$1@sea.gmane.org> <002f01c390e1$3d153ff0$6401a8c0@xp>
Message-ID: <bmdo0l$ol4$1@sea.gmane.org>

"Alan Gauld" <alan.gauld@blueyonder.co.uk> wrote in message
news:002f01c390e1$3d153ff0$6401a8c0@xp...
> Ultimately you will have to test each character but you want to
> do it in C rather than Python. However the best I can think of
> is a comprehension:
>...

Hi Alan:

Yes - I can see how comprehension would be slightly more efficient.
OTOH, I want to kick out as soon as I see ANY error condition, so I may
stay with a standard FOR loop with a sys.exit (after displaying an error
message) if I find any bad characters.  Thanks for the ideas,

-- 
Greg



From gbrunet at sempersoft.com  Mon Oct 13 04:33:03 2003
From: gbrunet at sempersoft.com (Greg Brunet)
Date: Mon Oct 13 04:40:21 2003
Subject: [Tutor] Re: Testing for punctuation in a string
References: <bmbej9$lug$1@sea.gmane.org>
	<002f01c390e1$3d153ff0$6401a8c0@xp><200310122335.34640.anna@aleax.it>
	<3F8A18E2.5090805@netzero.net>
Message-ID: <bmdo0n$ol4$3@sea.gmane.org>

"Kirk Bailey" <idiot1@netzero.net> wrote in message
news:3F8A18E2.5090805@netzero.net...
> May I please jump in the thread?
>
> I just wrote 2 wiki's, and had to sort things out, seperating sheep
from goats
> just this way. And I had to do it a char at a time, and used recursion
in doing
> it. You might not want to use recursion, but maybe you will...

Hi Kirk:

I ended up using regex (the actual routine I used is in my response to
Anna).  Your code sample has a lot of interesting stuff though, so I'll
flag it to look at later for some more good ideas.  Thanks,

-- 
Greg




From gbrunet at sempersoft.com  Mon Oct 13 04:30:37 2003
From: gbrunet at sempersoft.com (Greg Brunet)
Date: Mon Oct 13 04:50:18 2003
Subject: [Tutor] Re: Testing for punctuation in a string
References: <bmbej9$lug$1@sea.gmane.org> <002f01c390e1$3d153ff0$6401a8c0@xp>
	<200310122335.34640.anna@aleax.it>
Message-ID: <bmdo0m$ol4$2@sea.gmane.org>

Hi Anna:

Thanks for your response.

"Anna Ravenscroft" <anna@aleax.it> wrote in message
news:200310122335.34640.anna@aleax.it...
> On Sunday 12 October 2003 06:52 pm, Alan Gauld wrote:
> > > If s is my list of fieldnames (s='fld1,fld2,fld-bad'), I'm not
sure
>
> Make sure your list of fieldnames has quotes around each item, not
just the
> beginning and end of the list...

Actually, I the string is getting loaded by a call to getopt, so I
wanted to show what I originally received in case there wasn't a need to
split it into the actual names.  If I want to look at it by names (which
I eventually did), my first step was to use:
    fields = s.split(',')

> > what to do next.  I would probably split the string & test it a
character
> > at a time, but I am hoping for something better.  Thanks,
>
> Ouch. Sounds long and unpleasant.

Yeah, but it was a quick and easy first approach.  For various reasons,
I ended up using regex, thought that might be a bit heavyweight for what
I needed:

p=re.compile('^[a-zA-Z]\w*$')
def fldNameValid(fldName):
    return p.match(fldName) != None


> I like the nifty new sets module (available in 2.3). You can use a
list
> comprehension (as Alan suggested) but if you have more than one type
of "bad"
> punctuation in a particular fieldname, you'll get duplicates. If you
use the
> new sets module, you can eliminate the duplicates.
>
> Hope this gives you some ideas... Have fun.
>
> Anna


I will look into sets though, so I am familiar with them for the next
time.  Thanks again,


-- 
Greg



From pythontutor at venix.com  Mon Oct 13 09:01:12 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Mon Oct 13 09:01:16 2003
Subject: [Tutor] Auto login of website
In-Reply-To: <5.1.0.14.0.20031012203457.01bda8d8@smtp.sbcglobal.net>
References: <5.1.0.14.0.20031012203457.01bda8d8@smtp.sbcglobal.net>
Message-ID: <3F8AA218.1030503@venix.com>

The urllib and urllib2 modules support accessing a website.  The module
documentation for urllib describes how to create your own class to
override functions provided by urllib.  In your case, you want to
override the method:
     prompt_user_passwd
to return a tuple containing your username and password.

import urllib
class MyURLopener(urllib.FancyURLopener):
     def prompt_user_passwd(host,realm):
     #ignore host and realm
     # substitue your id and password
     return ("mulder", "trustNo1")

urllib._urlopener = MyURLopener()

f = urllib.urlopen("http://www.some.com")
print f.read()

This omits cookie issues and other pitfalls.  You may find it easier to
use a program like wget to access URL's that have cookies and passwords
to control access.


Tony Cappellini wrote:

> 
> 
> Would anyone happen to have a small python program (with or without gui) 
> that can
> 
> log a user into a website, at regular intervals ?
> 
> The program would have to take the following as input (can be 
> hard-coded, or on the cmd line)
> 
> 1. the URL of a website (http)
> 2. the user ID
> 3. the user pasword
> 4. click (simulate a keypress or mouse click) on the button to log the 
> user in
> 
> if the user could not be logged in, due to the website being overloaded, 
> then it would do a retry at the next interval (where the interval can be
> supplied by the user, preferably in seconds)
> 
> I've already checked the Python Cookbook, didn't find a match for the 
> keywords I used
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582


From Janssen at rz.uni-frankfurt.de  Mon Oct 13 11:31:02 2003
From: Janssen at rz.uni-frankfurt.de (Michael Janssen)
Date: Mon Oct 13 11:31:22 2003
Subject: [Tutor] Re: Testing for punctuation in a string
In-Reply-To: <bmdo0m$ol4$2@sea.gmane.org>
References: <bmbej9$lug$1@sea.gmane.org> <002f01c390e1$3d153ff0$6401a8c0@xp>
	<200310122335.34640.anna@aleax.it> <bmdo0m$ol4$2@sea.gmane.org>
Message-ID: <Pine.A41.4.56.0310131536310.1526002@hermes-22.rz.uni-frankfurt.de>

On Mon, 13 Oct 2003, Greg Brunet wrote:

> I ended up using regex, thought that might be a bit heavyweight for what
> I needed:
>
> p=re.compile('^[a-zA-Z]\w*$')
> def fldNameValid(fldName):
>     return p.match(fldName) != None

Hello Greg Brunet,


in case your goal is to "test for punctuation in a string" you
should do that in the most direct way:

[untested]
_punctuation = string.punctuation.replace("_","").replace(",","")
aPattern = "[%s]" % _punctuation
mt = re.search(aPattern, aString)
if mt:
    # do whatever you want, including:
    raise Exception, \
      "fldName '%s' contains a '%s' on position %s" \
      % (fldName, mg.group(), mt.start() )

regular expression is the thing to test for the presence or absence of
patterns. The other way (iterating through the string and look if each
element is in a sequence of punctuation chars:

for s in aString:
    if s in _punctuation:
        raise

) is heavyweight in terms of performance: Python has to perform
len(aString) "s in _punctuation" lookups against one single
regexp-operation with the former example (OTOH, it is believed that
only testing the actual runtime of both solutions truly reveals their
better or worse performance).


When I may take a look at your latest approach (Testing legality by
definig a pattern the Field Name must match):

> p=re.compile('^[a-zA-Z]\w*$')
> def fldNameValid(fldName):
>     return p.match(fldName) != None

Doing things the other way around as in ones own goal-definition
(supposed I can take the thread's subject as such a thing ;-) might
be a clever choice in case it becomes clear that it's better than the
"former way around". Nevertheless it might introduce some unforeseen
results: Now, your pattern rejects whitespace and commas; Field Names
starting with numbers or an underscore will be rejected. All this might
be perfectly what you needs but it doesn't do the "Testing for
punctuation in a string" job any longer.

Beside this (and given that the additional restrictions for valid Field
Names are what you need), you're solution will do the job, and you won't
feel much of a performance impact as long as you don't want to parse a
serveral kB's commandline ;-)


Michael


From idiot1 at netzero.net  Mon Oct 13 12:36:33 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Mon Oct 13 12:37:10 2003
Subject: [Tutor] Re: Testing for punctuation in a string
In-Reply-To: <bmdo0n$ol4$3@sea.gmane.org>
References: <bmbej9$lug$1@sea.gmane.org>	<002f01c390e1$3d153ff0$6401a8c0@xp><200310122335.34640.anna@aleax.it>	<3F8A18E2.5090805@netzero.net>
	<bmdo0n$ol4$3@sea.gmane.org>
Message-ID: <3F8AD491.4010908@netzero.net>

thanks for the compliment Greg. This is the first time I ever used recursion in 
a significant way, and I *THINK* the series of functions which together form a 
state machine, check and see if I am blowing sunshine up my own kilt please.

Greg Brunet wrote:

> "Kirk Bailey" <idiot1@netzero.net> wrote in message
> news:3F8A18E2.5090805@netzero.net...
> 
>>May I please jump in the thread?
>>
>>I just wrote 2 wiki's, and had to sort things out, seperating sheep
> 
> from goats
> 
>>just this way. And I had to do it a char at a time, and used recursion
> 
> in doing
> 
>>it. You might not want to use recursion, but maybe you will...
> 
> 
> Hi Kirk:
> 
> I ended up using regex (the actual routine I used is in my response to
> Anna).  Your code sample has a lot of interesting stuff though, so I'll
> flag it to look at later for some more good ideas.  Thanks,
> 

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Prometheus
  +                              kniht                                +

Fnord.


From pythontutor at venix.com  Mon Oct 13 13:59:35 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Mon Oct 13 13:59:44 2003
Subject: [Tutor] Auto login of website
In-Reply-To: <20031013103414.B52710-100000@yamato.yamato.com>
References: <20031013103414.B52710-100000@yamato.yamato.com>
Message-ID: <3F8AE807.2080408@venix.com>

http://unxutils.sourceforge.net/
Native Win32 ports of some GNU utilities

wget is included in the list of utilities.


The python snippet I sent you should be close to working code.  You need
to specify the real URL, username, and password.  A class website is less
likely to have strange cookie requirements than commercial sites.  You might
find that the python code does the trick.

Tony Cappellini wrote:

> Thanks Lloyd
> 
> I dont know what wget is ?
> Is that available for Windows ?
> I need something that works now, as opposed to having to write a program.
> I'm not familair with web programming, and odnt have time to learn now,
> but need to get logged into a wesbtie to work on a project for a class.
> I'd liek to write  a Python version of the auto login program later though
> 
> 
> thanks
> 
> Tony
> 
> 
> On Mon, 13 Oct 2003, Lloyd Kvam wrote:
> 
> 
>>The urllib and urllib2 modules support accessing a website.  The module
>>documentation for urllib describes how to create your own class to
>>override functions provided by urllib.  In your case, you want to
>>override the method:
>>	prompt_user_passwd
>>to return a tuple containing your username and password.
>>
>>import urllib
>>class MyURLopener(urllib.FancyURLopener):
>>     def prompt_user_passwd(host,realm):
>>	#ignore host and realm
>>	# substitue your id and password
>>	return ("mulder", "trustNo1")
>>
>>urllib._urlopener = MyURLopener()
>>
>>f = urllib.urlopen("http://www.some.com")
>>print f.read()
>>
>>This omits cookie issues and other pitfalls.  You may find it easier to
>>use a program like wget to access URL's that have cookies and passwords
>>to control access.
>>
>>Tony Cappellini wrote:
>>
>>>
>>>Would anyone happen to have a small python program (with or without gui)
>>>that can
>>>
>>>log a user into a website, at regular intervals ?
>>>
>>>The program would have to take the following as input (can be
>>>hard-coded, or on the cmd line)
>>>
>>>1. the URL of a website (http)
>>>2. the user ID
>>>3. the user pasword
>>>4. click (simulate a keypress or mouse click) on the button to log the
>>>user in
>>>
>>>if the user could not be logged in, due to the website being overloaded,
>>>then it would do a retry at the next interval (where the interval can be
>>>supplied by the user, preferably in seconds)
>>>
>>>I've already checked the Python Cookbook, didn't find a match for the
>>>keywords I used
>>>
>>>
>>>_______________________________________________
>>>Tutor maillist  -  Tutor@python.org
>>>http://mail.python.org/mailman/listinfo/tutor
>>>
>>
>>--
>>Lloyd Kvam
>>Venix Corp.
>>1 Court Street, Suite 378
>>Lebanon, NH 03766-1358
>>
>>voice:	603-443-6155
>>fax:	801-459-9582
>>
>>
> 
> 
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582


From scot at possum.in-berlin.de  Mon Oct 13 21:35:34 2003
From: scot at possum.in-berlin.de (Scot W. Stevenson)
Date: Mon Oct 13 21:45:41 2003
Subject: [Tutor] osx python editor
In-Reply-To: <69372ED0-F227-11D7-84A4-000A9579AE94@csiro.au>
References: <69372ED0-F227-11D7-84A4-000A9579AE94@csiro.au>
Message-ID: <200310140335.34515.scot@possum.in-berlin.de>

Hello Kim, 

> i'm making the transition from perl to python, i'm trying to  convert a
> lot of tools into python so they can be maintained a little better.
> I'm looking at doing alot of my work under osx  rather than linux. 

I'm sure somebody has already pointed this out or that you have already 
considered this solution and found it lacking, but just to be sure: You 
might want to try an editor that will run on just about any platform, so you 
don't have to care which operating system you are running. My favorite is 
vim (http://www.vim.org), which runs on just about anything above a 6502 and 
is beautiful for pythonizing. You will, however, have to invest a bit of 
time to become familiar with it. 

Various Mac versions seem to live at 

http://macvim.swdev.org/OSX/

The vim page has more info.


Note to the list: vim has a new Python script, check

http://www.vim.org/scripts/script.php?script_id=790

for details. Haven't tried it out myself yet.

Y, Scot

-- 
                Scot W. Stevenson - Zepernick, Germany


From j.ezequiel at spitech.com  Mon Oct 13 22:45:15 2003
From: j.ezequiel at spitech.com (Ezequiel, Justin)
Date: Mon Oct 13 22:45:53 2003
Subject: [Tutor] unichr() question
Message-ID: <29E16390A38FD7118A03000BCD0F3F6501223811@mail.spiglobe.com>

PythonWin 2.2.2
Windows XP

>>> long('1D4AA', 16)
119978L
>>> unichr(long('1D4AA', 16))
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
ValueError: unichr() arg not in range(0x10000) (narrow Python build)
>>> x = eval("u'\\U000%s'" % '1D4AA')
>>> x
u'\U0001d4aa'
>>> for c in x:
... 	print ord(c)
... 
55349
56490
>>> unichr(55349) + unichr(56490)
u'\U0001d4aa'
>>> 

How do I convert strings such as '1D4AA' to unicode without using eval()?
Alternatively, how can I break down the value 119978L into 55349 and 56490?

From hall at ouhep1.nhn.ou.edu  Fri Oct 10 16:25:50 2003
From: hall at ouhep1.nhn.ou.edu (Isaac Hall)
Date: Tue Oct 14 14:19:45 2003
Subject: [Tutor] Re: Random numbers
In-Reply-To: <E1A82e1-0000DQ-00@hooloovoo>
Message-ID: <Pine.LNX.4.44.0310101525010.22001-100000@ouhep1.nhn.ou.edu>

In this case, the last number would not be random at all.

Ike

On Fri, 10 Oct 2003, Abel Daniel wrote:

> UCT Student - DLLBIA001 <DLLBIA001@mail.uct.ac.za> writes:
> 
> > i was just wandring if you could not help me to generate 25 random
> > numbers in the range of 0 to 24 without any number repeating.
> 
> Just a note: in this case you aren't 'generating random numbers' but
> 'shuffling numbers'.
> 
> Abel Daniel
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 


From m_anderson_0830 at yahoo.com  Fri Oct 10 22:26:55 2003
From: m_anderson_0830 at yahoo.com (Michelle R. Anderson Anderson)
Date: Tue Oct 14 14:19:51 2003
Subject: [Tutor] which way do I go?
Message-ID: <20031011022655.44589.qmail@web11501.mail.yahoo.com>

Hi Tutor:
     My name is Michelle.  I am learning languages for the first time in my life and right now I'm kind of on my own with it.  I have a pre-class assignment to complete, which is due by October 18, and I'm am totally lost.  I need to create a function that receives two numbers as arguments.  This function should add up all the integers between the two numbers, for example:
 
If I called the function with the numbers 3 and 9, I should get:
 
>>>sumdifference (3, 9)
 
my result should be 30
this comes from adding the numbers 4+5+6+7+8=30
 
This program should give me an output of:
the sum of integers between 3 and 9 is equal to 30
 
Now don't get me wrong, I am not looking for a step by step procedureto complete this problem.  However, I have been through several tutorials and nothing has pointed me in the right direction.  I've read about defining arguments and several other topics that seemed related, but I still cannot seem to get started.  All that I need is a big push in the right direction and possibly some pointers on finishing it off.  Please keep in mind that this is my very FIRST time attempting to program and I am doing this on my own (no instructors, no nothing).  Thank you so much for your time.  I cannot wait to hear your suggestions.
 
 
 




---------------------------------
Do you Yahoo!?
The New Yahoo! Shopping - with improved product search
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20031010/0a8af4fb/attachment.html
From tgoodear at bigpond.net.au  Sat Oct 11 18:55:35 2003
From: tgoodear at bigpond.net.au (Trevor G)
Date: Tue Oct 14 14:19:55 2003
Subject: [Tutor] A beginners question
Message-ID: <000b01c3904a$c8920be0$4f09fea9@J23388.tfil.com>

Hello guys,
I am new to programming and have installed 2.3.2 onto my pc operating under
Windows 98.
1. When I go to run a coded program ie Run Module F5 it takes a long time to
actually 'run'. Is this a normal feature of Python or should it simply take
several seconds and then 'run'. The code is very straight forward and is the
type of exercises seen in any Python textbook for beginners ... chapter 1.
Am I doing something stupid?
Hope you can be of assistance.
Thanks

Trevor Goodear
tgoodear@bigpond.net.au



From psgopu at rediffmail.com  Sun Oct 12 11:05:35 2003
From: psgopu at rediffmail.com (Perumal  Sadagopan)
Date: Tue Oct 14 14:19:59 2003
Subject: [Tutor] (no subject)
Message-ID: <20031012150535.6815.qmail@webmail8.rediffmail.com>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20031012/cbf5b793/attachment.html
-------------- next part --------------
pl tell me how to  edit a programm
From druidmatt at yahoo.com  Mon Oct 13 02:05:46 2003
From: druidmatt at yahoo.com (Matt Hehman)
Date: Tue Oct 14 14:20:03 2003
Subject: [Tutor] Newbie - Outputting List to a File
Message-ID: <20031013060546.31737.qmail@web10308.mail.yahoo.com>

I have written a program that will either give you
prime factors of an inputted number or inform you that
it is prime.  (That is pretty much my programming
resume.)  To do this, I begin by generating a list of
prime numbers, and then I use them for mod operations.
 I was wondering if there was a way to save the list
of primes generated to an output file so that I could
just retrieve it and use it for the next number I
tested.  I tried the .write command and received the
error message:

TypeError: argument 1 must be string or read-only
character buffer, not list

Also, I started playing around with increasingly large
numbers, is there anything I need to do to accomodate
that?



__________________________________
Do you Yahoo!?
The New Yahoo! Shopping - with improved product search
http://shopping.yahoo.com

From lkvam at venix.com  Mon Oct 13 09:00:28 2003
From: lkvam at venix.com (Lloyd Kvam)
Date: Tue Oct 14 14:20:08 2003
Subject: [Tutor] Auto login of website
In-Reply-To: <5.1.0.14.0.20031012203457.01bda8d8@smtp.sbcglobal.net>
References: <5.1.0.14.0.20031012203457.01bda8d8@smtp.sbcglobal.net>
Message-ID: <3F8AA1EC.4000407@venix.com>

The urllib and urllib2 modules support accessing a website.  The module
documentation for urllib describes how to create your own class to
override functions provided by urllib.  In your case, you want to
override the method:
	prompt_user_passwd
to return a tuple containing your username and password.

import urllib
class MyURLopener(urllib.FancyURLopener):
     def prompt_user_passwd(host,realm):
	#ignore host and realm
	# substitue your id and password
	return ("mulder", "trustNo1")

urllib._urlopener = MyURLopener()

f = urllib.urlopen("http://www.some.com")
print f.read()

This omits cookie issues and other pitfalls.  You may find it easier to
use a program like wget to access URL's that have cookies and passwords
to control access.

Tony Cappellini wrote:
> 
> 
> Would anyone happen to have a small python program (with or without gui) 
> that can
> 
> log a user into a website, at regular intervals ?
> 
> The program would have to take the following as input (can be 
> hard-coded, or on the cmd line)
> 
> 1. the URL of a website (http)
> 2. the user ID
> 3. the user pasword
> 4. click (simulate a keypress or mouse click) on the button to log the 
> user in
> 
> if the user could not be logged in, due to the website being overloaded, 
> then it would do a retry at the next interval (where the interval can be
> supplied by the user, preferably in seconds)
> 
> I've already checked the Python Cookbook, didn't find a match for the 
> keywords I used
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582


From gventer at fish.co.uk  Tue Oct 14 14:57:23 2003
From: gventer at fish.co.uk (Gerhard Venter)
Date: Tue Oct 14 14:57:09 2003
Subject: [Tutor] assigning a variable
Message-ID: <3F8C4713.8090704@fish.co.uk>

Hi

I have the following:

 >>> import os
 >>> K=os.system('curl -gs http://babelfish.altavista.com |grep -ic 
translate')
11
 >>> print K
0

What I am trying to do is a test to see if the website is running (as 
opposed to whether the web server is running).  Curl reads the website 
for me and grep counts the occurences of the word translate.  Later I 
might replace curl and grep with Python code that do the same job.

My question is why does K not assume the value of 11 and what can I do 
to make it do so.

Gerhard





From project5 at redrival.net  Tue Oct 14 15:27:27 2003
From: project5 at redrival.net (Andrei)
Date: Tue Oct 14 15:29:38 2003
Subject: [Tutor] Re: Newbie - Outputting List to a File
In-Reply-To: <20031013060546.31737.qmail@web10308.mail.yahoo.com>
References: <20031013060546.31737.qmail@web10308.mail.yahoo.com>
Message-ID: <bmhiqr$utg$1@sea.gmane.org>

Matt Hehman wrote:
<snip>
>  I was wondering if there was a way to save the list
> of primes generated to an output file so that I could
> just retrieve it and use it for the next number I
> tested.  I tried the .write command and received the
> error message:

It's called a method (function inside a class).

> TypeError: argument 1 must be string or read-only
> character buffer, not list

Use the str() function to convert a list (or anything else for that matter) to a 
string, like this:

somefile.write(str(somelist))

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur 
yvfg, fb gurer'f ab arrq gb PP.



From project5 at redrival.net  Tue Oct 14 15:28:41 2003
From: project5 at redrival.net (Andrei)
Date: Tue Oct 14 15:40:48 2003
Subject: [Tutor] Re: A beginners question
In-Reply-To: <000b01c3904a$c8920be0$4f09fea9@J23388.tfil.com>
References: <000b01c3904a$c8920be0$4f09fea9@J23388.tfil.com>
Message-ID: <bmhit5$utg$2@sea.gmane.org>

Trevor G wrote:

> Hello guys,
> I am new to programming and have installed 2.3.2 onto my pc operating under
> Windows 98.
> 1. When I go to run a coded program ie Run Module F5 it takes a long time to
> actually 'run'. Is this a normal feature of Python or should it simply take
> several seconds and then 'run'. The code is very straight forward and is the
> type of exercises seen in any Python textbook for beginners ... chapter 1.
> Am I doing something stupid?
> Hope you can be of assistance.

What IDE are you using? Is your PC very old?

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur 
yvfg, fb gurer'f ab arrq gb PP.



From project5 at redrival.net  Tue Oct 14 15:43:26 2003
From: project5 at redrival.net (Andrei)
Date: Tue Oct 14 15:45:40 2003
Subject: [Tutor] Re: which way do I go?
In-Reply-To: <20031011022655.44589.qmail@web11501.mail.yahoo.com>
References: <20031011022655.44589.qmail@web11501.mail.yahoo.com>
Message-ID: <bmhjoq$2nc$1@sea.gmane.org>

Hi,

>      My name is Michelle.  I am learning languages for the first time in 
> my life and right now I'm kind of on my own with it.  I have a pre-class 
> assignment to complete, which is due by October 18, and I'm am totally 

Well, at least you started reasonably early on it. Have you browsed through the 
python tutorials, Alan Gauld's online book or Thinking Like a Computer Scientist 
in Python? All of these contain enough info to write your program. Here's a 
link: http://www.python.org/topics/learn/.

> lost.  I need to create a function that receives two numbers as 
> arguments.  This function should add up all the integers between the two 
> numbers, for example:
>  
> If I called the function with the numbers 3 and 9, I should get:
>  
>  >>>sumdifference (3, 9)
>  
> my result should be 30
> this comes from adding the numbers 4+5+6+7+8=30

Assuming you don't want to dive into the exotic facilities for functional 
programming, here are some things you should study from one of the tutorials:
- python's code structure (indentation!, variables, assignment)
- mathematical operations (easy)
- functions: def ...():
- the list data type: []
- the for loop: for ... in ...:
- the while loop: while ...:
- the range function: range()

These are fairly simple things which you can probably grasp in a couple of 
hours. If you understand them, you know more than enough (quite literally, you 
don't need all of them) to write your program.
But you will need to take a tutorial and follow it properly in order to 
understand how these things work. You can also try to write out your program on 
paper: pretend you have to write a step-by-step guide for solving your problem 
in such a way that a very stupid problem can use that step-by-step guide. Your 
computer is quite stupid, so that should work out just fine.

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur 
yvfg, fb gurer'f ab arrq gb PP.



From project5 at redrival.net  Tue Oct 14 15:46:10 2003
From: project5 at redrival.net (Andrei)
Date: Tue Oct 14 15:50:33 2003
Subject: [Tutor] Re: editor (was: no subject)
In-Reply-To: <20031012150535.6815.qmail@webmail8.rediffmail.com>
References: <20031012150535.6815.qmail@webmail8.rediffmail.com>
Message-ID: <bmhjtu$2nc$2@sea.gmane.org>

Perumal Sadagopan wrote:

> pl tell me how to  edit a programm

My fav. editor is Spe (http://spe.pycs.net, wxPython based). SciTE 
(http://scintilla.org) is fast and versatile. PythonWin (included in the 
ActiveState python distro at http://activestate.com) is good too, but works only 
on Win. If all else fails, you can use Idle (included in your Python) - some 
people like it a lot, but I think it's ugly and slow.

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur 
yvfg, fb gurer'f ab arrq gb PP.



From sigurd at 12move.de  Tue Oct 14 16:04:30 2003
From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Tue Oct 14 16:05:40 2003
Subject: [Tutor] which way do I go?
In-Reply-To: <20031011022655.44589.qmail@web11501.mail.yahoo.com> (Michelle
	R. Anderson Anderson's message of "Fri,
	10 Oct 2003 19:26:55 -0700 (PDT)")
References: <20031011022655.44589.qmail@web11501.mail.yahoo.com>
Message-ID: <m3smlvsjdq.fsf@hamster.pflaesterer.de>

Michelle R. Anderson Anderson <- m_anderson_0830@yahoo.com wrote:

> am totally lost. I need to create a function that receives two numbers
> as arguments. This function should add up all the integers between the
> two numbers, for example:

> If I called the function with the numbers 3 and 9, I should get:

>>>>sumdifference (3, 9)

> my result should be 30 this comes from adding the numbers 4+5+6+7+8=30

> This program should give me an output of: the sum of integers between
> 3 and 9 is equal to 30

There are a lot of solutions to your problem.  I will show you one of
them.  First you should finf a way to generate a sequence of integers
from your smaller input upto your bigger input.  Let's call the smaller
start and the bigger end.  Python has a function which does nearly what
you need: range(). range(3,9) generates a list from 3 upto 8.

>>> range(3,9)
[3, 4, 5, 6, 7, 8]
>>> 

So start must be incremented by one before you use it with range.  Let's
write a toy example.

>>> def ourrange(start, end):
...     return range(start + 1, end)
... 
>>> ourrange(3,9)
[4, 5, 6, 7, 8]
>>> 

So now we know how to build out list we need a way to sum it up.  I'll
show you here a way how it can be done (there are plenty of others; some
of them even nicer).  If you want to use the elements of a list there is
an easy way in Python to iterate (look up the meaning of it in an
tutorial if you don't know it) over a list:
         for i in lst:
will bind `i' successively to the values of the list elements. So:

>>> for i in [1,2,3,4,5,6]:
...     print i, i*2
... 
1 2
2 4
3 6
4 8
5 10
6 12

`i' got first bound to 1 then to 2, to 3 etc.

That's nearly all you need. You know how to generate a list of integers,
you know how to iterate over the list; so how do we sum integrs up?

To assign a value in Python to a variable you simple write it with a `='

>>> num = 4
>>> print num
4
>>> num = num + 6  
>>> num
10
>>> 

Here first we assigned 4 to num, then we assigned num the value of num +
6.  Don't think like a mathematician about the way assignments are
written; which it means is:
num(newvalue) <- num(oldvalue) + 6

So bringing all that together gives (SPOILER)































>>> def sumupintegers(start, end):
...     result = 0
...     for num in range(start + 1, end):
...             result = result + num
...     return result
... 
>>> sumupintegers(3,9)
30
>>> 




   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


From jeff at ccvcorp.com  Tue Oct 14 16:34:31 2003
From: jeff at ccvcorp.com (Jeff Shannon)
Date: Tue Oct 14 16:31:11 2003
Subject: [Tutor] assigning a variable
References: <3F8C4713.8090704@fish.co.uk>
Message-ID: <3F8C5DD7.1010608@ccvcorp.com>

Gerhard Venter wrote:

> I have the following:
> 
>  >>> import os
>  >>> K=os.system('curl -gs http://babelfish.altavista.com |grep -ic 
> translate')
> 11
>  >>> print K
> 0
> 
> My question is why does K not assume the value of 11 and what can I do 
> to make it do so.

Not all output is return values.  In fact, the two are completely 
separate.  If you call a function from within the Python interpreter, 
and don't assign the return value to a variable, then Python will 
display it for you, and that's probably what's confusing you, but in 
this case they're two different things.

The os.system() function runs a system command, and then returns the 
exit value of that command.  Most system commands have exit values 
that indicate whether or not the command succeeded (and if it failed, 
some indication of why).  In this case, '0' is the exit value of the 
curl command, which indicates that curl ran successfully.

What you *want* to get, the 11, is the output of the command -- the 
shell's stdout.  Just like any *nix filter or redirection, stdout can 
be piped to different programs or what have you.  In this case, the 
stdout of curl is piped to grep, and the stdout from grep comes back 
to Python.  Python simply prints the stdout of os.system() calls to 
the screen.

If you want to be able to capture the stdout of your program, then you 
need to look into using  os.popen() and its related functions. 
os.popen() will return an open file-like object that is connected to 
the stdout of the system command; you can then use that object's 
read()/readlines() method(s) to assign that output to a Python variable.

Hope this helps!

Jeff Shannon
Technician/Programmer
Credit International



From sigurd at 12move.de  Tue Oct 14 16:34:30 2003
From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Tue Oct 14 16:36:27 2003
Subject: [Tutor] assigning a variable
In-Reply-To: <3F8C4713.8090704@fish.co.uk> (Gerhard Venter's message of
	"Tue, 14 Oct 2003 19:57:23 +0100")
References: <3F8C4713.8090704@fish.co.uk>
Message-ID: <m3oewjshze.fsf@hamster.pflaesterer.de>

On 14 Oct 2003, Gerhard Venter <- gventer@fish.co.uk wrote:

>  >>> import os
>  >>> K=os.system('curl -gs http://babelfish.altavista.com |grep -ic
>  >>> translate')
> 11
>  >>> print K
> 0

[...]
> My question is why does K not assume the value of 11 and what can I do
> to make it do so.

>>> help(os.system)
Help on built-in function system:

system(...)
    system(command) -> exit_status
    
    Execute the command (a string) in a subshell.

>>> 

So the return value of os.system is the exit status of grep.  If you
want the 11 as return value you need one of the os.popen* functions.

>>> g = os.popen('grep -c e .gnus.el')
>>> g
<open file 'grep -c e .gnus.el', mode 'r' at 0x9ad860>
>>> g.next()
'279\n'
>>> 



   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


From klappnase at freenet.de  Tue Oct 14 19:16:12 2003
From: klappnase at freenet.de (Michael Lange)
Date: Tue Oct 14 19:14:13 2003
Subject: [Tutor] (no subject)
In-Reply-To: <20031012150535.6815.qmail@webmail8.rediffmail.com>
References: <20031012150535.6815.qmail@webmail8.rediffmail.com>
Message-ID: <20031015011612.405e2571.klappnase@freenet.de>

On 12 Oct 2003 15:05:35 -0000
"Perumal  Sadagopan" <psgopu@rediffmail.com> wrote:

> pl tell me how to  edit a programm

Surely everyone have their own favorite editors, for linux I love Moleskine (http://www.micampe.it/moleskine.html).
It is written in Python and uses Gtk, so maybe it will even run on windows if you install Gtk.

Best regards

Michael

From tim at johnsons-web.com  Tue Oct 14 23:52:00 2003
From: tim at johnsons-web.com (Tim Johnson)
Date: Tue Oct 14 23:48:35 2003
Subject: [Tutor] Re: editor (was: no subject)
In-Reply-To: <bmhjtu$2nc$2@sea.gmane.org>
References: <20031012150535.6815.qmail@webmail8.rediffmail.com>
	<bmhjtu$2nc$2@sea.gmane.org>
Message-ID: <20031015035200.GJ27005@johnsons-web.com>

* Andrei <project5@redrival.net> [031014 12:00]:
> Perumal Sadagopan wrote:
> 
> >pl tell me how to  edit a programm
> 
> My fav. editor is Spe (http://spe.pycs.net, wxPython based). SciTE 
> (http://scintilla.org) is fast and versatile. PythonWin (included in the 
> ActiveState python distro at http://activestate.com) is good too, but works 
> only on Win. If all else fails, you can use Idle (included in your Python) 
> - some people like it a lot, but I think it's ugly and slow.
 
  I use vim. Some people think vim is strange because of its
  modal style of editing. Some people think python is strange
  because of the indent-sensitive control blocks. But it
  works and so does vim.

  Vim + 
    compiled-in python binary + 
        python plugins = 
            one fine IDE.
  tim
  (and pythonwin rocks too!)

-- 
Tim Johnson <tim@johnsons-web.com>
      http://www.alaska-internet-solutions.com

From fredm at smartypantsco.com  Wed Oct 15 00:25:47 2003
From: fredm at smartypantsco.com (Alfred Milgrom)
Date: Wed Oct 15 00:26:33 2003
Subject: [Tutor] Printing Chinese characters?
Message-ID: <5.1.0.14.0.20031015141811.033e11a0@192.168.1.1>

Hi:

I wonder if anyone can help me?

I have a string which I believe is made up of Chinese characters, but I 
cannot display it properly.
The string is
 >>> b = 
'\xba\xda\xcf?\xac\xb3\xa3\xbc\xfb\xb5\xc4\xc6\xe5\xd0?\xac\xba\xda\xc8\xe7\xba?\xf8\xb9\xa5\xa3\xbf'

This prints out as:

 >>> print b
???????????????????????????

which clearly is not Chinese :)

Does anyone know if there is an encoding I could use to make it display 
correctly?
Thanks in anticipation,
Fred Milgrom



From Jaco.Smuts at za.didata.com  Wed Oct 15 03:08:17 2003
From: Jaco.Smuts at za.didata.com (Jaco Smuts (ZA))
Date: Wed Oct 15 03:08:27 2003
Subject: [Tutor] parsing search engine keywords from search referrer log
Message-ID: <C2D8DF00392D6C4FA2F2ABE89252CE4E02A39978@ZABRYSVCL08EX01.af.didata.local>

Hello everyone

I'm about to start work on a little program to assist me with analyzing
my web server logs (in mysql using mod_log_sql).

I want to parse out Search phrases from the referrer fields (where
referrer is a search engine). Does any one have any ideas on how best to
approach this, or some code that already does this ?

thanks in advance
Jaco





This email and all contents are subject to the following disclaimer:

"http://www.didata.com/disclaimer.asp"


From amonroe at columbus.rr.com  Wed Oct 15 09:08:46 2003
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Wed Oct 15 09:08:53 2003
Subject: [Tutor] Forcing file modified date to arbitrary future date?
In-Reply-To: <C2D8DF00392D6C4FA2F2ABE89252CE4E02A39978@ZABRYSVCL08EX01.af.didata.local>
References: <C2D8DF00392D6C4FA2F2ABE89252CE4E02A39978@ZABRYSVCL08EX01.af.didata.local>
Message-ID: <16951867171.20031015090846@columbus.rr.com>

Subject says it all - I need a way to change the last modified date of
a file to any arbitrary future date. I didn't see anything in os.path.
It has a "getmtime" function, but not a matching "setmtime", that I
could see. I don't mind using win32api if there's not a function in
the standard libraries.

Alan


From pythontutor at venix.com  Wed Oct 15 09:52:17 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Wed Oct 15 09:52:28 2003
Subject: [Tutor] Forcing file modified date to arbitrary future date?
In-Reply-To: <16951867171.20031015090846@columbus.rr.com>
References: <C2D8DF00392D6C4FA2F2ABE89252CE4E02A39978@ZABRYSVCL08EX01.af.didata.local>
	<16951867171.20031015090846@columbus.rr.com>
Message-ID: <3F8D5111.2060301@venix.com>

(replying to another email and changing the subject does not change the threading.
It's best to create a new email to start a new thread.)

os.utime should do what you want.

R. Alan Monroe wrote:

> Subject says it all - I need a way to change the last modified date of
> a file to any arbitrary future date. I didn't see anything in os.path.
> It has a "getmtime" function, but not a matching "setmtime", that I
> could see. I don't mind using win32api if there's not a function in
> the standard libraries.
> 
> Alan
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582


From dyoo at hkn.eecs.berkeley.edu  Wed Oct 15 13:46:29 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Oct 15 13:46:34 2003
Subject: [Tutor] Newbie - Outputting List to a File [using shelve / long
	integers]
In-Reply-To: <20031013060546.31737.qmail@web10308.mail.yahoo.com>
Message-ID: <Pine.LNX.4.44.0310151030330.4726-100000@hkn.eecs.berkeley.edu>



On Sun, 12 Oct 2003, Matt Hehman wrote:

>  I was wondering if there was a way to save the list of primes generated
> to an output file so that I could just retrieve it and use it for the
> next number I tested.  I tried the .write command and received the error
> message:
>
> TypeError: argument 1 must be string or read-only character buffer, not
> list


Ah!  Try using the 'shelve' module: it provides persistant storage for
Python objects, and handles some of the low-level details of how to do it
efficiently.

    http://www.python.org/doc/lib/module-shelve.html

In particular, it deals with the details to convert live Python objects
into "character" bytes that can be written to disk.


Let's show a complete interactive session as a demonstration.  In the
first session, I'll generate a shelved object, and in the second, I'll try
retrieving that shelved object:

###
bash-2.05a$ python
Python 2.2 (#1, 11/12/02, 23:31:59)
[GCC Apple cpp-precomp 6.14] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> numbers = [42, 17, 3.1415926]
>>> import shelve
>>> d = shelve.open('storage')
>>> d['numbers'] = numbers
>>> d.close()
###

That's the first session.  Let's see if we can get back our numbers now:



###
bash-2.05a$ python
Python 2.2 (#1, 11/12/02, 23:31:59)
[GCC Apple cpp-precomp 6.14] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import shelve
>>> d = shelve.open('storage')
>>> numbers = d['numbers']
>>> numbers
[42, 17, 3.1415926000000001]
###


Try it out, and feel free to ask more questions about shelve; it's very
nice for saving the state of Python objects.



> Also, I started playing around with increasingly large numbers, is there
> anything I need to do to accomodate that?

If you're using large integers, you should be fine --- Python will
automagically promote an integer into a "long int" if it goes beyond the
range of a normal 32-bit integer.  For example, it's easy to do 2 to the
40'th power:

###
>>> 2**40
1099511627776L
###

The trailing 'L' at the end there tells us that Python is using
long-integers to represent the number, since it's too large to store using
a hardware representation.

Good luck!


From gbrunet at sempersoft.com  Wed Oct 15 15:22:09 2003
From: gbrunet at sempersoft.com (Greg Brunet)
Date: Wed Oct 15 15:22:36 2003
Subject: [Tutor] Re: Re: Testing for punctuation in a string
References: <bmbej9$lug$1@sea.gmane.org>
	<002f01c390e1$3d153ff0$6401a8c0@xp><200310122335.34640.anna@aleax.it>
	<bmdo0m$ol4$2@sea.gmane.org>
	<Pine.A41.4.56.0310131536310.1526002@hermes-22.rz.uni-frankfurt.de>
Message-ID: <bmk6pg$mbf$1@sea.gmane.org>

Hi Michael:

"Michael Janssen" <Janssen@rz.uni-frankfurt.de> wrote in message
news:Pine.A41.4.56.0310131536310.1526002@hermes-22.rz.uni-frankfurt.de...

> When I may take a look at your latest approach (Testing legality by
> definig a pattern the Field Name must match):
>
> > p=re.compile('^[a-zA-Z]\w*$')
> > def fldNameValid(fldName):
> >     return p.match(fldName) != None
>
> Doing things the other way around as in ones own goal-definition
> (supposed I can take the thread's subject as such a thing ;-) might
> be a clever choice in case it becomes clear that it's better than the
> "former way around". Nevertheless it might introduce some unforeseen
> results: Now, your pattern rejects whitespace and commas; Field Names
> starting with numbers or an underscore will be rejected. All this
might
> be perfectly what you needs but it doesn't do the "Testing for
> punctuation in a string" job any longer.
>
> Beside this (and given that the additional restrictions for valid
Field
> Names are what you need), you're solution will do the job, and you
won't
> feel much of a performance impact as long as you don't want to parse a
> serveral kB's commandline ;-)

Thanks for the comments.  You are right that my original request (just
testing for any punctuation in a string) was a simplification of my
complete needs (to make sure that I had valid field names).  Whereas I
originally allowed commas (as field separators), once I start checking
individual fields they are obviously not valid.  After my original
posting, I decided that I really should be checking for all invalid
field names (e.g. starting with a numeral), thus the need to re-work /
improve my objective.  The answer to my original question is still of
interest & value to me, since I am not completely up to speed on the
'correct' or most Pythonic way of doing various string operations.  So
thanks to all who helped out on this,

-- Greg



From hec.villafuerte at telgua.com.gt  Wed Oct 15 18:31:06 2003
From: hec.villafuerte at telgua.com.gt (=?ISO-8859-1?Q?=22H=E9ctor_Villafuerte_D=2E=22?=)
Date: Wed Oct 15 16:30:46 2003
Subject: [Tutor] Interfacing MySQL and Python
Message-ID: <3F8DCAAA.9020308@telgua.com.gt>

Hi all,
I need to start using Python in conjunction with MySQL,
but in
http://sourceforge.net/projects/mysql-python
which leads to
http://dustman.net/andy/python/MySQLdb_obsolete
appears this message:

MySQLdb module 0.3.5
OBSOLETE Python Interface to MySQL

So, what is the easiest way to connect from Python to MySQL?
and, what is the fastest way?
Any link to additional info would be great. Thanks in advance.


From pythontutor at venix.com  Wed Oct 15 17:08:26 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Wed Oct 15 17:08:31 2003
Subject: [Tutor] Interfacing MySQL and Python
In-Reply-To: <3F8DCAAA.9020308@telgua.com.gt>
References: <3F8DCAAA.9020308@telgua.com.gt>
Message-ID: <3F8DB74A.1010800@venix.com>

http://www.python.org/pypi?:action=display&name=MySQL-python&version=0.9.2
Python Packages Index

Don't know where you hit a faulty link, but this is the current version
which works well.

H?ctor Villafuerte D. wrote:
> Hi all,
> I need to start using Python in conjunction with MySQL,
> but in
> http://sourceforge.net/projects/mysql-python
> which leads to
> http://dustman.net/andy/python/MySQLdb_obsolete
> appears this message:
> 
> MySQLdb module 0.3.5
> OBSOLETE Python Interface to MySQL
> 
> So, what is the easiest way to connect from Python to MySQL?
> and, what is the fastest way?
> Any link to additional info would be great. Thanks in advance.
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582


From dyoo at hkn.eecs.berkeley.edu  Wed Oct 15 17:40:41 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Oct 15 17:41:09 2003
Subject: [Tutor] parsing search engine keywords from search referrer log
In-Reply-To: <C2D8DF00392D6C4FA2F2ABE89252CE4E02A39978@ZABRYSVCL08EX01.af.didata.local>
Message-ID: <Pine.LNX.4.44.0310151432350.25688-100000@hkn.eecs.berkeley.edu>



On Wed, 15 Oct 2003, Jaco Smuts (ZA) wrote:

> I'm about to start work on a little program to assist me with analyzing
> my web server logs (in mysql using mod_log_sql).
>
> I want to parse out Search phrases from the referrer fields (where
> referrer is a search engine). Does any one have any ideas on how best to
> approach this, or some code that already does this ?

Hi Jaco,

Do you have examples of some of what these referrer fields look like?

I did a quick Google search: it does look like the Python Community Server
Project

    http://pycs.sourceforge.net/

is writing some interesting software.  For example, they have a
referrer-log analyzer:

http://cvs.sourceforge.net/viewcvs.py/*checkout*/pycs/pycs/analyse_logs.py?content-type=text%2Fplain&rev=1.9

Their approach appears to be use regular expressions to parse the request
message for their logs.  I'm not sure how easy it would be to adopt their
code exactly, but the idea seems right.

Are you familiar with regular expressions?  If not, there's an
introduction to them here:

    http://www.amk.ca/python/howto/regex/

Please feel free to ask questions about them on Tutor; we'll be happy to
help.  Good luck to you!


From alan.gauld at blueyonder.co.uk  Wed Oct 15 17:41:53 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Wed Oct 15 17:42:42 2003
Subject: [Tutor] which way do I go?
References: <20031011022655.44589.qmail@web11501.mail.yahoo.com>
Message-ID: <004101c39365$26345650$6401a8c0@xp>

> >>>sumdifference (3, 9)
>
> my result should be 30
> this comes from adding the numbers 4+5+6+7+8=30

Look at how to define functions.

You need a function called sumdifference that takes two arguments,
therefore your definition has to have two parameters, lets call
them x and y.

You want to add all the values from x+1 to y-1.

Look at the range(x,y) function in Python, it generates numbers
in the range x to y-1 which is nearly what you want.

Also to add the numbers together you need to repeat the addition for
each numvber.

Look at the for command in Python.

In my tutor the relevant topics are:

Simple sequences
Looping
Functions and Modules

I hope thats enough of a starter along with the other comments.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


From alan.gauld at blueyonder.co.uk  Wed Oct 15 17:48:22 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Wed Oct 15 17:49:10 2003
Subject: [Tutor] Re: editor (was: no subject)
References: <20031012150535.6815.qmail@webmail8.rediffmail.com><bmhjtu$2nc$2@sea.gmane.org>
	<20031015035200.GJ27005@johnsons-web.com>
Message-ID: <005a01c39366$0e3a39b0$6401a8c0@xp>

> Perumal Sadagopan wrote:
> 
 > >pl tell me how to  edit a programm

Open any text editor(even notepad if you like!).
Type Python commands into it.
Save the file giving it a name that ends in .py
Make sure it is saved as plain ASCII text not RTF or 
MS Word format etc.

The new file is a python program that you can run 
by double clicking in explorer(assuming you use Windows)

or by typing

python file.py

where file.py should be whatever you called your program.

If its a short program you may find it closes too quickly
to see it, in which case add the line

raw_input("Hit return to quit...")

as the last line.

HTH,

Alan G.

From dyoo at hkn.eecs.berkeley.edu  Wed Oct 15 17:52:16 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Oct 15 17:52:34 2003
Subject: [Tutor] Printing Chinese characters?
In-Reply-To: <5.1.0.14.0.20031015141811.033e11a0@192.168.1.1>
Message-ID: <Pine.LNX.4.44.0310151440550.25688-100000@hkn.eecs.berkeley.edu>



On Wed, 15 Oct 2003, Alfred Milgrom wrote:

> I have a string which I believe is made up of Chinese characters, but I
> cannot display it properly.
> The string is
>  >>> b =3D
> '\xba\xda\xcf?\xac\xb3\xa3\xbc\xfb\xb5\xc4\xc6\xe5\xd0?\xac\xba\xda\xc8\x=
e7\xba?\xf8\xb9\xa5\xa3\xbf'
>
> This prints out as:
>
>  >>> print b
> =BA=DA=CF?=AC=B3=A3=BC=FB=B5=C4=C6=E5=D0?=AC=BA=DA=C8=E7=BA?=F8=B9=A5=A3=
=BF
>
> which clearly is not Chinese :)

Hi Alfred,

It all looks Greek to me.  *grin*


When you say "display", do you mean display in a Tkinter window?  Most
terminal windows don't natively support extended character sets, so you
might need to use a GUI to properly see those characters.

I'm guessing that you might be doing Unicode?  If so, maybe use can use
your web browser to help?  I wrote a small post a while back:

    http://mail.python.org/pipermail/tutor/2002-December/019087.html

that generates the Korean unicode character for the letter "Yoo".  *wink*



But that character string you've posted:

###
s =3D ('\xba\xda\xcf?\xac\xb3\xa3\xbc\xfb\xb5\xc4\xc6' +
     '\xe5\xd0?\xac\xba\xda\xc8\xe7\xba?\xf8\xb9\xa5\xa3\xbf')
###

will need to be first decoded from whatever byte encoding it is in now
into Unicode before any display approach will work.


Let's try something:

###
>>> s =3D ('\xba\xda\xcf?\xac\xb3\xa3\xbc\xfb\xb5\xc4\xc6' +
=2E..      '\xe5\xd0?\xac\xba\xda\xc8\xe7\xba?\xf8\xb9\xa5\xa3\xbf')
>>> s.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
UnicodeError: UTF-8 decoding error: unexpected code byte
>>> s.decode('utf-16')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
UnicodeError: UTF-16 decoding error: truncated data
###

Hmmm... no luck there.  The 'encodings' page:

    http://www.python.org/doc/lib/node126.html

shows the native encodings that Python supports out of the box.  I'm not
quite sure if we can guess the byte encoding, although the tests above
immediately discount UTF-8 and UTF-16.  Do you have more information on
the byte encoding is being used for your string 's'?


Good luck to you!


From dyoo at hkn.eecs.berkeley.edu  Wed Oct 15 18:04:18 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Oct 15 18:04:23 2003
Subject: [Tutor] which way do I go?
In-Reply-To: <004101c39365$26345650$6401a8c0@xp>
Message-ID: <Pine.LNX.4.44.0310151452510.25688-100000@hkn.eecs.berkeley.edu>



On Wed, 15 Oct 2003, Alan Gauld wrote:

> > >>>sumdifference (3, 9)
> >
> > my result should be 30
> > this comes from adding the numbers 4+5+6+7+8=30
>
> Look at how to define functions.


Time for more contradictory suggestions.  *grin*

Simplifed problem: Can you write a program that sums the numbers from 0 to
9?  How about a program that sums the numbers from 0 to 3?

More generally: Can you write a function that accepts an input 'n' and
sums the numbers from 0 to n?

This problem should be simpler for you, since the left endpoint is always
at zero.  (It should also remind you of a problem you really should have
seen in algebra called "Gauss's sum".)

If you have a function that solves the simpler zero-based problem, you can
get the sum of an arbitrary interval in a very cute way.

Good luck to you.


From hec.villafuerte at telgua.com.gt  Wed Oct 15 20:31:49 2003
From: hec.villafuerte at telgua.com.gt (=?ISO-8859-1?Q?=22H=E9ctor_Villafuerte_D=2E=22?=)
Date: Wed Oct 15 18:31:24 2003
Subject: [Tutor] site-packages folder
Message-ID: <3F8DE6F5.3040805@telgua.com.gt>

Hi,
I downloaded dbfpy.tgz (for managing .DBF tables) and then I
extracted it to:

C:\Python23\Lib\site-packages\dbfpy

but when I try to import the module, it fails:

 >>> from dbf import *

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in -toplevel-
    from dbf import *
ImportError: No module named dbf
 >>>

Obviously I need to do something to register this module (not just
extract it to C:\Python23\Lib\site-packages).
Thanks in advance.


From Jaco.Smuts at za.didata.com  Wed Oct 15 18:36:53 2003
From: Jaco.Smuts at za.didata.com (Jaco Smuts (ZA))
Date: Wed Oct 15 18:42:52 2003
Subject: [Tutor] parsing search engine keywords from search referrer log
Message-ID: <C2D8DF00392D6C4FA2F2ABE89252CE4E02A39982@ZABRYSVCL08EX01.af.didata.local>

Hello Danny

Thank you for your response. 

Because my logs are in MySQL I suspect regular expressions might be an
overkill. This is a part time venture so my progress is a series of
sporadic spurts of progress vs. none.

I have played with urlparse.urlparse and cgi.parseqs~~~. All I need to
do still is split the results into words (I want to analyse search
phrases and keywords). And build some kind of engine that can recognize
different search engines and apply specific rules for each. Any
suggestions on this will also be welcome. I'm hoping to get away with a
simple identification method linked to an (generic, if possible)
algorithm.

I will play a bit more and post my code. I'm sure I can greatly benefit
from watching the guru's correct my efforts :-)

thank you
Jaco Smuts

~~~ It seems a bit silly that I need to use to libraries to work with
url's and querstrings.

ps. lastly allow me to be facetious:
Some people, when confronted with a [programming] problem, think,
"I know, I'll use regular expressions."  Now they have two problems.
                        -- Jamie Zawinski


-----Original Message-----
From: Danny Yoo [mailto:dyoo@hkn.eecs.berkeley.edu]
Sent: Wednesday, October 15, 2003 11:41 PM
To: Jaco Smuts (ZA)
Cc: tutor@python.org
Subject: Re: [Tutor] parsing search engine keywords from search referrer
log




On Wed, 15 Oct 2003, Jaco Smuts (ZA) wrote:

> I'm about to start work on a little program to assist me with
analyzing
> my web server logs (in mysql using mod_log_sql).
>
> I want to parse out Search phrases from the referrer fields (where
> referrer is a search engine). Does any one have any ideas on how best
to
> approach this, or some code that already does this ?

Hi Jaco,

Do you have examples of some of what these referrer fields look like?

I did a quick Google search: it does look like the Python Community
Server
Project

    http://pycs.sourceforge.net/

is writing some interesting software.  For example, they have a
referrer-log analyzer:

http://cvs.sourceforge.net/viewcvs.py/*checkout*/pycs/pycs/analyse_logs.
py?content-type=text%2Fplain&rev=1.9

Their approach appears to be use regular expressions to parse the
request
message for their logs.  I'm not sure how easy it would be to adopt
their
code exactly, but the idea seems right.

Are you familiar with regular expressions?  If not, there's an
introduction to them here:

    http://www.amk.ca/python/howto/regex/

Please feel free to ask questions about them on Tutor; we'll be happy to
help.  Good luck to you!




This email and all contents are subject to the following disclaimer:

"http://www.didata.com/disclaimer.asp"


From learning.python at dbmail.dk  Wed Oct 15 21:22:35 2003
From: learning.python at dbmail.dk (Ole Jensen)
Date: Wed Oct 15 21:22:53 2003
Subject: [Tutor] Databases
Message-ID: <001601c39383$fae02be0$9e4c73d5@BAERBAR>

Hi everybody
I'm currently experimenting on creating some python generated web pages, and was wondering what databases are used for... (Sorry if it is abit to vague/general)

Basically what I have been thinking of doing (without using a database) is having a few articles as text documents (with html code i.e. <p>'s and <a>'s) and importing them into python and displaying the text into an entire page (with tables and pics et al).

Without any prior experince in web programming I was just curious, if this is something that is (normally) done with databases,  or how they are used (in simple terms *grin*) in practise.

Also would you recommend me to try and play around with some variant of a database or to just relax and get to understand basic CGI/web programming better before starting with it now? I realize you don't know my current level but as a general pointer, is it best saved for later?

I have been trying to google for it but I didn't really find anything useful... 

Regards Ole Jensen
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20031016/abb7358f/attachment.html
From fredm at smartypantsco.com  Wed Oct 15 23:54:54 2003
From: fredm at smartypantsco.com (Alfred Milgrom)
Date: Wed Oct 15 23:56:29 2003
Subject: [Tutor] Printing Chinese characters?
In-Reply-To: <Pine.LNX.4.44.0310151440550.25688-100000@hkn.eecs.berkeley .edu>
References: <5.1.0.14.0.20031015141811.033e11a0@192.168.1.1>
Message-ID: <5.1.0.14.0.20031016134659.03a0e6d0@192.168.1.1>

Hi Danny:

Thanks for your reply.
Given that this is a Chinese string, I think it might be a BIG-5 encoding, 
but I am unable to find the proper encoding files.

In my distribution of Python, there is an encodings directory under 
Python22/Lib, and a file called aliases.py. As I understand it, this module 
is used by the encodings package search function to map encodings names to 
module names.

There is an interesting comment under CJK encodings (Chinese, Japanese, 
Korean) as follows:
     # The codecs for these encodings are not distributed with the
     # Python core, but are included here for reference, since the
     # locale module relies on having these aliases available.

Do you (or anyone else) know where I can get the Chinese encodings, 
including BIG-5?

Thanks in advance,
Fred Milgrom


At 02:52 PM 15/10/03 -0700, Danny Yoo wrote:

><snip>
>But that character string you've posted:
>
>###
>s = ('\xba\xda\xcf?\xac\xb3\xa3\xbc\xfb\xb5\xc4\xc6' +
>      '\xe5\xd0?\xac\xba\xda\xc8\xe7\xba?\xf8\xb9\xa5\xa3\xbf')
>###
>will need to be first decoded from whatever byte encoding it is in now
>into Unicode before any display approach will work.
>
><snip> Do you have more information on
>the byte encoding is being used for your string 's'?
>
>Good luck to you!



From neal at bcn.boulder.co.us  Thu Oct 16 00:44:28 2003
From: neal at bcn.boulder.co.us (Neal McBurnett)
Date: Thu Oct 16 00:44:49 2003
Subject: [Tutor] Printing Chinese characters?
In-Reply-To: <5.1.0.14.0.20031016134659.03a0e6d0@192.168.1.1>
References: <5.1.0.14.0.20031015141811.033e11a0@192.168.1.1>
	<5.1.0.14.0.20031016134659.03a0e6d0@192.168.1.1>
Message-ID: <20031016044428.GR1348@feynman>

Well, I think the idea that it is at least similar to big5 is right.
But it may have a Japanese hiragana character also.

But to make that work I had to drop the '?' characters, as well as the
\xc8 (trial and error....)

I used linux and the free, quirky but very handy "recode" program to
do the recoding.  I inserted a few newlines to help keep my place....

original string:
 '\xba\xda\xcf?\xac\xb3\xa3\xbc\xfb\xb5\xc4\xc6\xe5\xd0?\xac\xba\xda\xc8\xe7\xba?\xf8\xb9\xa5\xa3\xbf'

my script:
$ python2 -c "print '\xba\xda\xcf\xac\xb3\xa3\xbc\xfb\xb5\xc4\xc6\xe5\xd0\xac\xba\xda\n\xe7\xba\xf8\xb9\xa5\xa3'" |
 recode big5..dump

Output, in Unicode UCS2 form:

UCS2   Mne   Description

7AAA      
6D09      
90FD      
7357      
8154      
3081   me    hiragana letter me
8867      
7AAA      
000A   LF    line feed (lf)
8765      
7E97      
5974      
000A   LF    line feed (lf)

Those characters can be looked up via the Unihan.txt file at
unicode.org, yielding the name of each character, and in many common
cases also pronunciation and a definition:

$ for i in 7AAA 6D09 90FD 7357 8154 3081 8867 7AAA 000A 8765 7E97 5974 000A; do
  fgrep $i Unihan.txt | grep kDefinition; done

U+7AAA kDefinition hollow; pit; depression; swamp
U+90FD kDefinition metropolis, capital; all, the whole; elegant,
refined
U+7357 kDefinition unruly, wild, violent, lawless
U+8154 kDefinition chest cavity; hollow in body
U+7AAA kDefinition hollow; pit; depression; swamp
U+8765 kDefinition a fly which is used similarly to cantharides
U+5974 kDefinition slave, servant

The other characters weren't in that "dictionary".

I don't know what the deal is with the characters I had to drop out,
so it may be some other character set which is related to big5.

But I think that  for someone who knows no Chinese, using
free tools and databases....

Cheers,

Neal McBurnett                 http://bcn.boulder.co.us/~neal/
Signed and/or sealed mail encouraged.  GPG/PGP Keyid: 2C9EBA60


On Thu, Oct 16, 2003 at 01:54:54PM +1000, Alfred Milgrom wrote:
> Hi Danny:
> 
> Thanks for your reply.
> Given that this is a Chinese string, I think it might be a BIG-5 encoding, 
> but I am unable to find the proper encoding files.
> 
> In my distribution of Python, there is an encodings directory under 
> Python22/Lib, and a file called aliases.py. As I understand it, this module 
> is used by the encodings package search function to map encodings names to 
> module names.
> 
> There is an interesting comment under CJK encodings (Chinese, Japanese, 
> Korean) as follows:
>     # The codecs for these encodings are not distributed with the
>     # Python core, but are included here for reference, since the
>     # locale module relies on having these aliases available.
> 
> Do you (or anyone else) know where I can get the Chinese encodings, 
> including BIG-5?
> 
> Thanks in advance,
> Fred Milgrom
> 
> 
> At 02:52 PM 15/10/03 -0700, Danny Yoo wrote:
> 
> ><snip>
> >But that character string you've posted:
> >
> >###
> >s = ('\xba\xda\xcf?\xac\xb3\xa3\xbc\xfb\xb5\xc4\xc6' +
> >     '\xe5\xd0?\xac\xba\xda\xc8\xe7\xba?\xf8\xb9\xa5\xa3\xbf')
> >###
> >will need to be first decoded from whatever byte encoding it is in now
> >into Unicode before any display approach will work.
> >
> ><snip> Do you have more information on
> >the byte encoding is being used for your string 's'?
> >
> >Good luck to you!
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

From neal at bcn.boulder.co.us  Thu Oct 16 00:54:41 2003
From: neal at bcn.boulder.co.us (Neal McBurnett)
Date: Thu Oct 16 00:54:54 2003
Subject: [Tutor] Printing Chinese characters?
In-Reply-To: <20031016044428.GR1348@feynman>
References: <5.1.0.14.0.20031015141811.033e11a0@192.168.1.1>
	<5.1.0.14.0.20031016134659.03a0e6d0@192.168.1.1>
	<20031016044428.GR1348@feynman>
Message-ID: <20031016045441.GS1348@feynman>

Ahh - and the final step - that would yield this utf-8 encoding (of
the original string minus the troublesome characters) rendered as a
python string:

print '\xe7\xaa\xaa\xe6\xb4\x89\xe9\x83\xbd\xe7\x8d\x97\xe8\x85\x94\xe3\x82\x81\xe8\xa1\xa7\xe7\xaa\xaa\xe8\x9d\xa5\xe7\xba\x97\xe5\xa5\xb4\x0a'

which prints fine on my utf-8-enabled xterm, as described so
wonderfuly at http://www.cl.cam.ac.uk/~mgk25/unicode.html by Markus
Kuhn.  Though a few characters aren't in the free font I got with
X11/Redhat 7.3.

Of course I may be way off-base here - just playing around with it.

-Neal

On Wed, Oct 15, 2003 at 10:44:28PM -0600, Neal McBurnett wrote:
> Well, I think the idea that it is at least similar to big5 is right.
> But it may have a Japanese hiragana character also.
> 
> But to make that work I had to drop the '?' characters, as well as the
> \xc8 (trial and error....)
> 
> I used linux and the free, quirky but very handy "recode" program to
> do the recoding.  I inserted a few newlines to help keep my place....
> 
> original string:
>  '\xba\xda\xcf?\xac\xb3\xa3\xbc\xfb\xb5\xc4\xc6\xe5\xd0?\xac\xba\xda\xc8\xe7\xba?\xf8\xb9\xa5\xa3\xbf'
> 
> my script:
> $ python2 -c "print '\xba\xda\xcf\xac\xb3\xa3\xbc\xfb\xb5\xc4\xc6\xe5\xd0\xac\xba\xda\n\xe7\xba\xf8\xb9\xa5\xa3'" |
>  recode big5..dump
> 
> Output, in Unicode UCS2 form:
> 
> UCS2   Mne   Description
> 
> 7AAA      
> 6D09      
> 90FD      
> 7357      
> 8154      
> 3081   me    hiragana letter me
> 8867      
> 7AAA      
> 000A   LF    line feed (lf)
> 8765      
> 7E97      
> 5974      
> 000A   LF    line feed (lf)
> 
> Those characters can be looked up via the Unihan.txt file at
> unicode.org, yielding the name of each character, and in many common
> cases also pronunciation and a definition:
> 
> $ for i in 7AAA 6D09 90FD 7357 8154 3081 8867 7AAA 000A 8765 7E97 5974 000A; do
>   fgrep $i Unihan.txt | grep kDefinition; done
> 
> U+7AAA kDefinition hollow; pit; depression; swamp
> U+90FD kDefinition metropolis, capital; all, the whole; elegant,
> refined
> U+7357 kDefinition unruly, wild, violent, lawless
> U+8154 kDefinition chest cavity; hollow in body
> U+7AAA kDefinition hollow; pit; depression; swamp
> U+8765 kDefinition a fly which is used similarly to cantharides
> U+5974 kDefinition slave, servant
> 
> The other characters weren't in that "dictionary".
> 
> I don't know what the deal is with the characters I had to drop out,
> so it may be some other character set which is related to big5.
> 
> But I think that  for someone who knows no Chinese, using
> free tools and databases....
> 
> Cheers,
> 
> Neal McBurnett                 http://bcn.boulder.co.us/~neal/
> Signed and/or sealed mail encouraged.  GPG/PGP Keyid: 2C9EBA60
> 
> 
> On Thu, Oct 16, 2003 at 01:54:54PM +1000, Alfred Milgrom wrote:
> > Hi Danny:
> > 
> > Thanks for your reply.
> > Given that this is a Chinese string, I think it might be a BIG-5 encoding, 
> > but I am unable to find the proper encoding files.
> > 
> > In my distribution of Python, there is an encodings directory under 
> > Python22/Lib, and a file called aliases.py. As I understand it, this module 
> > is used by the encodings package search function to map encodings names to 
> > module names.
> > 
> > There is an interesting comment under CJK encodings (Chinese, Japanese, 
> > Korean) as follows:
> >     # The codecs for these encodings are not distributed with the
> >     # Python core, but are included here for reference, since the
> >     # locale module relies on having these aliases available.
> > 
> > Do you (or anyone else) know where I can get the Chinese encodings, 
> > including BIG-5?
> > 
> > Thanks in advance,
> > Fred Milgrom
> > 
> > 
> > At 02:52 PM 15/10/03 -0700, Danny Yoo wrote:
> > 
> > ><snip>
> > >But that character string you've posted:
> > >
> > >###
> > >s = ('\xba\xda\xcf?\xac\xb3\xa3\xbc\xfb\xb5\xc4\xc6' +
> > >     '\xe5\xd0?\xac\xba\xda\xc8\xe7\xba?\xf8\xb9\xa5\xa3\xbf')
> > >###
> > >will need to be first decoded from whatever byte encoding it is in now
> > >into Unicode before any display approach will work.
> > >
> > ><snip> Do you have more information on
> > >the byte encoding is being used for your string 's'?
> > >
> > >Good luck to you!
> > 
> > 
> > 
> > _______________________________________________
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

From dyoo at hkn.eecs.berkeley.edu  Thu Oct 16 02:47:31 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Oct 16 02:47:50 2003
Subject: [Tutor] Printing Chinese characters?
In-Reply-To: <20031016045441.GS1348@feynman>
Message-ID: <Pine.LNX.4.44.0310152326380.27035-100000@hkn.eecs.berkeley.edu>



On Wed, 15 Oct 2003, Neal McBurnett wrote:

> Ahh - and the final step - that would yield this utf-8 encoding (of the
> original string minus the troublesome characters) rendered as a python
> string:
>
> print
> '\xe7\xaa\xaa\xe6\xb4\x89\xe9\x83\xbd\xe7\x8d\x97\xe8\x85\x94\xe3
> \x82\x81\xe8\xa1\xa7\xe7\xaa\xaa\xe8\x9d\xa5\xe7\xba\x97\xe5\xa5
> \xb4\x0a'


Ah, then it is UTF-8 then?  Oh, I must have introduced some weird
characters when I copied and pasted.  You're right!  Oh, cool!

###
>>> s = ('\xe7\xaa\xaa\xe6\xb4\x89\xe9\x83\xbd\xe7\x8d\x97\xe8'
...    + '\x85\x94\xe3\x82\x81\xe8\xa1\xa7\xe7\xaa\xaa\xe8\x9d'
...    + '\xa5\xe7\xba\x97\xe5\xa5\xb4').decode('utf8')
>>> s
u'\u7aaa\u6d09\u90fd\u7357\u8154\u3081\u8867\u7aaa\u8765\u7e97\u5974'
###

There, now it's decoding properly.  Yes, it matches what Neal decoded:


> > U+7AAA kDefinition hollow; pit; depression; swamp
> > U+90FD kDefinition metropolis, capital; all, the whole; elegant,
> > refined
> > U+7357 kDefinition unruly, wild, violent, lawless
> > U+8154 kDefinition chest cavity; hollow in body
> > U+7AAA kDefinition hollow; pit; depression; swamp
> > U+8765 kDefinition a fly which is used similarly to cantharides
> > U+5974 kDefinition slave, servant


Wow, that sounds rather... um... grim.  *grin*


Most web browsers have native support for utf8-encoded files, so, in a
pinch, you might be able to see the message this way:

###
msg = ('\xe7\xaa\xaa\xe6\xb4\x89\xe9\x83\xbd\xe7\x8d\x97\xe8'
       + '\x85\x94\xe3\x82\x81\xe8\xa1\xa7\xe7\xaa\xaa\xe8\x9d'
       + '\xa5\xe7\xba\x97\xe5\xa5\xb4')
print """<!doctype HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<p>%s</p>
</body>
</html>""" % msg
###

Redirect the result of this to an HTML file, and then try browsing it.

If you're still having trouble seeing it, visit:

    http://hkn.eecs.berkeley.edu/~dyoo/weird_chinese_msg.pdf

I've printed it out as a PDF as a stopgap measure if you're really
desperate to see the Chinese characters.  *grin*


But does anyone know if ReportLab's happy with UTF-8 characters?



> > > There is an interesting comment under CJK encodings (Chinese, Japanese,
> > > Korean) as follows:
> > >     # The codecs for these encodings are not distributed with the
> > >     # Python core, but are included here for reference, since the
> > >     # locale module relies on having these aliases available.
> > >
> > > Do you (or anyone else) know where I can get the Chinese encodings,
> > > including BIG-5?


Here you go:

    http://cjkpython.i18n.org/

It looks like we won't need them this time, but if we run across BIG5
encoded files, we'll know what to do to transform them to utf8 now.


Good luck!


From sabineq at wisemail.weizmann.ac.il  Thu Oct 16 08:15:11 2003
From: sabineq at wisemail.weizmann.ac.il (Sabine Ruth Quadt)
Date: Thu Oct 16 08:15:20 2003
Subject: [Tutor] Configuring for Tk
Message-ID: <sf8ea7f3.079@wisemail.weizmann.ac.il>

Hallo,

I have a problem configuring Python for Tk.

I changed the file Modules/Setup and uncommented  the lines for tkinter
and edited the lines for my TcL/Tk libraries and headers.
I execute make Makefile.
When I then run mke, I get a lot of error messages about undefined
references like the folowing:

/sabine/SOFTWARE/python/Python-2.3.2/Modules/tkappinit.c:74: undefined
reference to `Tk_MainWindow'


Can someone help me?

Thanks

Sabine 

From amk at amk.ca  Thu Oct 16 10:42:18 2003
From: amk at amk.ca (amk@amk.ca)
Date: Thu Oct 16 10:42:24 2003
Subject: [Tutor] site-packages folder
In-Reply-To: <3F8DE6F5.3040805@telgua.com.gt>
References: <3F8DE6F5.3040805@telgua.com.gt>
Message-ID: <20031016144218.GB4406@rogue.amk.ca>

On Wed, Oct 15, 2003 at 04:31:49PM -0800, "H?ctor Villafuerte D." wrote:
> C:\Python23\Lib\site-packages\dbfpy

Was what you unzipped a source or a built distribution?  If it's the source
distribution, you shouldn't have unpacked it in site-packages; instead you
would have unpacked it somewhere else and run the included setup.py script
to install the code in site-packages.  The package should have had a README
explaining what to do.

--amk

From hec.villafuerte at telgua.com.gt  Thu Oct 16 12:54:17 2003
From: hec.villafuerte at telgua.com.gt (=?ISO-8859-1?Q?=22H=E9ctor_Villafuerte_D=2E=22?=)
Date: Thu Oct 16 10:53:50 2003
Subject: [Tutor] Interfacing MySQL and Python
In-Reply-To: <04875CB4331F0240A0AD66F970978651011375A0@paul>
References: <04875CB4331F0240A0AD66F970978651011375A0@paul>
Message-ID: <3F8ECD39.6080302@telgua.com.gt>

Jason Tesser wrote:

>What versions of Mysql and Python are you running?
>
>  
>
Thank you all! I downloaded MySQLdb 0.92 and it is working just great.
I got mislead with the "obsolete" message in the project page.



From carroll at tjc.com  Thu Oct 16 18:07:48 2003
From: carroll at tjc.com (Terry Carroll)
Date: Thu Oct 16 18:07:53 2003
Subject: [Tutor] Printing Chinese characters?
In-Reply-To: <5.1.0.14.0.20031016134659.03a0e6d0@192.168.1.1>
Message-ID: <Pine.LNX.4.44.0310161502530.31258-100000@violet.rahul.net>

On Thu, 16 Oct 2003, Alfred Milgrom wrote:

> Do you (or anyone else) know where I can get the Chinese encodings, 
> including BIG-5?

Alfred --

The Unicode orginazation has a file with the mappings of major Asian 
encodings to Unicode at

  http://www.unicode.org/Public/UNIDATA/Unihan.txt

It's 25 meg.  The Big-5 encodings are associated with the tag "kBigFive".

I have a Python module, still in rough form, for looking up entries in the 
Unihan.txt file.  I was planning on releasing in when I have it in a 
little bit better state, but I'd be happy to share a copy with you now, as 
long as you realize it's still pretty rough.

-- 
Terry Carroll
Santa Clara, CA
carroll@tjc.com 



From missive at hotmail.com  Thu Oct 16 18:36:40 2003
From: missive at hotmail.com (Lee Harr)
Date: Thu Oct 16 18:36:44 2003
Subject: [Tutor] Re: Databases
Message-ID: <BAY2-F1254waDpktwrW00007109@hotmail.com>

>I'm currently experimenting on creating some python generated web pages, =
>and was wondering what databases are used for... (Sorry if it is abit to =
>vague/general)
>

They are used to store data.  If your site is very simple, you could just
use flat files (text files) or if it gets more complex you would want to
use a relational database (postgresql is a very good free one)


>Basically what I have been thinking of doing (without using a database) =
>is having a few articles as text documents (with html code i.e. <p>'s =
>and <a>'s) and importing them into python and displaying the text into =
>an entire page (with tables and pics et al).
>
>Without any prior experince in web programming I was just curious, if =
>this is something that is (normally) done with databases,  or how they =
>are used (in simple terms *grin*) in practise.
>

Depends on how many articles you have, how many people will be working
on them / updating them / adding new articles.

Look at a site like http://slashdot.org/ for a great example of articles 
(and
comments on those articles) stored in a database, then presented to users
through a web interface.


>Also would you recommend me to try and play around with some variant of =
>a database or to just relax and get to understand basic CGI/web =
>programming better before starting with it now? I realize you don't know =
>my current level but as a general pointer, is it best saved for later?
>

If you like python, you may want to try Zope (the 800-pound gorilla of 
python
web programming) or one of the lighter-weight web frameworks. Web
programming is interesting. Web programming backed up by a database
is even more interesting.

_________________________________________________________________
The new MSN 8: smart spam protection and 2 months FREE*  
http://join.msn.com/?page=features/junkmail


From dyoo at hkn.eecs.berkeley.edu  Thu Oct 16 20:29:39 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Oct 16 20:29:48 2003
Subject: [Tutor] Re: Databases  [Phil Greenspun's Panda book]
In-Reply-To: <BAY2-F1254waDpktwrW00007109@hotmail.com>
Message-ID: <Pine.LNX.4.44.0310161724090.30736-100000@hkn.eecs.berkeley.edu>



On Thu, 16 Oct 2003, Lee Harr wrote:

> >I'm currently experimenting on creating some python generated web
> >pages, = and was wondering what databases are used for... (Sorry if it
> >is abit to = vague/general)
>
> They are used to store data.  If your site is very simple, you could
> just use flat files (text files) or if it gets more complex you would
> want to use a relational database (postgresql is a very good free one)

[some text cut]

> Look at a site like http://slashdot.org/ for a great example of articles
> (and comments on those articles) stored in a database, then presented to
> users through a web interface.


There's another good online book by Phil Greenspun that talks about how to
develop a database-backed web site:

    http://philip.greenspun.com/panda/
    http://philip.greenspun.com/panda/databases-intro

The advice he gives applies equally well to any computer language, and,
more importantly, it's an entertaining read.  *grin*


Good luck to you!


From carroll at tjc.com  Thu Oct 16 22:54:05 2003
From: carroll at tjc.com (Terry Carroll)
Date: Thu Oct 16 22:54:09 2003
Subject: [Tutor] unichr() question
In-Reply-To: <29E16390A38FD7118A03000BCD0F3F6501223811@mail.spiglobe.com>
Message-ID: <Pine.LNX.4.44.0310161944590.31258-100000@violet.rahul.net>

On Tue, 14 Oct 2003, Ezequiel, Justin wrote:

> PythonWin 2.2.2
> Windows XP
> 
> >>> long('1D4AA', 16)
> 119978L
> >>> unichr(long('1D4AA', 16))
> Traceback (most recent call last):
>   File "<interactive input>", line 1, in ?
> ValueError: unichr() arg not in range(0x10000) (narrow Python build)
> >>> x = eval("u'\\U000%s'" % '1D4AA')
> >>> x
> u'\U0001d4aa'
> >>> for c in x:
> ... 	print ord(c)
> ... 
> 55349
> 56490
> >>> unichr(55349) + unichr(56490)
> u'\U0001d4aa'
> >>> 
> 
> How do I convert strings such as '1D4AA' to unicode without using eval()?
Justin, I see you haven't gotten any responses on this yet.  I don't know 
an answer, but I ran into something similar on some of the Unihan 
characters.  Fortunately for me, I found I could just ignore any that were 
over x'FFFF'; it doesn't sound like you can.

I looked into it for a while and determined that it depends on how your 
Python was built.  If it was a "narrow build", it supports Unicode 
characters only up to x'FFFF'; if a "wide build", it supports Unicode 
x'10000" and higher, as well.  As far as I can tell, it depends on whether 
the installer specified "--enable-unicode=ucs4" to get the wide build.

I'm a Windows user, too, and dependent on the Activestate build, which is
narrow.  In the end, I decided to just avoid the higher Unicode values,
which didn't matter for me.  If you have a way of getting a "wide build" I
suspect this would do the trick for you.

There's more information in PEP 261, 
http://www.python.org/peps/pep-0261.html : I think this is the last word 
on it.

Hopefully, some others more informed on Python internals and Unicode can 
give more information on this, but I hope this helps somewhat.


-- 
Terry Carroll
Santa Clara, CA
carroll@tjc.com 


From rahulk at bhartitelesoft.com  Fri Oct 17 01:51:17 2003
From: rahulk at bhartitelesoft.com (Rahul Kumar)
Date: Fri Oct 17 01:34:25 2003
Subject: [Tutor] python_naming_conventions - newbie
Message-ID: <20031017055117.GF7414@bhartitelesoft.com>

As someone learning python after several years of working on Java, i am
interested to know why does python follow the
lower_case_with_underscores way of naming methods and variables while
Java follows the MixedCaseWithoutUnderscores.

After writing a couple of py progs, i find myself using the python way
in Java, and i prefer it (used to write C progs this way 10 yrs ago), and
i need some justification for this, since i am the guy who made the Java
guidelines for my org 4 years back !

--
regards,
rahul kumar

From fredm at smartypantsco.com  Fri Oct 17 03:43:34 2003
From: fredm at smartypantsco.com (Alfred Milgrom)
Date: Fri Oct 17 03:46:39 2003
Subject: [Tutor] Printing Chinese characters?
Message-ID: <5.1.0.14.0.20031017173840.02a41c20@mail.milgromphoto.com>

Hi:

Let me start by saying I just love programming in Python. I love its 
philosophy, its ease of use, the obvious productivity, the third-party 
support, the code libraries, and so on.
(As an aside, I thought list comprehension was pretty great, but now that I 
have discovered iterators, it's even better:)

But just as important as the power of the language, the support given by 
people on this forum is incredible. So I just want to start off by saying 
thanks to all of you.

As far as my Chinese text string is concerned, the string is part of 
comments in a Go game problem from a Chinese web site (Go is an ancient 
oriental board game, also known as weiqi in China and baduk in Korea).

My first problem was converting the string into unicode. Now that I have 
access to the CJK encodings (thanks Danny), I believe that the coding is 
mainly 'chinese' rather than 'big5'. But there could be some special 
Japanese Go terms in there as well :((

The first two Chinese characters might be:
u'\u9ed1' Black
u'\u5408' combine

(Translation made using unihan.txt - thanks Neal for pointing me in that 
direction)
This makes sense in the context of the problem and would translate as 
'Black to join his groups' (or similar).

I haven't figured out what to do with the '?' characters, and haven't 
decided if they are punctuation of some kind or an escape character or 
whatever.  And I don't know when to check for Japanese characters, either. 
So I am not sure about the following characters yet. Some characters are 
definitely not 'chinese' encoding.

But now I have enough ammunition to get me going forward.
(Terry: When I get enough confidence in my decoding, I will get in touch 
with you concerning your unihan Python lookup module. Thanks.)

As a final aside, I know that many people prefer other editors rather than 
IDLE, but IDLE can't be beaten in this situation. There is no need for 
other GUIs, web browsers, etc. Because IDLE is written in Tkinter, it 
automatically displays unicode characters properly!

Thanks again,
Fred Milgrom


From project5 at redrival.net  Fri Oct 17 10:17:41 2003
From: project5 at redrival.net (Andrei)
Date: Fri Oct 17 10:19:58 2003
Subject: [Tutor] Re: python_naming_conventions - newbie
In-Reply-To: <20031017055117.GF7414@bhartitelesoft.com>
References: <20031017055117.GF7414@bhartitelesoft.com>
Message-ID: <bmotq6$ael$1@sea.gmane.org>

Rahul Kumar wrote:
> As someone learning python after several years of working on Java, i am
> interested to know why does python follow the
> lower_case_with_underscores way of naming methods and variables while
> Java follows the MixedCaseWithoutUnderscores.

Does it? It's not really true. The conventions for this kind of stuff are in the 
Style Guide:

http://www.python.org/doc/essays/styleguide.html

The recommendations for camelCase, MixedCase and under_scores are quite murky 
IMO, here's a quote: "CapWords style is used for functions that provide major 
functionality (e.g. nstools.WorldOpen()), while lowercase is used more for 
"utility" functions". For the one using the module, it's all pretty much 
guesswork whether the author considered something major or minor functionality.

> After writing a couple of py progs, i find myself using the python way
> in Java, and i prefer it (used to write C progs this way 10 yrs ago), and
> i need some justification for this, since i am the guy who made the Java
> guidelines for my org 4 years back !

I use camelCase in method names, MixedCase for classes and objects, UPPERCASE 
for 'constants' (well, things that are *supposed* to remain constant anyway), 
lowercase for most variables and normal functions, while avoiding under_scores 
like the plague :) - I find them very time consuming. In the end, I suppose it's 
all a matter of taste, as long as it's consistent.
When I started programming in Pascal, we were taught to write "BEGIN". When I 
switched to Delphi, which uses "begin" in all generated code, I found that 
lowercase stuff quite annoying. Not too long ago I looked at an old Pascal 
program and found the all-caps impossible to read again :).

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur 
yvfg, fb gurer'f ab arrq gb PP.



From marc_barry at hotmail.com  Fri Oct 17 11:54:54 2003
From: marc_barry at hotmail.com (Marc Barry)
Date: Fri Oct 17 11:55:00 2003
Subject: [Tutor] Public, private and protected member variables.
Message-ID: <Sea2-F616nHUiZYjW0n00008111@hotmail.com>

Dear All:

I have a question regarding the existence of protected members in Python. 
Basically, in a language like Java we have public, private and protected 
member variables. But in Python I only know of public and private. I would 
like to inherit from a class and be able to modify parent member variables, 
but I would not like any class that doesn't inherit from the parent to be 
able to modify the member variables (i.e. Protected concept in Java).

Here is a simple example:

#------------------------------------------------------------
class Car:
	def __init__(self, colour):
		self.__colour = colour


class Ferrari(Car):
	def __init__(self, model, colour):

		Car.__init__(self, colour)
		self.__model = model

	def printColour(self):
		print self.__colour

a_ferrari = Ferrari("Enzo", "Red")
print dir(a_ferrari)
a_ferrari.printColour()
#------------------------------------------------------------

The output from running this script is:

['_Car__colour', '_Ferrari__model', '__doc__', '__init__', '__module__', 
'printColour']
Traceback (most recent call last):
  File "inheritance.py", line 19, in ?
    a_ferrari.printColour()
  File "inheritance.py", line 15, in printColour
    self.__colour
AttributeError: Ferrari instance has no attribute '_Ferrari__colour'

As you can see the __colour member variable of Car is not visible in the 
Ferrari class since it appears that appending '__' on a variable makes it 
private and not protected. Is there a way to make a variable protected in 
Python?

If I expose a variable in Car as public ,then I will allow users of the 
class to modify it directly. I would like to avoid this since that fixes my 
implementation to being always having to provide a variable named "colour" 
for example. Also, this is just a simplification of my problem as my class 
is much more complicated with a lot of gettable and settable properties in 
the parent object (Which I want to inherit).

Regards,

Marc Barry
marc_barry@hotmail.com

_________________________________________________________________
MSN 8 with e-mail virus protection service: 2 months FREE*  
http://join.msn.com/?page=features/virus


From dyoo at hkn.eecs.berkeley.edu  Fri Oct 17 13:22:05 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Oct 17 13:25:34 2003
Subject: [Tutor] Public, private and protected member variables.
In-Reply-To: <Sea2-F616nHUiZYjW0n00008111@hotmail.com>
Message-ID: <Pine.LNX.4.44.0310171002320.26170-100000@hkn.eecs.berkeley.edu>



On Fri, 17 Oct 2003, Marc Barry wrote:

> I have a question regarding the existence of protected members in
> Python.  Basically, in a language like Java we have public, private and
> protected member variables.

Hi Mark,

(Tangential note: In some programming languages all member variables are
private by default.  Objective C is one example.)


> Here is a simple example:
>
> #------------------------------------------------------------
> class Car:
> 	def __init__(self, colour):
> 		self.__colour = colour
>
>
> class Ferrari(Car):
> 	def __init__(self, model, colour):
>
> 		Car.__init__(self, colour)
> 		self.__model = model
>
> 	def printColour(self):
> 		print self.__colour
>
> a_ferrari = Ferrari("Enzo", "Red")
> print dir(a_ferrari)
> a_ferrari.printColour()


> But in Python I only know of public and private. I would like to inherit
> from a class and be able to modify parent member variables, but I would
> not like any class that doesn't inherit from the parent to be able to
> modify the member variables (i.e. Protected concept in Java).

Python's variable protection is handled by convention, not law.  The
Python Style essay says that if we want to specify "protected"-style
status, we can use a single underscore in the front of the name:

    http://www.python.org/doc/essays/styleguide.html

So the informal way to handle this might be something like this:

###
class Car:
    def __init__(self, colour):
        self._colour = colour

class Ferrari(Car):
    def __init__(self, model, colour):
        Car.__init__(self, colour)
        self.__model = model

    def printColour(self):
        print self._colour
###


I know this is a toy example, but it might be better to "pull up"  the
printColour() method into the parent, and avoid the visibility problems
altogether:

###
class Car:
    def __init__(self, colour):
        self.__colour = colour

    def printColour(self):
        print self.__colour


class Ferrari(Car):
    def __init__(self, model, colour):
        Car.__init__(self, colour)
        self.__model = model
###



> If I expose a variable in Car as public, then I will allow users of the
> class to modify it directly. I would like to avoid this since that fixes
> my implementation to being always having to provide a variable named
> "colour"  for example. Also, this is just a simplification of my problem
> as my class is much more complicated with a lot of gettable and settable
> properties in the parent object (Which I want to inherit).


If you'd like, please feel free to talk about object design on the Tutor
list.  It's one of those things I'd like to learn more about myself.
*grin*  Perhaps it might be possible to avoid exposing so many properties
by reworking the design a little?

I think we had a recent discussion about this subject, and one thing that
came up was Java's influence was making people overdesign their classes to
use setFoo/getFoo everywhere.  Folks on the list also talked a bit about
the variable visibility stuff that you're interested in:

    http://mail.python.org/pipermail/tutor/2003-October/025599.html


Good luck to you!


From project5 at redrival.net  Fri Oct 17 13:40:07 2003
From: project5 at redrival.net (Andrei)
Date: Fri Oct 17 13:42:21 2003
Subject: [Tutor] Re: Public, private and protected member variables.
In-Reply-To: <Sea2-F616nHUiZYjW0n00008111@hotmail.com>
References: <Sea2-F616nHUiZYjW0n00008111@hotmail.com>
Message-ID: <bmp9ll$1vd$1@sea.gmane.org>

Marc Barry wrote:
> Dear All:
> 
> I have a question regarding the existence of protected members in 
> Python. Basically, in a language like Java we have public, private and 
> protected member variables. But in Python I only know of public and 
> private. I would like to inherit from a class and be able to modify 

Only in Python private isn't *really* private. Come to think of it, other 
languages which have public/private/protected have some awkward rules too, e.g. 
classes declared in the same unit in Delphi don't behave quite as you'd expect 
them regarding these permissions.

<snip>

> The output from running this script is:
> 
> ['_Car__colour', '_Ferrari__model', '__doc__', '__init__', '__module__', 
> 'printColour']
> Traceback (most recent call last):
>  File "inheritance.py", line 19, in ?
>    a_ferrari.printColour()
>  File "inheritance.py", line 15, in printColour
>    self.__colour
> AttributeError: Ferrari instance has no attribute '_Ferrari__colour'
> 
> As you can see the __colour member variable of Car is not visible in the 
> Ferrari class since it appears that appending '__' on a variable makes 
> it private and not protected. Is there a way to make a variable 
> protected in Python?

Actually, it is visible. The name is mangled to "_Car__colour", that's all that 
"private" does: name mangling. So it should be ok if you do in printColour 
"print self._Car__colour" rather than "print self.__colour".

Note that in Python you can access the pieces of a class using its __dict__, so 
you can't do a lot about a really persistent programmer trying to access your 
private parts - in a programming sense, that is.

> If I expose a variable in Car as public ,then I will allow users of the 
> class to modify it directly. I would like to avoid this since that fixes 
> my implementation to being always having to provide a variable named 
> "colour" for example. Also, this is just a simplification of my problem 

Python doesn't enforce this kind of security. If someone *wants* to access the 
mangled name (_Car__colour), its name makes it clear it's "private" and they're 
aware of the risk that it might change. At that point they can choose to be 
responsible programmers and not use it, or use it anyway and live with the 
consequences. I like this attitude better than that in "traditional" langauges 
which enforce private/protected, where programmers then start looking for clever 
hacks to access that supposedly secret data anyway.

> as my class is much more complicated with a lot of gettable and settable 
> properties in the parent object (Which I want to inherit).

I don't know your needs, but perhaps you're trying too hard to turn Python into 
a language with static typing? When I first started in Python (which is not that 
long ago), I had a tendency to do manual typechecking along the lines of "if 
type(x)==type(y):". Turns out that's actually not necessary.

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur 
yvfg, fb gurer'f ab arrq gb PP.



From tim.ronning at start.no  Fri Oct 17 18:19:24 2003
From: tim.ronning at start.no (Tim)
Date: Fri Oct 17 16:44:51 2003
Subject: [Tutor] Python audio help needed
Message-ID: <oprw7kamgxs9of6q@smtp.start.no>

Hello list, and greetings from Norway

I'm new to this list and to Python (obviously since I'm asking questions 
here..)

In paralell with learning from books, online training, etc, I have also 
started my own little project. I want to build a dead simple mp3 player 
using pymad (libmad) library and PyQt when I get the basics to work.

I started out with this little script, supplied by the author to show how 
to use pymad.

#!/usr/bin/env python
import mad, ao, sys
mf = mad.MadFile(sys.argv[1])
dev = ao.AudioDevice('oss', rate=mf.samplerate())
while 1:
    buf = mf.read()
    if buf is None:
        break
    dev.play(buf, len(buf))

My first problem, I don't have module ao! Couldn't find on the net so I'm 
trying to acomplish the same with module ossaudiodev. After some study in 
the Python docs I now have this script.

#!/usr/bin/env python
import mad, ossaudiodev, sys

mf = mad.MadFile(sys.argv[1])
dev = ossaudiodev.open('/dev/audio0', "w")
rate=mf.samplerate()
#print rate
dev.setfmt(505)
dev.channels(2)
dev.speed(rate)
while 1:
    buf = mf.read()
    if buf is None:
        break
    dev.write(buf)

This actually plays the commandline supplied mp3 file, but! It sound's like 
something out of a seventees horror movie. It's extremely slow and with a 
lot of noise. I have a feeling that it has something to do with the 
setfmt() but I'm not sure. I'm running with ALSA drivers (with OSS support) 
so in theory it should work, but again I'm not sure. When I run getfmts() 
the result I'm getting back from the sound device is bitmask 505. The 
device is a Creative Live! 5.1 (ALSA emu10k1)

Can anyone help me out here. Is there an ALSA audio module out there 
somewhere? Or should I set some other value to setfmt() All help is greatly 
appriciated.

Best regards
Tim

-- 
Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/

From alan.gauld at blueyonder.co.uk  Fri Oct 17 18:25:52 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Fri Oct 17 18:25:23 2003
Subject: [Tutor] Re: python_naming_conventions - newbie
References: <20031017055117.GF7414@bhartitelesoft.com>
	<bmotq6$ael$1@sea.gmane.org>
Message-ID: <001901c394fd$9fb74250$6401a8c0@xp>

> When I started programming in Pascal, we were taught to write
"BEGIN". When I
> switched to Delphi, which uses "begin" in all generated code, I
found that
> lowercase stuff quite annoying. Not too long ago I looked at an old
Pascal
> program and found the all-caps impossible to read again :).

One reason COBOL is so hard to maintain is that it uses all uppercase
for everything. Uppercase is much harder for the human brain to
comprehend because much of our cognitive system is based on the
shape of words not the exact sequence of letters. By using
uppercase the shape variation is lost - all words look square.

As to the underscore_thing verses mixedCase I use a mixture
depending on the name. Some things dont look right(to me)
using MixedCase, others are too long using underscores.

So far as I know there is no conclusive data favouring one over
the other, like many stylistic issues intenal consistency is more
important than which one you pick.

Alan G.


From alan.gauld at blueyonder.co.uk  Fri Oct 17 18:45:43 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Fri Oct 17 18:45:15 2003
Subject: [Tutor] Public, private and protected member variables.
References: <Sea2-F616nHUiZYjW0n00008111@hotmail.com>
Message-ID: <002001c39500$657d3970$6401a8c0@xp>

> I have a question regarding the existence of protected members in
Python.

We had a longish thread on variable scoping in Python just recently,
try searching the archives.

> Basically, in a language like Java we have public, private and
protected
> member variables.

Indeed, Java copied the concept from C++ which introduced it
in version 2, partly to help manage complexity in the face of
multiple inheritance(also introduced in version 2).

> But in Python I only know of public and private.

And even private can be bypassed fairly easily (as it can
in C++!) and in practice public variables are the norm.

> inherit from a class and be able to modify parent member variables,
> but I would not like any class that doesn't inherit from the parent
> to be able to modify the member variables

Why? Apart from paranoia born from exposure to languages
like C++ and Java(which as I say just played copycat?)

OO programmers have been using inheritance for many years
without protected scopes (and originally often without
private either!) and it very rarely causes problems.
If you really do need to hide the variables completely
then simply make them private and then provide accessor
functions(yuk!) or make them properties(slightly better).
The accessor can if you really want to, check the immediate
parent of the calling class...if you really want to...

But do you habitually find yourself breaking your own design
by trying to directly access internal state? Or do you really
distrust your fellow programmers that much? And what about
the occasions when internal access is actually needed by
a non child class? C++ provides the friend construct,
should Python do likewise?

Its easier to just go with the flow when using a new language.
One of the reasons that C++ and Java are so verbose and
difficult to use is that they introduce all manner of
artificial restictions which programmers have to work around.
(And I say that as someone who used C++ almost exclusively
from 1988 through to 1996 - then I found Delphi, hooray!
Then I found Python, double hooray! And I haven't written
any serious C++ since 1999. And I studiously avoid Java as
much as possible) Python tries to make the programmers life
easy at the expense of expecting a little courtesy to be
exercised.

> If I expose a variable in Car as public ,then I will allow users of
the
> class to modify it directly. I would like to avoid this since that
fixes my
> implementation to being always having to provide a variable named
"colour"
> for example.

If that's your concern you could override setattr and getattr
to prevent access to anything that wasn't a method. That
way all attributes are private. Then you have to provide
accessor functions - is that really any better?

Alternatively, in your documentation just tell users not
to access the attributes directly. And that doing so may result
in undefined behaviour!

> is much more complicated with a lot of gettable and settable
properties in
> the parent object (Which I want to inherit).

Yep, that's why lots of gettable/settable properties are a pain.
See the previous thread... Sorry but the gettable/settable stuff
is one of my hot buttons :-(

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


From arkamir at softhome.net  Fri Oct 17 20:14:56 2003
From: arkamir at softhome.net (Conrad Koziol)
Date: Fri Oct 17 20:15:13 2003
Subject: [Tutor] sorting nested tuples
Message-ID: <1066436096.8346.5.camel@quercus>

if I have a list


x = [('hello', 2), ('goodbye', 3), ('python', 1)]

how would i sort it by the 2 variable or any variable for that matter.

From dyoo at hkn.eecs.berkeley.edu  Fri Oct 17 20:33:15 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Oct 17 20:34:17 2003
Subject: [Tutor] sorting nested tuples  [decorate-sort-undecorate]
In-Reply-To: <1066436096.8346.5.camel@quercus>
Message-ID: <Pine.LNX.4.44.0310171717560.22372-100000@hkn.eecs.berkeley.edu>



On Fri, 17 Oct 2003, Conrad Koziol wrote:

> if I have a list
>
>
> x = [('hello', 2), ('goodbye', 3), ('python', 1)]
>
> how would i sort it by the 2 variable or any variable for that matter.


Hi Conrad,


A quick way to do it is to "decorate" the list:

###
>>> mylist = [('hello', 2), ('goodbye', 3), ('python', 1)]
>>> for i, e in enumerate(mylist):
...     mylist[i] = (e[1], e)
...
>>> mylist
[(2, ('hello', 2)), (3, ('goodbye', 3)), (1, ('python', 1))]
###


And this is something that can now be sorted!

###
>>> mylist.sort()
>>> mylist
[(1, ('python', 1)), (2, ('hello', 2)), (3, ('goodbye', 3))]
###


So it's sorted, but it's still decorated.  So we need to "undecorate"
the list:

###
>>> for i, e in enumerate(mylist):
...     mylist[i] = e[1]
...
>>> mylist
[('python', 1), ('hello', 2), ('goodbye', 3)]
###

This is the "decorate-sort-undecorate" pattern.  We take advantage of
Python's native sort() method, and augment/deaugment our structure just
enough to make things work nicely.

The Perl folks have popularized this technique as the "Schwartzian
Transform".  If you do a search on that term, you'll can find more
examples of this technique.  The technique is especially nice on Python
because tuples are directly comparable --- and tuples can contain tuples!
--- so we don't have anything really ugly to do the decoration.

If you'd like to know more, Andrew Dalke Sorting mini-HOWTO tutorial is a
good resource:

    http://www.amk.ca/python/howto/sorting/sorting.html


Good luck to you!


From j.ezequiel at spitech.com  Fri Oct 17 21:22:51 2003
From: j.ezequiel at spitech.com (Ezequiel, Justin)
Date: Fri Oct 17 21:23:19 2003
Subject: [Tutor] Re: unichr() question
Message-ID: <29E16390A38FD7118A03000BCD0F3F6501316A8A@mail.spiglobe.com>

>> > >>> unichr(long('1D4AA', 16))
>> > Traceback (most recent call last):
>> >   File "<interactive input>", line 1, in ?
>> > ValueError: unichr() arg not in range(0x10000) (narrow Python build)
>> > >>> x = eval("u'\\U000%s'" % '1D4AA')
>> > >>> x
>> > u'\U0001d4aa'
>> > >>> for c in x:
>> > ... 	print ord(c)
>> > ... 
>> > 55349
>> > 56490
>> > >>> unichr(55349) + unichr(56490)
>> > u'\U0001d4aa'
>> > How do I convert strings such as '1D4AA' to unicode without using eval()?

On Thu, 16 Oct 2003, Terry Carroll wrote:
>> If you have a way of getting a "wide build" I
>> suspect this would do the trick for you.
>> 
>> There's more information in PEP 261, 
>> http://www.python.org/peps/pep-0261.html : I think this is the last word 
>> on it.
>> 
Thanks Terry. I guess I'll just have to live with my eval() workaround.
Thanks also for the link to the PEP. Will re-read it to see if I missed anything.

From tim at johnsons-web.com  Fri Oct 17 23:25:51 2003
From: tim at johnsons-web.com (Tim Johnson)
Date: Fri Oct 17 23:22:11 2003
Subject: [Tutor] reference instead of copy
Message-ID: <20031018032551.GJ5104@johnsons-web.com>

Hello All:
I have been using the following function
(produced by help from this list (thanks!))
which returns a subset of a list.:
def extract (oldlist, spacing,ndx=-1):
	if ndx > -1:
		return [oldlist[i][ndx] for i in range (len(oldlist)) if not i%spacing]
	else:
		return [oldlist[i] for i in range (len(oldlist)) if not i%spacing]
# But let's suppose I wish to operate on this subset and have it
# reflected in the original list. I can't do this with the above
# configuration. Example below:
>>> test = [1,2,3,4,5,6,7,8,9,10]
>>> t = mylib.extract(test,2)
>>> print t
[1, 3, 5, 7, 9]
>>> t[1] = 'three'
>>> print t
[1, 'three', 5, 7, 9]
>>> print test
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# What I need for this is and 'extract' function which retains
# the original reference so that when I code:
t[1] = 'three'
# list 'test looks like this:
[1, 2, 'three', 4, 5, 6, 7, 8, 9, 10]
Any ideas?
    TIA
    tim
-- 
Tim Johnson <tim@johnsons-web.com>
      http://www.alaska-internet-solutions.com

From good_time_bad_time_moofoshi_time_ressurected at hotmail.com  Sat Oct 18 02:54:57 2003
From: good_time_bad_time_moofoshi_time_ressurected at hotmail.com (Hiroshi Ransom)
Date: Sat Oct 18 02:55:02 2003
Subject: [Tutor] (no subject)
Message-ID: <Sea1-F138ZcIVMm0LzE00017151@hotmail.com>

hi,
   im new this is basic u prlly heard this question a MIllion times but what 
are all the commands usable in the snake program and what do they do? also 
explain any spacings that must b done between commands.

_________________________________________________________________
E-mail just got a whole lot better. New ninemsn Premium. Click here 
http://ninemsn.com.au/premium/landing.asp


From dyoo at hkn.eecs.berkeley.edu  Sat Oct 18 03:32:31 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat Oct 18 03:35:52 2003
Subject: [Tutor] (no subject)
In-Reply-To: <Sea1-F138ZcIVMm0LzE00017151@hotmail.com>
Message-ID: <Pine.LNX.4.44.0310180020240.13889-100000@hkn.eecs.berkeley.edu>



On Sat, 18 Oct 2003, Hiroshi Ransom wrote:

> what are all the commands usable in the snake program and what do they
> do?

Hi Hiroshi,

What snake program do you mean?


> also explain any spacings that must b done between commands.

What kind of spacings do you mean?  Do you have a concrete example of
commands with spaces in them that you can show us?


If it sounds like these questions are a little silly, please forgive me.
But I'm just trying to figure out what you are trying to figure out.
*grin*


> im new this is basic u prlly heard this question a MIllion times but

Wwe may have heard similar questions before, but that is actually besides
the point.  We want to understand better why you're asking those
particular ones --- the "why" is much more important to us.  Are you
trying to learn programming from a tutorial?  If so, can you point it out
to us?  We want to see why you're running into problems.


Just in case you're starting from scratch: there's a lot of good beginner
tutorials here:

    http://www.python.org/topics/learn/non-prog.html

There's a lot of good tutorials there, and if you go through one, we'll be
happy to help answer your questions about them.


Good luck!


From alan.gauld at blueyonder.co.uk  Sat Oct 18 03:44:44 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Sat Oct 18 03:44:09 2003
Subject: [Tutor] (no subject)
References: <Sea1-F138ZcIVMm0LzE00017151@hotmail.com>
Message-ID: <004901c3954b$b29c9d40$6401a8c0@xp>

> im new this is basic u prlly heard this question a MIllion times but
what
> are all the commands usable in the snake program and what do they
do?

OK, I'll assume that "the snake program" is Python and not
the old snake game?

Python is a programming language and just like any other
language it has words and a set of rules abouit how to use
those words. Once you understand those rules you can
combine the words in many different sequences to express
ideas. In a programming language instead of expressing
ideas we express instructions to the computer to make
it do things.

The Python program is the mechanism for translating
the Python statements that we write into something
the computer understands.

The best place to find out how to do this is to use
one of the tutorials designed for complete beginners
on the Python web site, and ask specific questions
about them as you go on this mailing list. THe tutorials
are found here:

http://www.python.org/topics/learn/non-prog.html

> explain any spacings that must b done between commands.

The tutorials will explain all of that because spacing
(or indentation as its called ) is important in Python.

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


From fredm at smartypantsco.com  Sat Oct 18 03:45:00 2003
From: fredm at smartypantsco.com (Alfred Milgrom)
Date: Sat Oct 18 03:47:20 2003
Subject: [Tutor] Re: sorting nested tuples
Message-ID: <5.1.0.14.0.20031018174158.02a75310@mail.milgromphoto.com>

Hi Conrad:

 >> if I have a list
 >> x = [('hello', 2), ('goodbye', 3), ('python', 1)]
 >> how would i sort it by the 2 variable or any variable for that matter.

Danny has shown one way to sort the list using [decorate-sort-undecorate].
Here is another way to sort your list, by specifying your own compare 
function for sort.

For example:
 >>> def compare(a,b):
         if a[1]>b[1]: return 0
         else: return -1

The function 'compare' we have defined will compare tuples based on the 
second element, returning 0 if true. (Note you could use '>=' depending on 
how you want the compare to operate).

This function is OK for quick and dirty programming, but if you are going 
to be using it in a more general environment you should also put in some 
error checking to make sure you have tuples, etc.

 >>> x = [('hello', 2), ('goodbye', 3), ('python', 1)]
 >>> x.sort(compare)
 >>> x
[('python', 1), ('hello', 2), ('goodbye', 3)]

Personally I prefer this way as it makes my code more readable (especially 
if I use a better name than 'compare' :)

Hope this helps
Fred Milgrom




From dyoo at hkn.eecs.berkeley.edu  Sat Oct 18 04:04:13 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat Oct 18 04:04:23 2003
Subject: [Tutor] reference instead of copy
In-Reply-To: <20031018032551.GJ5104@johnsons-web.com>
Message-ID: <Pine.LNX.4.44.0310180034370.13889-100000@hkn.eecs.berkeley.edu>



On Fri, 17 Oct 2003, Tim Johnson wrote:

> I have been using the following function (produced by help from this
> list (thanks!)) which returns a subset of a list.:

> def extract (oldlist, spacing,ndx=-1):
> 	if ndx > -1:
> 		return [oldlist[i][ndx] for i in range (len(oldlist)) if not i%spacing]
> 	else:
> 		return [oldlist[i] for i in range (len(oldlist)) if not i%spacing]


Hi Tim,


Do you mind if we take a quick sidetrip?  The complexity of the list
comprehension is slightly high --- let me see what this looks like with
explicit loops:

###
def extract (oldlist, spacing,ndx=-1):
    if ndx > -1:
        results = []
        for i in range(len(oldlist)):
            if not i % spacing:
                results.append(oldlist[i][ndx])
    else:
        results = []
        for i in range(len(oldlist)):
            if not i % spacing:
                results.append(oldlist[i])
    return results
###



Hmm... There's some common stuff here.  Let me rework it a little more.

###
def extract (oldlist, spacing,ndx=-1):
    results = []
    for i in range(len(oldlist)):
        if i % spacing == 0:
            if ndx > -1:
                results.append(oldlist[i][ndx])
            else:
                results.append(oldlist[i])
    return results
###


Does extract() really have to deal with grabbing specific subindices using
that 'ndx' value?  That's something that I think can be done outside of
extract().  If it's ok, we can yank it out violently:

###
def extract (oldlist, spacing):
    results = []
    for i in range(len(oldlist)):
        if i % spacing == 0:
            results.append(oldlist[i])
    return results
###


Oh!  There's one more simplification we can make if we know a little more
about the range function() --- range can actually take in a "skip" third
argument.  For example:

###
>>> range(0, 10, 3)
[0, 3, 6, 9]
###


If we take advantage of this feature, then that lets us cut out the
remainder check:

###
def extract (oldlist, spacing):
    results = []
    for i in range(0, len(oldlist), spacing):
        results.append(oldlist[i])
    return results
###


We can transform this back to its list-comprehension equivalent:

###
def extract(oldlist, spacing):
    return [oldlist[i] for i in range(0, len(oldlist), spacing)]
###


> # But let's suppose I wish to operate on this subset and have it
> # reflected in the original list. I can't do this with the above
> # configuration.


Very true.  The reason for this is because of the use of the list
comprehension: list comprehnsions generate fresh new lists.  For example:

###
>>> def makeListCopy(L):
...     return [x for x in L]
...
>>> pi = [3, 1, 3, 1, 5, 9, 2, 6]
>>> pi_copy = makeListCopy(pi)
>>> pi
[3, 1, 3, 1, 5, 9, 2, 6]
>>> pi_copy
[3, 1, 3, 1, 5, 9, 2, 6]
###


Although they look the same now, they're only clones at birth.

###
>>> del pi[2:]
>>> pi_copy[2] = 4
>>>
>>> pi
[3, 1]
>>>
>>> pi_copy
[3, 1, 4, 1, 5, 9, 2, 6]
###



> # What I need for this is and 'extract' function which retains
> # the original reference so that when I code:
> t[1] = 'three'
> # list 'test looks like this:
> [1, 2, 'three', 4, 5, 6, 7, 8, 9, 10]

Trying to do this with list comprehensions probably won't work: list
comprehensions are spiritually designed NOT to modify the original list.
*grin*

Instead, you may want do direct manipulations --- like indicing and del
--- instead, and you should have better results.  In your original code,
though, you did something like:

###
>>> test = [1,2,3,4,5,6,7,8,9,10]
>>> t = mylib.extract(test,2)
>>> print t
###

How about reassigning to 'test'?



Good luck!


From dyoo at hkn.eecs.berkeley.edu  Sat Oct 18 04:09:59 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat Oct 18 04:10:19 2003
Subject: [Tutor] Re: sorting nested tuples
In-Reply-To: <5.1.0.14.0.20031018174158.02a75310@mail.milgromphoto.com>
Message-ID: <Pine.LNX.4.44.0310180104520.13889-100000@hkn.eecs.berkeley.edu>



On Sat, 18 Oct 2003, Alfred Milgrom wrote:

> Danny has shown one way to sort the list using [decorate-sort-undecorate].
> Here is another way to sort your list, by specifying your own compare
> function for sort.
>
> For example:
>  >>> def compare(a,b):
>          if a[1]>b[1]: return 0
>          else: return -1
>
> The function 'compare' we have defined will compare tuples based on the
> second element, returning 0 if true. (Note you could use '>=' depending
> on how you want the compare to operate).

By the way, we can say this another way by taking advantage of the
built-in cmp()  comparison function:

###
def compare(a, b):
    return cmp(a[1], b[1])
###



> Personally I prefer this way as it makes my code more readable
> (especially if I use a better name than 'compare' :)

How about compare_second_component()?  *grin*


Talk to you later!


From yduppen at xs4all.nl  Sat Oct 18 08:23:30 2003
From: yduppen at xs4all.nl (Yigal Duppen)
Date: Sat Oct 18 08:29:29 2003
Subject: [Tutor] sorting nested tuples
In-Reply-To: <1066436096.8346.5.camel@quercus>
References: <1066436096.8346.5.camel@quercus>
Message-ID: <200310181423.32558.yduppen@xs4all.nl>

> x = [('hello', 2), ('goodbye', 3), ('python', 1)]
>
> how would i sort it by the 2 variable or any variable for that matter.

Hi Conrad,

Apart from the decorate-sort-undecorate pattern described by Danny, you can 
also pass a comparator function to the sort method of a list.

First, define a comparator that compares on the second element of a tuple:
>>> def cmpOnSecond(t1, t2):
...     return cmp(t1[1], t2[1])

And the use that function:
>>> mylist = [('hello', 2), ('goodbye', 3), ('python', 1)]
>>> mylist.sort(cmpOnSecond)
>>> mylist
[('python', 1), ('hello', 2), ('goodbye', 3)]

If you're more into anonymous functions, this works too:
>>> mylist = [('hello', 2), ('goodbye', 3), ('python', 1)]
>>> mylist.sort(lambda t1,t2: cmp(t1[1], t2[1]))
>>> mylist
[('python', 1), ('hello', 2), ('goodbye', 3)]

For simple cases like this, I prefer the comparator function above the 
decorate-sort-undecorate approach.

YDD
-- 
http://www.xs4all.nl/~yduppen

From klappnase at freenet.de  Sat Oct 18 09:08:47 2003
From: klappnase at freenet.de (Michael Lange)
Date: Sat Oct 18 09:14:13 2003
Subject: [Tutor] Python audio help needed
In-Reply-To: <oprw7kamgxs9of6q@smtp.start.no>
References: <oprw7kamgxs9of6q@smtp.start.no>
Message-ID: <20031018150847.32470041.klappnase@freenet.de>

On Sat, 18 Oct 2003 00:19:24 +0200
Tim <tim.ronning@start.no> wrote:

> Hello list, and greetings from Norway
> 
> I'm new to this list and to Python (obviously since I'm asking questions 
> here..)
> 
> In paralell with learning from books, online training, etc, I have also 
> started my own little project. I want to build a dead simple mp3 player 
> using pymad (libmad) library and PyQt when I get the basics to work.
> 
...
> 
> Can anyone help me out here. Is there an ALSA audio module out there 
> somewhere? Or should I set some other value to setfmt() All help is greatly 
> appriciated.
> 
> Best regards
> Tim

Hi Tim,

maybe you should try tkSnack : www.speech.kth.se/snack

Snack supports both OSS and ALSA (however, when I tried to compile the sources with "--enable-alsa"  option it did NOT work,
but compiling without I have no problems using ALSA).
Snack's usage is quite simple and file formats are recognized automatically by the filename extension, so it is fairly easy to
play mp3 files:

	import tkSnack
	s = tkSnack.Sound(file='somefile.mp3')
	s.play()
This way you can even play large files(bigger than system memory.

I hope this helps.

Cheers

Michael

From missive at hotmail.com  Sat Oct 18 09:24:45 2003
From: missive at hotmail.com (Lee Harr)
Date: Sat Oct 18 09:24:49 2003
Subject: [Tutor] Re: Python audio help needed
Message-ID: <BAY2-F126GypSkiQlb90000b5cf@hotmail.com>

>In paralell with learning from books, online training, etc, I have also
>started my own little project. I want to build a dead simple mp3 player
>using pymad (libmad) library and PyQt when I get the basics to work.
>
>I started out with this little script, supplied by the author to show how
>to use pymad.
>
>#!/usr/bin/env python
>import mad, ao, sys
>mf = mad.MadFile(sys.argv[1])
>dev = ao.AudioDevice('oss', rate=mf.samplerate())
>while 1:
>    buf = mf.read()
>    if buf is None:
>        break
>    dev.play(buf, len(buf))
>
>My first problem, I don't have module ao! Couldn't find on the net so I'm
>trying to acomplish the same with module ossaudiodev. After some study in
>the Python docs I now have this script.
>


http://www.google.com/search?q=python+audio+ao
http://www.freshports.org/audio/py-ao/
http://www.andrewchatham.com/pyogg/

_________________________________________________________________
The new MSN 8: smart spam protection and 2 months FREE*  
http://join.msn.com/?page=features/junkmail


From raymond.hettinger at verizon.net  Sat Oct 18 10:45:30 2003
From: raymond.hettinger at verizon.net (Raymond Hettinger)
Date: Sat Oct 18 10:46:17 2003
Subject: [Tutor] Merge Challenge
Message-ID: <000001c39586$7aecc740$e841fea9@oemcomputer>

Given two sorted lists, a and b, write the fastest, 
code that merges a and b into a new list c.
 
My answer has 15 characters including newlines.
 
 
Raymond Hettinger
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20031018/005eecb8/attachment.html
From erikprice at mac.com  Sat Oct 18 11:17:26 2003
From: erikprice at mac.com (Erik Price)
Date: Sat Oct 18 10:55:10 2003
Subject: [Tutor] python_naming_conventions - newbie
In-Reply-To: <20031017055117.GF7414@bhartitelesoft.com>
Message-ID: <2E8D0FAA-017E-11D8-81B0-00039351FE6A@mac.com>


On Friday, October 17, 2003, at 01:51  AM, Rahul Kumar wrote:

> As someone learning python after several years of working on Java, i am
> interested to know why does python follow the
> lower_case_with_underscores way of naming methods and variables while
> Java follows the MixedCaseWithoutUnderscores.

I don't know the answer why, but one of the more important suggestions 
made by both "Java Elements of Style" and IIRC the Python Style 
Guidelines is that convention is more important than aesthetics.  That 
is to say, while aesthetics certainly play a role (even in the very 
choice of a name for a variable), what is more important is to make 
sure that your naming is consistent with what is conventional for your 
project.  Java happens to have a well-known published style guide that 
strongly recommends that camelCase be used for variable names and 
UNDERSCORE_SEPARATORS only be used in [capitalized] constant 
declarations (static final String FOO).

That said, my guess is that the reason why it was originally selected 
is probably because the extra underscores make the variable names 
wider.  This isn't as much an issue in Python because type and access 
declarations aren't used, but because you need to declare the access 
level and type/return type in Java, it ends up making your code lines 
wider.  Just yesterday I wrote this method signature:

     private Mip mipFromFile(File mipFile)

whereas in Python, it could have simply been declared as:

     def mip_from_file(mip_file):

As you can see, the Python version is still shorter even though I've 
used the underscores as separators.

> After writing a couple of py progs, i find myself using the python way
> in Java, and i prefer it (used to write C progs this way 10 yrs ago), 
> and
> i need some justification for this, since i am the guy who made the 
> Java
> guidelines for my org 4 years back !

In Python I don't really stick to one or the other, but try to go with 
what seems most logical for the situation.  However, in Java my own 
preference is to simply stick to the official standard simply because 
when others read my code, that's probably what they'll expect to see.


Erik


From tim at johnsons-web.com  Sat Oct 18 12:37:28 2003
From: tim at johnsons-web.com (Tim Johnson)
Date: Sat Oct 18 12:33:49 2003
Subject: [Tutor] reference instead of copy
In-Reply-To: <Pine.LNX.4.44.0310180034370.13889-100000@hkn.eecs.berkeley.edu>
References: <20031018032551.GJ5104@johnsons-web.com>
	<Pine.LNX.4.44.0310180034370.13889-100000@hkn.eecs.berkeley.edu>
Message-ID: <20031018163728.GM5104@johnsons-web.com>

* Danny Yoo <dyoo@hkn.eecs.berkeley.edu> [031018 00:10]:

Mornin' Danny: 

As usual, you are chock full of good info. Coming from a "C"
background 'way' back, I would be able to copy a subset of an array
of pointers, work on the data that they referenced and have it reflected
in the original. Haha! But we're not supposed to talk about pointers
here. Rebol's own 'extract' has the same behavior.

Can you point me to some docs or discussions on the
more advanced use of slicing and indexing, if you can think of any?
Thanks!

(and as soon as I'm done with my coffee, I'm going to start thinking
 of 'range' as generating object with the indices I want) 
 there's a solution there, I can just start to see it)

cheers
tim
> 
> On Fri, 17 Oct 2003, Tim Johnson wrote:
> 
> > I have been using the following function (produced by help from this
> > list (thanks!)) which returns a subset of a list.:
> 
> > def extract (oldlist, spacing,ndx=-1):
> > 	if ndx > -1:
> > 		return [oldlist[i][ndx] for i in range (len(oldlist)) if not i%spacing]
> > 	else:
> > 		return [oldlist[i] for i in range (len(oldlist)) if not i%spacing]
> 
> 
> Hi Tim,
> 
> 
> Do you mind if we take a quick sidetrip?  The complexity of the list
> comprehension is slightly high --- let me see what this looks like with
> explicit loops:
> 
> ###
> def extract (oldlist, spacing,ndx=-1):
>     if ndx > -1:
>         results = []
>         for i in range(len(oldlist)):
>             if not i % spacing:
>                 results.append(oldlist[i][ndx])
>     else:
>         results = []
>         for i in range(len(oldlist)):
>             if not i % spacing:
>                 results.append(oldlist[i])
>     return results
> ###
> 
> 
> 
> Hmm... There's some common stuff here.  Let me rework it a little more.
> 
> ###
> def extract (oldlist, spacing,ndx=-1):
>     results = []
>     for i in range(len(oldlist)):
>         if i % spacing == 0:
>             if ndx > -1:
>                 results.append(oldlist[i][ndx])
>             else:
>                 results.append(oldlist[i])
>     return results
> ###
> 
> 
> Does extract() really have to deal with grabbing specific subindices using
> that 'ndx' value?  That's something that I think can be done outside of
> extract().  If it's ok, we can yank it out violently:
> 
> ###
> def extract (oldlist, spacing):
>     results = []
>     for i in range(len(oldlist)):
>         if i % spacing == 0:
>             results.append(oldlist[i])
>     return results
> ###
> 
> 
> Oh!  There's one more simplification we can make if we know a little more
> about the range function() --- range can actually take in a "skip" third
> argument.  For example:
> 
> ###
> >>> range(0, 10, 3)
> [0, 3, 6, 9]
> ###
> 
> 
> If we take advantage of this feature, then that lets us cut out the
> remainder check:
> 
> ###
> def extract (oldlist, spacing):
>     results = []
>     for i in range(0, len(oldlist), spacing):
>         results.append(oldlist[i])
>     return results
> ###
> 
> 
> We can transform this back to its list-comprehension equivalent:
> 
> ###
> def extract(oldlist, spacing):
>     return [oldlist[i] for i in range(0, len(oldlist), spacing)]
> ###
> 
> 
> > # But let's suppose I wish to operate on this subset and have it
> > # reflected in the original list. I can't do this with the above
> > # configuration.
> 
> 
> Very true.  The reason for this is because of the use of the list
> comprehension: list comprehnsions generate fresh new lists.  For example:
> 
> ###
> >>> def makeListCopy(L):
> ...     return [x for x in L]
> ...
> >>> pi = [3, 1, 3, 1, 5, 9, 2, 6]
> >>> pi_copy = makeListCopy(pi)
> >>> pi
> [3, 1, 3, 1, 5, 9, 2, 6]
> >>> pi_copy
> [3, 1, 3, 1, 5, 9, 2, 6]
> ###
> 
> 
> Although they look the same now, they're only clones at birth.
> 
> ###
> >>> del pi[2:]
> >>> pi_copy[2] = 4
> >>>
> >>> pi
> [3, 1]
> >>>
> >>> pi_copy
> [3, 1, 4, 1, 5, 9, 2, 6]
> ###
> 
> 
> 
> > # What I need for this is and 'extract' function which retains
> > # the original reference so that when I code:
> > t[1] = 'three'
> > # list 'test looks like this:
> > [1, 2, 'three', 4, 5, 6, 7, 8, 9, 10]
> 
> Trying to do this with list comprehensions probably won't work: list
> comprehensions are spiritually designed NOT to modify the original list.
> *grin*
> 
> Instead, you may want do direct manipulations --- like indicing and del
> --- instead, and you should have better results.  In your original code,
> though, you did something like:
> 
> ###
> >>> test = [1,2,3,4,5,6,7,8,9,10]
> >>> t = mylib.extract(test,2)
> >>> print t
> ###
> 
> How about reassigning to 'test'?
> 
> 
> 
> Good luck!

-- 
Tim Johnson <tim@johnsons-web.com>
      http://www.alaska-internet-solutions.com

From glingl at aon.at  Sat Oct 18 13:54:44 2003
From: glingl at aon.at (Gregor Lingl)
Date: Sat Oct 18 13:56:39 2003
Subject: [Tutor] Merge Challenge
In-Reply-To: <000001c39586$7aecc740$e841fea9@oemcomputer>
References: <000001c39586$7aecc740$e841fea9@oemcomputer>
Message-ID: <3F917E64.2060807@aon.at>

Hello Raymond!

I'm very courious about your solution.
I tried

c=a+b
c.sort()

and that is indeed very fast. (Trying for half an
hour I couldn't find *any* faster one).
Will be hard to surpass.

Regards, Gregor


Raymond Hettinger schrieb:

> Given two sorted lists, a and b, write the fastest,
>
> code that merges a and b into a new list c.
>
>  
>
> My answer has 15 characters including newlines.
>
>  
>
>  
>
> Raymond Hettinger
>
>------------------------------------------------------------------------
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>  
>


From jim_938 at hotmail.com  Sat Oct 18 14:58:47 2003
From: jim_938 at hotmail.com (Jimmy verma)
Date: Sat Oct 18 14:58:51 2003
Subject: [Tutor] long-to-string
Message-ID: <Sea1-F31y0mVRDoNVtW0000828e@hotmail.com>

Hello,

First of all thanks to tutor for providing their support. People on this 
list are really helpful.

Now I would like to discuss something about my problem::


i have written a module to covert a 4 byte string into a long like this:

>>>def makelong(chaine):
...     # Make a long form a 4-byte string
...     return 
((ord(chaine[0])*256+ord(chaine[1]))*256+ord(chaine[2]))*256+ord(chaine[3])
...
>>># Now call the function we just defined:
... makelong('oMAP')
1867333968


I packs this data with struct module

using '>L' format

I am able to unpack this and get the no from my file

Now i want is to convert the no back into the string like 'oXYZ' for which 
this no was meant.

I would welcome your suggestions on how should i move ahead.

Thanks in advance.

With best regards,

J+

_________________________________________________________________
MSN Hotmail now on your Mobile phone. 
http://server1.msn.co.in/sp03/mobilesms/ Click here.


From python at rcn.com  Sat Oct 18 15:06:47 2003
From: python at rcn.com (Raymond Hettinger)
Date: Sat Oct 18 15:07:33 2003
Subject: [Tutor] Merge Challenge
In-Reply-To: <3F917E64.2060807@aon.at>
Message-ID: <003301c395aa$fad8d880$e841fea9@oemcomputer>

[Gregor]
> I'm very courious about your solution.
> I tried
> 
> c=a+b
> c.sort()
> 
> and that is indeed very fast. (Trying for half an
> hour I couldn't find *any* faster one).
> Will be hard to surpass.

That's the winning solution.
Tim Peter's amazing new sort routine discovers 
the two sorted subsequences and merges them in
a tight C coded loop at O(n) runtime.

For almost any other implementation of sort, the
above solution would run at a much slower O(n log n)
speed and would be beat by even badly coded pure
python solutions running at O(n).

In case you can't tell, I'm very impressed with
Tim's sort code.



Raymond Hettinger


From jk_ksu at budweiser.com  Sat Oct 18 16:17:39 2003
From: jk_ksu at budweiser.com (jeremy kearns)
Date: Sat Oct 18 16:17:42 2003
Subject: [Tutor] Regarding loops
Message-ID: <20031018201739.7231.qmail@machiavelli.synacor.com>

import random



# create a sequence



WORDS = ("python","jumble",)



# pick a random word



word = random.choice(WORDS)



# create variable to use later to see if guess is correct



correct = word



# jumble creation part



# -------------------------------



# create an empty jumble word

# while the chosen word has letters in it

# extract a random letter from the chosen word

# add the random letter to the jumble word



# jumbled version of the word

jumble = " "

while word:

    position = random.randrange(len(word))

    jumble += word[position]

    word = word[:position] + word[(position + 1):]



# start



print \

"""



            Welcome to the word jumble!



    Unscramble the letters to make a word.

    (press the enter key at prompt to exit)

"""



# PROBLEM AREA



print "The jumble is:", jumble



guess = raw_input("\nYour guess: ")

guess = guess.lower()

while (guess != correct) and (guess != ""):

    if guess != correct and correct == "python":

        print "Do you want a hint?"        

    userHint1 = int(raw_input("1 for True or 0 for False: "))

    if userHint1 == True:

        print "What program is associated with python.org? "

    else:

        print "You guessed wrong, maybe take a hint next time."



    if guess != correct and correct == "jumble":

        print "Do you want a hint?"        

    userHint1 = int(raw_input("1 for True or 0 for False: "))

    if userHint1 == True:

        print " "

    else:

        print "You guessed wrong, maybe take a hint next time."



# I can't get the loops to function properly here.  

# The loops override each other.

# Can you please point out what is wrong with this?



if guess == correct:

    print "That's it! You guessed it!\n"



print "Thanks for playing."

raw_input("\nPress enter to exit the program.")




-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20031018/4d73cef9/attachment.html
From intatia at paradise.net.nz  Sat Oct 18 21:33:04 2003
From: intatia at paradise.net.nz (Intatia)
Date: Sat Oct 18 21:33:30 2003
Subject: [Tutor] Merge Challenge
In-Reply-To: <003301c395aa$fad8d880$e841fea9@oemcomputer>
References: <003301c395aa$fad8d880$e841fea9@oemcomputer>
Message-ID: <3F91E9D0.1070609@paradise.net.nz>



Raymond Hettinger wrote:
> [Gregor]
> 
>>I'm very courious about your solution.
>>I tried
>>
>>c=a+b
>>c.sort()
>>
>>and that is indeed very fast. (Trying for half an
>>hour I couldn't find *any* faster one).
>>Will be hard to surpass.
> 
> 
> That's the winning solution.

So that's the best way to do it... *bangs head on desk*

> Tim Peter's amazing new sort routine discovers 
> the two sorted subsequences and merges them in
> a tight C coded loop at O(n) runtime.
> 
> For almost any other implementation of sort, the
> above solution would run at a much slower O(n log n)
> speed and would be beat by even badly coded pure
> python solutions running at O(n).
> 
> In case you can't tell, I'm very impressed with
> Tim's sort code.
> 
> 
> 
> Raymond Hettinger
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


From glingl at aon.at  Sun Oct 19 05:31:42 2003
From: glingl at aon.at (Gregor Lingl)
Date: Sun Oct 19 05:33:34 2003
Subject: [Tutor] Regarding loops
In-Reply-To: <20031018201739.7231.qmail@machiavelli.synacor.com>
References: <20031018201739.7231.qmail@machiavelli.synacor.com>
Message-ID: <3F9259FE.8030206@aon.at>



jeremy kearns schrieb:
...

> Welcome to the word jumble!
> ...
> # PROBLEM AREA
>
> print "The jumble is:", jumble
>
> guess = raw_input("\nYour guess: ")
> guess = guess.lower()
> while (guess != correct) and (guess != ""):
>     if guess != correct and correct == "python":
>         print "Do you want a hint?"
>         userHint1 = int(raw_input("1 for True or 0 for False: "))
>         if userHint1 == True:
>              print "What program is associated with python.org? "
>         else:
>              print "You guessed wrong, maybe take a hint next time."
>
>     if guess != correct and correct == "jumble":
>         print "Do you want a hint?"
>         userHint1 = int(raw_input("1 for True or 0 for False: "))
>         if userHint1 == True:
>             print " "
>         else:
>             print "You guessed wrong, maybe take a hint next time."
>
> # I can't get the loops to function properly here.
> # The loops override each other.
> # Can you please point out what is wrong with this?

Hi Jeremy!

I think you expect this loop to terminate, if the user guessed right.
But in your code the user has  only  one possibility  to give an input  
for the
guess. That is before entering the loop. In the body of the loop there is
no assignment of a new value to guess.
To give the user the opportunity to input a new guess, you should add
an appropriate raw_input() call to the body of the loop.

moeover I observed that yuo loop consist of two parts, that are almost 
equal.
There is only one line which is different: that printing the hint. 
Perhaps you
could find a way to make your code more compact by putting only this line,
depending on the value of correct in (one or two) appropriate if 
statement(s)?

 Hope this helps?
Gregor

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


From karld at ugcs.caltech.edu  Sun Oct 19 15:16:37 2003
From: karld at ugcs.caltech.edu (karl d'adamo)
Date: Sun Oct 19 15:16:43 2003
Subject: [Tutor] Introduction and ? re: searching the list's archives
In-Reply-To: <001801c385d8$39570420$797ba8c0@rclilly.com>
References: <001801c385d8$39570420$797ba8c0@rclilly.com>
Message-ID: <20031019191637.GA6578@ugcs.caltech.edu>

On Sun, Sep 28, 2003 at 08:50:21AM -0700, Robert Lilly wrote:
> Hello everyone,
> I know that many of the questions I will want to ask have probably already
> been discussed. So I've downloaded the mbox archive so that I may search
> through it before asking a question. However, I'm not sure what an efficient
> means for searching it may be. Does anyone have any recommendations on how
> to go about searching an mbox archive? I am working primarily under Windows
> 2000, but I have Cygwin installed, so a *nix solution may be viable as well.
> post is off-topic.

how about mutt.  it should come with a full distribution
of cygwin.  it will likely take a few minutes to load a
very large mbox, but you get powerful searches like:

  show me all posts with a subject containing
  "dictionary", a body containing "hashable", that have
  been replied to and are PGP signed from 10/1/01 to
  11/1/01

  ~s dictionary ~b hashable ~Q ~g ~d 1/10/01-1/11/01

see here for a full description of mutt patterns:

    http://mutt.org/doc/manual/manual-4.html#ss4.2

to run it on your file, just type:

  mutt -f <name of mbox>

for messages it finds, you will see them in a nice
threaded format.

if you have multiple mboxes to search there is a nice
program that can search gzipped, bzip2ed mboxes, maildirs
by date and regexes within headers and/or body.  it also
includes a wrapper for mutt or pine called grepmail:

  http://grepmail.sourceforge.net/

wow, i am replying almost a month too late.

From rahulk at bhartitelesoft.com  Mon Oct 20 01:32:04 2003
From: rahulk at bhartitelesoft.com (Rahul Kumar)
Date: Mon Oct 20 01:14:25 2003
Subject: [Tutor] python_naming_conventions - newbie
In-Reply-To: <2E8D0FAA-017E-11D8-81B0-00039351FE6A@mac.com>
References: <20031017055117.GF7414@bhartitelesoft.com>
	<2E8D0FAA-017E-11D8-81B0-00039351FE6A@mac.com>
Message-ID: <20031020053204.GA7016@bhartitelesoft.com>

Interestingly, while going through the code of TwistedMatrix I find that
they use the camelCase. I wonder what Bruce Eckel uses (the Thinking in
Java guy who has moved to Python).
I completely agree about consistency over ethics, but just wanted to
know how the decision was made in the first place.
Thanks for your answers.

On Sat, Oct 18, 2003 at 11:17:26AM -0400, Erik Price wrote:
> Date: Sat, 18 Oct 2003 11:17:26 -0400
> Subject: Re: [Tutor] python_naming_conventions - newbie
> Cc: tutor@python.org
> To: Rahul Kumar <rahulk@bhartitelesoft.com>
> From: Erik Price <erikprice@mac.com>
> X-Mailer: Apple Mail (2.552)
> 
> 
> On Friday, October 17, 2003, at 01:51  AM, Rahul Kumar wrote:
> 
> >As someone learning python after several years of working on Java, i am
> >interested to know why does python follow the
> >lower_case_with_underscores way of naming methods and variables while
> >Java follows the MixedCaseWithoutUnderscores.
> 
> I don't know the answer why, but one of the more important suggestions 
> made by both "Java Elements of Style" and IIRC the Python Style 
> Guidelines is that convention is more important than aesthetics.  That 
> is to say, while aesthetics certainly play a role (even in the very 
> choice of a name for a variable), what is more important is to make 
> sure that your naming is consistent with what is conventional for your 
> project.  Java happens to have a well-known published style guide that 
> strongly recommends that camelCase be used for variable names and 
> UNDERSCORE_SEPARATORS only be used in [capitalized] constant 
> declarations (static final String FOO).
> 
> That said, my guess is that the reason why it was originally selected 
> is probably because the extra underscores make the variable names 
> wider.  This isn't as much an issue in Python because type and access 
> declarations aren't used, but because you need to declare the access 
> level and type/return type in Java, it ends up making your code lines 
> wider.  Just yesterday I wrote this method signature:
> 
>     private Mip mipFromFile(File mipFile)
> 
> whereas in Python, it could have simply been declared as:
> 
>     def mip_from_file(mip_file):
> 
> As you can see, the Python version is still shorter even though I've 
> used the underscores as separators.
> 
> >After writing a couple of py progs, i find myself using the python way
> >in Java, and i prefer it (used to write C progs this way 10 yrs ago), 
> >and
> >i need some justification for this, since i am the guy who made the 
> >Java
> >guidelines for my org 4 years back !
> 
> In Python I don't really stick to one or the other, but try to go with 
> what seems most logical for the situation.  However, in Java my own 
> preference is to simply stick to the official standard simply because 
> when others read my code, that's probably what they'll expect to see.
> 
> 
> Erik
> 

-- 
Regards,
Rahul Kumar                               | Fax: 6817557, 5770
Bharti Telesoft Intl Pvt Ltd              | Tel: 6819330,31,32,34,36 X:231
F-89/6 Okhla Indl Area Phase 1, New Delhi |      8611508-14,16,17

Java everywhere!

From idiot1 at netzero.net  Mon Oct 20 01:21:07 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Mon Oct 20 01:21:05 2003
Subject: [Tutor] python_naming_conventions - newbie
In-Reply-To: <20031020053204.GA7016@bhartitelesoft.com>
References: <20031017055117.GF7414@bhartitelesoft.com>	<2E8D0FAA-017E-11D8-81B0-00039351FE6A@mac.com>
	<20031020053204.GA7016@bhartitelesoft.com>
Message-ID: <3F9370C3.7070106@netzero.net>

Intresting. I wonder if the Matrix is a wikiwiki?

Rahul Kumar wrote:
> Interestingly, while going through the code of TwistedMatrix I find that
> they use the camelCase. I wonder what Bruce Eckel uses (the Thinking in
> Java guy who has moved to Python).
> I completely agree about consistency over ethics, but just wanted to
> know how the decision was made in the first place.
> Thanks for your answers.
> 
> On Sat, Oct 18, 2003 at 11:17:26AM -0400, Erik Price wrote:
> 
>>Date: Sat, 18 Oct 2003 11:17:26 -0400
>>Subject: Re: [Tutor] python_naming_conventions - newbie
>>Cc: tutor@python.org
>>To: Rahul Kumar <rahulk@bhartitelesoft.com>
>>From: Erik Price <erikprice@mac.com>
>>X-Mailer: Apple Mail (2.552)
>>
>>
>>On Friday, October 17, 2003, at 01:51  AM, Rahul Kumar wrote:
>>
>>
>>>As someone learning python after several years of working on Java, i am
>>>interested to know why does python follow the
>>>lower_case_with_underscores way of naming methods and variables while
>>>Java follows the MixedCaseWithoutUnderscores.
>>
>>I don't know the answer why, but one of the more important suggestions 
>>made by both "Java Elements of Style" and IIRC the Python Style 
>>Guidelines is that convention is more important than aesthetics.  That 
>>is to say, while aesthetics certainly play a role (even in the very 
>>choice of a name for a variable), what is more important is to make 
>>sure that your naming is consistent with what is conventional for your 
>>project.  Java happens to have a well-known published style guide that 
>>strongly recommends that camelCase be used for variable names and 
>>UNDERSCORE_SEPARATORS only be used in [capitalized] constant 
>>declarations (static final String FOO).
>>
>>That said, my guess is that the reason why it was originally selected 
>>is probably because the extra underscores make the variable names 
>>wider.  This isn't as much an issue in Python because type and access 
>>declarations aren't used, but because you need to declare the access 
>>level and type/return type in Java, it ends up making your code lines 
>>wider.  Just yesterday I wrote this method signature:
>>
>>    private Mip mipFromFile(File mipFile)
>>
>>whereas in Python, it could have simply been declared as:
>>
>>    def mip_from_file(mip_file):
>>
>>As you can see, the Python version is still shorter even though I've 
>>used the underscores as separators.
>>
>>
>>>After writing a couple of py progs, i find myself using the python way
>>>in Java, and i prefer it (used to write C progs this way 10 yrs ago), 
>>>and
>>>i need some justification for this, since i am the guy who made the 
>>>Java
>>>guidelines for my org 4 years back !
>>
>>In Python I don't really stick to one or the other, but try to go with 
>>what seems most logical for the situation.  However, in Java my own 
>>preference is to simply stick to the official standard simply because 
>>when others read my code, that's probably what they'll expect to see.
>>
>>
>>Erik
>>
> 
> 

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Prometheus
  +                              kniht                                +

Fnord.


From xenacat3 at hotmail.com  Mon Oct 20 10:14:29 2003
From: xenacat3 at hotmail.com (Lisa Sullivan)
Date: Mon Oct 20 10:14:38 2003
Subject: [Tutor] Help understanding code
Message-ID: <Law11-F1014kqZ8RQDk0002a621@hotmail.com>

I am new to programming and I'm trying to teach myself Python via online 
tutorials.  I am

struggling with functions.  I wonder if someone could help me.
Here is the URL for the program I am trying to understand:
http://www.honors.montana.edu/~jjc/easytut/easytut/node10.html#SECTION001030000000000000000
I have worked through the program and I understand all but one line.  Below 
is an edited version

of my notes while I was working through understanding the program.
Let me know if I should post the program as well.

  if get_questions(questions[index]):
I don't understand this line.
It seems to move through the list stored in (questions) and determine 
whether or not to increase

right by 1.

Right should only be increased if the question was answered right, so:
That must be what the return statements in the check_question function are 
for.
It replaces the words get_questions with the value returned from running 
get_questions.
We set the variable true to equal 1 and the variable false to = 0.
  if get_questions(questions[index]):
now could say
if 1(questions[index]):
or
if 0(questions)[index]:

(questions) refers to the get_questions info sent to the run_test function 
that we are now inside

of.
and [index] refers to an entry in this list.  But which one?
Is index used to get the index variable we set above?
If so, then right will only be increased:
if 0 or 1(questions[current question]
In other words if the current question is answered correctly or incorrectly.
This doesn't make sense to me.
I don't understand how the program is progressing through the questions.
I don't see how it knows to skip the answers.
I know it has something to do with the fact that the questions and answers 
are stored in lists

that are inside of the main list.

I hope I'm not too far off here.
Thanks for your help.
Lisa

_________________________________________________________________
Add MSN 8 Internet Software to your current Internet access and enjoy 
patented spam control and more.  Get two months FREE!     
http://join.msn.com/?page=dept/byoa


From zach at zcsmith.com  Mon Oct 20 11:07:34 2003
From: zach at zcsmith.com (Zach Smith (Linux))
Date: Mon Oct 20 11:07:52 2003
Subject: [Tutor] Help understanding code
In-Reply-To: <Law11-F1014kqZ8RQDk0002a621@hotmail.com>
References: <Law11-F1014kqZ8RQDk0002a621@hotmail.com>
Message-ID: <3F93FA36.2030804@zcsmith.com>

Lisa Sullivan wrote:

> I am new to programming and I'm trying to teach myself Python via 
> online tutorials.  I am
>
> struggling with functions.  I wonder if someone could help me.
> Here is the URL for the program I am trying to understand:
> http://www.honors.montana.edu/~jjc/easytut/easytut/node10.html#SECTION001030000000000000000 
>
> I have worked through the program and I understand all but one line.  
> Below is an edited version
>
> of my notes while I was working through understanding the program.
> Let me know if I should post the program as well.
>
>  if get_questions(questions[index]):
> I don't understand this line.
> It seems to move through the list stored in (questions) and determine 
> whether or not to increase
>
If I'm understanding you right, you don't know why this performs what it 
does.  Any "if" statement reverts to true (asks if it is true).  In 
other words, it automatically implies true unless specifically stated 
otherwise.  Think of the line looking like this:

if get_questions(questions[index])=true then:
    run these statements/instructions

Like I said, there is an automatic implementation of true unless written 
otherwise, such as:

if get_questions(questions[index])=false then:
    run these statements/instructions

Hope this helps.

Zach


From project5 at redrival.net  Mon Oct 20 11:11:43 2003
From: project5 at redrival.net (Andrei)
Date: Mon Oct 20 11:14:04 2003
Subject: [Tutor] Re: Help understanding code
In-Reply-To: <Law11-F1014kqZ8RQDk0002a621@hotmail.com>
References: <Law11-F1014kqZ8RQDk0002a621@hotmail.com>
Message-ID: <bn0u3k$mec$1@sea.gmane.org>

Lisa Sullivan wrote:
> I am new to programming and I'm trying to teach myself Python via online 
> tutorials.  I am
> struggling with functions.  I wonder if someone could help me.

Functions are just chunks of code which have a name and may return a result.

> Here is the URL for the program I am trying to understand:
> http://www.honors.montana.edu/~jjc/easytut/easytut/node10.html#SECTION001030000000000000000 

<snip>

>  if get_questions(questions[index]):
> I don't understand this line.

> It seems to move through the list stored in (questions) and determine 
> whether or not to increase
> right by 1.

check_question asks the question, records the answer and compares the 
given answer to the correct one: if answer==given_answer. If the answer 
is correct, the function returns True (that snippet is old, in recent 
Python versions you should just use True and False, there's no need to 
define your own true/false). If the answer is incorrect it returns a False.

In run_test, "if check_question(question[index])" is then basically 
evaluated as "if the value returned by check_question is True, do the 
thing below".
In other words, if check_question returns a value which is evaluated as 
True in a boolean sense (most things are True except for 0, "", and 
other empty things), "right" is increased. If check_question returns a 
false, it does nothing.

> Right should only be increased if the question was answered right, so:
> That must be what the return statements in the check_question function 
> are for.

return statements stop the execution of the function and return whatever 
comes after them on the same line. check_question returns true (1) if 
the given answer is the same as the correct answer and false (0) otherwise.

> It replaces the words get_questions with the value returned from running 
> get_questions.

Yep.

> Is index used to get the index variable we set above?

index *is* the index variable set above.

> If so, then right will only be increased:
> if 0 or 1(questions[current question]

I don't understand this notation. It must be wrong, there is no "or" in 
its interpretation.

> In other words if the current question is answered correctly or 
> incorrectly.

Nope, see my explanation above.

> This doesn't make sense to me.
> I don't understand how the program is progressing through the questions.
> I don't see how it knows to skip the answers.

It doesn't skip the answers. It passes to check_question a list which 
looks like this:

["somequestion", "correctanswer"]
   ^-- index 0       ^-- index 1

In check_question, this is split into a question part and an answer part:

question = question_and_answer[0] # becomes "somequestion"
answer = question_and_answer[1] # becomes "correctanswer"

> I know it has something to do with the fact that the questions and 
> answers are stored in lists
> that are inside of the main list.

Yep. The main list contains 3 question-answer lists. The while loop in 
run_test accesses these items one by one, by increasing the index it's 
looking at the end of each loop. During each loop the question-answer 
list at the current index is passed to check_question and evaluated.

Yours,

Andrei



From idiot1 at netzero.net  Mon Oct 20 11:33:07 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Mon Oct 20 11:33:02 2003
Subject: [Tutor] Help understanding code
In-Reply-To: <Law11-F1014kqZ8RQDk0002a621@hotmail.com>
References: <Law11-F1014kqZ8RQDk0002a621@hotmail.com>
Message-ID: <3F940033.7070406@netzero.net>

OK, how about this?

def square(x):		# define the square function
	return x * x	# return the value of multiplying x by  itself

now in the definition X is an arguement passed to the function when you invoke 
it. For instance:

side=input('What is the sidelength of your square?')
area=square(side)
print 'The surface area of your square courtyard is ', x, 'units.'

notice that I passed a variable called 'side', NOT 'x'. However, in it's 
operation it  used a variable named x, and that variable was local- noplace else 
in the program could access it.

Any help as a beginning?


Lisa Sullivan wrote:

> I am new to programming and I'm trying to teach myself Python via online 
> tutorials.  I am
> 
> struggling with functions.  I wonder if someone could help me.
> Here is the URL for the program I am trying to understand:
> http://www.honors.montana.edu/~jjc/easytut/easytut/node10.html#SECTION001030000000000000000 
> 
> I have worked through the program and I understand all but one line.  
> Below is an edited version
> 
> of my notes while I was working through understanding the program.
> Let me know if I should post the program as well.
> 
>  if get_questions(questions[index]):
> I don't understand this line.
> It seems to move through the list stored in (questions) and determine 
> whether or not to increase
> 
> right by 1.
> 
> Right should only be increased if the question was answered right, so:
> That must be what the return statements in the check_question function 
> are for.
> It replaces the words get_questions with the value returned from running 
> get_questions.
> We set the variable true to equal 1 and the variable false to = 0.
>  if get_questions(questions[index]):
> now could say
> if 1(questions[index]):
> or
> if 0(questions)[index]:
> 
> (questions) refers to the get_questions info sent to the run_test 
> function that we are now inside
> 
> of.
> and [index] refers to an entry in this list.  But which one?
> Is index used to get the index variable we set above?
> If so, then right will only be increased:
> if 0 or 1(questions[current question]
> In other words if the current question is answered correctly or 
> incorrectly.
> This doesn't make sense to me.
> I don't understand how the program is progressing through the questions.
> I don't see how it knows to skip the answers.
> I know it has something to do with the fact that the questions and 
> answers are stored in lists
> 
> that are inside of the main list.
> 
> I hope I'm not too far off here.
> Thanks for your help.
> Lisa
> 
> _________________________________________________________________
> Add MSN 8 Internet Software to your current Internet access and enjoy 
> patented spam control and more.  Get two months FREE!     
> http://join.msn.com/?page=dept/byoa
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Prometheus
  +                              kniht                                +

Fnord.


From jim_938 at hotmail.com  Mon Oct 20 14:41:16 2003
From: jim_938 at hotmail.com (Jimmy verma)
Date: Mon Oct 20 14:41:22 2003
Subject: [Tutor] long-to-string
Message-ID: <Sea1-F141FkAvYSTzeC0001d176@hotmail.com>

I hope my message reached properly as i have not recieved any response!!!



>Hello,
>
>First of all thanks to tutor for providing their support. People on this 
>list are really helpful.
>
>Now I would like to discuss something about my problem::
>
>
>i have written a module to covert a 4 byte string into a long like this:
>
>>>>def makelong(chaine):
>...     # Make a long form a 4-byte string
>...     return 
>((ord(chaine[0])*256+ord(chaine[1]))*256+ord(chaine[2]))*256+ord(chaine[3])
>...
>>>># Now call the function we just defined:
>... makelong('oMAP')
>1867333968
>
>
>I packs this data with struct module
>
>using '>L' format
>
>I am able to unpack this and get the no from my file
>
>Now i want is to convert the no back into the string like 'oMAP' for which 
>this no was meant.
>
>I would welcome your suggestions on how should i move ahead.
>
>Thanks in advance.
>
>With best regards,
>
>J+
>
>_________________________________________________________________
>MSN Hotmail now on your Mobile phone. 
>http://server1.msn.co.in/sp03/mobilesms/ Click here.
>
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor

_________________________________________________________________
Celebrate Shakti. Send money to loved ones in India. 
http://server1.msn.co.in/sp03/navaratri/ Have a joyous Navratri.


From bwinton at latte.ca  Mon Oct 20 15:13:41 2003
From: bwinton at latte.ca (Blake Winton)
Date: Mon Oct 20 15:11:45 2003
Subject: [Tutor] long-to-string
In-Reply-To: <Sea1-F141FkAvYSTzeC0001d176@hotmail.com>
Message-ID: <007401c3973e$483eaf20$6401a8c0@phantomfiber.com>

I was going to reply, but frankly I just started eating my lunch,
and didn't read email over the weekend.  You might consider being
a little more patient if you send out your messages on a Saturday
or Sunday.

So, you want to convert a long to and from a 4-char string.

The conversion to a long (which you already did) can also be
written as:
>>> struct.unpack( ">l", 'oMAP' )
(1867333968,)

and since we only want the first thing, we write:
>>> struct.unpack( ">l", 'oMAP' )[0]
1867333968

Which leads me to think that the conversion from a long to the
string could be expressed as:
>>> struct.pack( ">l", 1867333968 )
'oMAP'

And we see from the result that it indeed can.

My one final warning is:  If this is intended to help in writing
a Palm program (where 4-character longs are used all over the
place), then you really want the little-endian version of "l" (or
"<l) instead of the big-endian version (or ">l").  If not, then
feel free to ignore this whole paragraph.

Later,
Blake.



> -----Original Message-----
> From: tutor-bounces@python.org 
> [mailto:tutor-bounces@python.org] On Behalf Of Jimmy verma
> Sent: Monday, October 20, 2003 2:41 PM
> To: tutor@python.org
> Subject: Re: [Tutor] long-to-string
> 
> 
> I hope my message reached properly as i have not recieved any 
> response!!!
> 
> 
> 
> >Hello,
> >
> >First of all thanks to tutor for providing their support. 
> People on this 
> >list are really helpful.
> >
> >Now I would like to discuss something about my problem::
> >
> >
> >i have written a module to covert a 4 byte string into a 
> long like this:
> >
> >>>>def makelong(chaine):
> >...     # Make a long form a 4-byte string
> >...     return 
> >((ord(chaine[0])*256+ord(chaine[1]))*256+ord(chaine[2]))*256+
> ord(chaine[3])
> >...
> >>>># Now call the function we just defined:
> >... makelong('oMAP')
> >1867333968
> >
> >
> >I packs this data with struct module
> >
> >using '>L' format
> >
> >I am able to unpack this and get the no from my file
> >
> >Now i want is to convert the no back into the string like 
> >'oMAP' for which this no was meant.
> >
> >I would welcome your suggestions on how should i move ahead.


From jim_938 at hotmail.com  Mon Oct 20 15:32:39 2003
From: jim_938 at hotmail.com (Jimmy verma)
Date: Mon Oct 20 15:32:44 2003
Subject: [Tutor] long-to-string
Message-ID: <Sea1-F169UkY2Bv4YOs0001d5a8@hotmail.com>

Thanks a lot for responding.  I am able to get what i was looking for. I 
have packed the long no again in order to get the required string. Can you 
please explain a bit more on this. Though I got the result but have not 
understood properly why it happened. I converted my string to a long with 
the function i wrote. and same thing can be done with unpack.


>The conversion to a long (which you already did) can also be
>written as:
> >>> struct.unpack( ">l", 'oMAP' )
>(1867333968,)



>
>and since we only want the first thing, we write:
> >>> struct.unpack( ">l", 'oMAP' )[0]
>1867333968
>
>Which leads me to think that the conversion from a long to the
>string could be expressed as:
> >>> struct.pack( ">l", 1867333968 )
>'oMAP'

What happened here???? Not fully clear!!!

Waiting for your expert suggestions.

Thanks again for your kind support.


With best regards,

James

PS:  Sorry for a bit of hurry in sending my mail again.

_________________________________________________________________
Buy now! Receive a gold coin on Dhan Teras. 
http://server1.msn.co.in/features/general/dhanteras/index.asp Celebrate 
prosperity!


From john at duartedailey.org  Mon Oct 20 18:37:09 2003
From: john at duartedailey.org (John Duarte)
Date: Mon Oct 20 18:37:16 2003
Subject: [Tutor] 2nd Python Book
Message-ID: <200310201537.09775.john@duartedailey.org>

I have seen recommendations for a first Python book, ie Alan Guald's Learn to 
Program Using Python, and Lutz & Asher's Learning Python. (Which are both 
terrific books!)

I was wondering if anyone could recommend a '2nd book'.

I was glancing through Deitel & Deitel's How to Program Python, and it looks 
very thorough. Are their any opinions about this book specifically.

Thank you.
John

From pythontutor at venix.com  Mon Oct 20 19:32:17 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Mon Oct 20 19:32:27 2003
Subject: [Tutor] 2nd Python Book
In-Reply-To: <200310201537.09775.john@duartedailey.org>
References: <200310201537.09775.john@duartedailey.org>
Message-ID: <3F947081.8010408@venix.com>

You need to know what you're trying to accomplish to make a good choice.

Python in a Nutshell provides a terrific reference for the language with
short examples and sage advice.

Text Processing in Python has a much narrower focus, but provides some
in depth coverage of problem domains where Python is a great tool for
writing solutions.

Python Programming on Win32 is essential if you need to cater to the
world of windows.

Programming Python has lots of sample code with detailed discussion.


Python in a Nutshell sits by my keyboard.  I find it invaluable.

John Duarte wrote:

> I have seen recommendations for a first Python book, ie Alan Guald's Learn to 
> Program Using Python, and Lutz & Asher's Learning Python. (Which are both 
> terrific books!)
> 
> I was wondering if anyone could recommend a '2nd book'.
> 
> I was glancing through Deitel & Deitel's How to Program Python, and it looks 
> very thorough. Are their any opinions about this book specifically.
> 
> Thank you.
> John
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582


From glingl at aon.at  Mon Oct 20 19:37:36 2003
From: glingl at aon.at (Gregor Lingl)
Date: Mon Oct 20 19:39:28 2003
Subject: [Tutor] 2nd Python Book
In-Reply-To: <3F947081.8010408@venix.com>
References: <200310201537.09775.john@duartedailey.org>
	<3F947081.8010408@venix.com>
Message-ID: <3F9471C0.3040204@aon.at>



Lloyd Kvam schrieb:

> You need to know what you're trying to accomplish to make a good choice.
>
> Python in a Nutshell provides a terrific reference for the language with
> short examples and sage advice.
>
> Text Processing in Python has a much narrower focus, but provides some
> in depth coverage of problem domains where Python is a great tool for
> writing solutions.
>
> Python Programming on Win32 is essential if you need to cater to the
> world of windows.
>
> Programming Python has lots of sample code with detailed discussion.
>
>
> Python in a Nutshell sits by my keyboard.  I find it invaluable.

May I additionally sugest, that the Python Cookbook is an invaluable
source of true Python philosophy. Lots of small, very interesting *and*
useful recipes ("mind size bites").
And (most of it and more of it) also available  online:
http://aspn.activestate.com/ASPN/Python/Cookbook/

Regards, Gregor
P.S. Editor was Alex Martelli, author of ython in a nutshell

>
> John Duarte wrote:
>
>> I have seen recommendations for a first Python book, ie Alan Guald's 
>> Learn to Program Using Python, and Lutz & Asher's Learning Python. 
>> (Which are both terrific books!)
>>
>> I was wondering if anyone could recommend a '2nd book'.
>>
>> I was glancing through Deitel & Deitel's How to Program Python, and 
>> it looks very thorough. Are their any opinions about this book 
>> specifically.
>>
>> Thank you.
>> John
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor@python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>


From carroll at tjc.com  Mon Oct 20 21:30:40 2003
From: carroll at tjc.com (Terry Carroll)
Date: Mon Oct 20 21:30:54 2003
Subject: [Tutor] 2nd Python Book
In-Reply-To: <200310201537.09775.john@duartedailey.org>
Message-ID: <Pine.LNX.4.44.0310201827580.31258-100000@violet.rahul.net>

On Mon, 20 Oct 2003, John Duarte wrote:

> I have seen recommendations for a first Python book, ie Alan Guald's Learn to 
> Program Using Python, and Lutz & Asher's Learning Python. (Which are both 
> terrific books!)
> 
> I was wondering if anyone could recommend a '2nd book'.

I like Martelli's "Python in a Nutshell" as a second book.  It bridges the 
gap between typical instruction and reference quite well.

Some like Lutz's "Programming Python," but I found it completely
frustrating; but that might just be me.  As I said, others do like it.

For a third book, I like the Python Cookbook.

-- 
Terry Carroll
Santa Clara, CA
carroll@tjc.com 


From tbstep at tampabay.rr.com  Mon Oct 20 22:01:50 2003
From: tbstep at tampabay.rr.com (Todd Stephens)
Date: Mon Oct 20 22:06:01 2003
Subject: [Tutor] 2nd Python Book
In-Reply-To: <200310201537.09775.john@duartedailey.org>
References: <200310201537.09775.john@duartedailey.org>
Message-ID: <200310202201.50907.tbstep@tampabay.rr.com>

On Monday 20 October 2003 06:37 pm, John Duarte wrote:

>  I was wondering if anyone could recommend a '2nd book'.
>
>  I was glancing through Deitel & Deitel's How to Program Python, and
> it looks very thorough. Are their any opinions about this book
> specifically.

I tried a few books to start with.  Most were pretty good for getting 
started, but the best I have found so far is "Practical Python" by 
Magnus Lie Hetland.  This is a good first *and* second book.  If you 
use the sample projects from the book as learning tools, it is also a 
good third book, IMO.

-- 
Todd Stephens
"Good people do not need laws to tell them to act responsibly, 
while bad people will find a way around the laws." - Plato


From idiot1 at netzero.net  Tue Oct 21 00:38:40 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Tue Oct 21 00:38:42 2003
Subject: [Tutor] 2nd Python Book
In-Reply-To: <200310201537.09775.john@duartedailey.org>
References: <200310201537.09775.john@duartedailey.org>
Message-ID: <3F94B850.4020502@netzero.net>

Learning Python.

John Duarte wrote:

> I have seen recommendations for a first Python book, ie Alan Guald's Learn to 
> Program Using Python, and Lutz & Asher's Learning Python. (Which are both 
> terrific books!)
> 
> I was wondering if anyone could recommend a '2nd book'.
> 
> I was glancing through Deitel & Deitel's How to Program Python, and it looks 
> very thorough. Are their any opinions about this book specifically.
> 
> Thank you.
> John
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Prometheus
  +                              kniht                                +

Fnord.


From david at graniteweb.com  Tue Oct 21 00:48:49 2003
From: david at graniteweb.com (David Rock)
Date: Tue Oct 21 00:48:53 2003
Subject: [Tutor] 2nd Python Book
In-Reply-To: <200310201537.09775.john@duartedailey.org>
References: <200310201537.09775.john@duartedailey.org>
Message-ID: <20031021044848.GA15903@wdfs.graniteweb.com>

* John Duarte <john@duartedailey.org> [2003-10-20 15:37]:
> I have seen recommendations for a first Python book, ie Alan Guald's Learn to 
> Program Using Python, and Lutz & Asher's Learning Python. (Which are both 
> terrific books!)
> 
> I was wondering if anyone could recommend a '2nd book'.
> 
> I was glancing through Deitel & Deitel's How to Program Python, and it looks 
> very thorough. Are their any opinions about this book specifically.

The Deitel & Deitel book is a good starting point. I would consider it
another '1st book'. Once you get past the basics, I find that I spend
most of my time on the python.org website, personally. The Python
Cookbook is good for insights into how to "think python", but the best
reference is still the current docs on the website.

-- 
David Rock
david@graniteweb.com
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20031020/c275c4e1/attachment.bin
From gventer at fish.co.uk  Tue Oct 21 02:09:19 2003
From: gventer at fish.co.uk (Gerhard)
Date: Tue Oct 21 02:09:12 2003
Subject: [Tutor] this is ugly
Message-ID: <3F94CD8F.3070105@fish.co.uk>

Dear list

Can line 3 of the following be improved (especially since I might want 
to search for even more strings within each line):

myfile=open(r'F:\logs\myfile.txt', 'r')
for line in myfile.readlines():
   if line.find("KeC 923") != -1 or line.find("ZEF 156") != -1 or 
line.find("pBX 88347") != -1 or line.find("FZX 17255") != -1:
         #code if found


Thanks
Gerhard


From glingl at aon.at  Tue Oct 21 02:36:30 2003
From: glingl at aon.at (Gregor Lingl)
Date: Tue Oct 21 02:38:21 2003
Subject: [Tutor] this is ugly
In-Reply-To: <3F94CD8F.3070105@fish.co.uk>
References: <3F94CD8F.3070105@fish.co.uk>
Message-ID: <3F94D3EE.6090202@aon.at>



Gerhard schrieb:

> Dear list
>
> Can line 3 of the following be improved (especially since I might want 
> to search for even more strings within each line):
>
> myfile=open(r'F:\logs\myfile.txt', 'r')
> for line in myfile.readlines():
>   if line.find("KeC 923") != -1 or line.find("ZEF 156") != -1 or 
> line.find("pBX 88347") != -1 or line.find("FZX 17255") != -1:
>         #code if found
>
A quick suggestion:

    if -1 not in [line.find(x) for x in ["KeC 923","ZEF 156","pBX 
88347","FZX 17255"]]:
        # etc.

(untested, of course)
Gregor

>
> Thanks
> Gerhard
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>


From glingl at aon.at  Tue Oct 21 02:48:13 2003
From: glingl at aon.at (Gregor Lingl)
Date: Tue Oct 21 02:50:37 2003
Subject: OOPS -  Re: [Tutor] this is ugly
Message-ID: <3F94D6AD.6040601@aon.at>


>   if line.find("KeC 923") != -1 or line.find("ZEF 156") != -1 or 
> line.find("pBX 88347") != -1 or line.find("FZX 17255") != -1:
>         #code if found
>
A quick suggestion:

   if -1 not in :
       # etc.

THIS SUGGESTIION WAS WRONG (error in boolean logic - what a shame!)

perhaps you like the the less nice 

   
   if [line.find(x) for x in 
         ["KeC 923","ZEF 156","pBX 88347","FZX 17255"]] != [-1]*4
 ?

    things = ["KeC 923","ZEF 156","pBX 88347","FZX 17255"]
    if sum([line.find(thing) for thing in things]) != -len(things)

sum is a built-in function since Python 2.3

Sorry for the inconvenience, I'm in a hurry
Gregor

>
> Thanks
> Gerhard
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>



From jjhegde at ncst.ernet.in  Tue Oct 21 04:05:21 2003
From: jjhegde at ncst.ernet.in (Jayprasad J. Hegde)
Date: Tue Oct 21 04:04:48 2003
Subject: [Tutor] Yet another question on Python and XML
In-Reply-To: <3F94D6AD.6040601@aon.at>
References: <3F94D6AD.6040601@aon.at>
Message-ID: <20031021080521.GA4947@sarathi.ncst.ernet.in>

Hello folks, 

You must have seen this question many times:
Could you give me pointers to some *good* source for studying XML
processing--DOM, especially--using Python?

I am sure that one of the answers would be the "PyXML HowTo". But IMO,
it is good as an overview article and I have struggled with getting an
in-depth understanding of the details. 

So, an additional criteria would most definitely be this: something which
is a bit more elaborate. Pointers to websites rather than books would
be appreciated.

Regards and thanks, 
- JJH
-- 
Comedy, like Medicine, was never meant to be practiced by the general
public.

From ms_barry2000 at yahoo.com  Tue Oct 21 05:40:42 2003
From: ms_barry2000 at yahoo.com (Marc Barry)
Date: Tue Oct 21 05:40:46 2003
Subject: [Tutor] Public, private and protected member variables.
Message-ID: <20031021094042.58659.qmail@web11702.mail.yahoo.com>

Danny, thanks for the help. Please see my comments
below. Note that my email address has changed.


>From: Danny Yoo <dyoo@hkn.eecs.berkeley.edu>
>To: Marc Barry <marc_barry@hotmail.com>
>CC: tutor@python.org
>Subject: Re: [Tutor] Public, private and protected
member variables.
>Date: Fri, 17 Oct 2003 10:22:05 -0700 (PDT)
>
>
>
>On Fri, 17 Oct 2003, Marc Barry wrote:
>
> > I have a question regarding the existence of
protected members in
> > Python.  Basically, in a language like Java we
have public, private and
> > protected member variables.
>
>Hi Mark,
>
>(Tangential note: In some programming languages all
member variables are
>private by default.  Objective C is one example.)
>
>
> > Here is a simple example:
> >
> >
#------------------------------------------------------------
> > class Car:
> > 	def __init__(self, colour):
> > 		self.__colour = colour
> >
> >
> > class Ferrari(Car):
> > 	def __init__(self, model, colour):
> >
> > 		Car.__init__(self, colour)
> > 		self.__model = model
> >
> > 	def printColour(self):
> > 		print self.__colour
> >
> > a_ferrari = Ferrari("Enzo", "Red")
> > print dir(a_ferrari)
> > a_ferrari.printColour()
>
>
> > But in Python I only know of public and private. I
would like to inherit
> > from a class and be able to modify parent member
variables, but I would
> > not like any class that doesn't inherit from the
parent to be able to
> > modify the member variables (i.e. Protected
concept in Java).
>
>Python's variable protection is handled by
convention, not law.  The
>Python Style essay says that if we want to specify
"protected"-style
>status, we can use a single underscore in the front
of the name:
>

Thanks for the the style essay. I am now following its
recommendations.

>     http://www.python.org/doc/essays/styleguide.html
>
>So the informal way to handle this might be something
like this:
>
>###
>class Car:
>     def __init__(self, colour):
>         self._colour = colour
>
>class Ferrari(Car):
>     def __init__(self, model, colour):
>         Car.__init__(self, colour)
>         self.__model = model
>
>     def printColour(self):
>         print self._colour
>###
>
>
>I know this is a toy example, but it might be better
to "pull up"  the
>printColour() method into the parent, and avoid the
visibility problems
>altogether:

Yes, this was a bad example on my part. I should have
just spent the time and gave more detail on the class
I needed the help with.

>
>###
>class Car:
>     def __init__(self, colour):
>         self.__colour = colour
>
>     def printColour(self):
>         print self.__colour
>
>
>class Ferrari(Car):
>     def __init__(self, model, colour):
>         Car.__init__(self, colour)
>         self.__model = model
>###
>
>
>
> > If I expose a variable in Car as public, then I
will allow users of the
> > class to modify it directly. I would like to avoid
this since that fixes
> > my implementation to being always having to
provide a variable named
> > "colour"  for example. Also, this is just a
simplification of my problem
> > as my class is much more complicated with a lot of
gettable and settable
> > properties in the parent object (Which I want to
inherit).
>
>
>If you'd like, please feel free to talk about object
design on the Tutor
>list.  It's one of those things I'd like to learn
more about myself.
>*grin*  Perhaps it might be possible to avoid
exposing so many properties
>by reworking the design a little?
>
>I think we had a recent discussion about this
subject, and one thing that
>came up was Java's influence was making people
overdesign their classes to
>use setFoo/getFoo everywhere.  Folks on the list also
talked a bit about
>the variable visibility stuff that you're interested
in:
>
>    
http://mail.python.org/pipermail/tutor/2003-October/025599.html
>

I do find myself using a lot of setFoo and getFoo. I
too would like to better understand how to design
classes to get around this problem. Right now, I have
a class that I reuse in many different situations and
depending on the situation the class requires
different properties. Basically, what I have done is I
use a dictionary inside the class that uses a string
as the key and any object as a value. Therefore, I
have methods of the form:

setProperty(key, value)
getProperty(key)

I cannot come up with a better way to design the class
to avoid using these types of accessor functions. I
hear many comments that this type of design is ugly
and lots of people hate getFoo/setFoo, but I guess I
can't seem to find a better way to handle the type of
situation where you have an object that has different
properties depending on the situation it is used.

>
>Good luck to you!
>

Once again, thanks for your help.

__________________________________
Do you Yahoo!?
The New Yahoo! Shopping - with improved product search
http://shopping.yahoo.com

From ms_barry2000 at yahoo.com  Tue Oct 21 08:34:49 2003
From: ms_barry2000 at yahoo.com (Marc Barry)
Date: Tue Oct 21 08:34:55 2003
Subject: [Tutor] Public, private and protected member variables.
Message-ID: <20031021123449.99844.qmail@web11708.mail.yahoo.com>

Thanks for your feedback Alan. 

I guess my reasoning for most of my statements comes from all of those Java
design principles that I have become so accustomed too. I am now beginning to
understand the Python handles these types of things. I remember being very
confused in the beginning with iterators under Python. I searched through the
documentation and all that was stated was an iterator protocol. I was looking
for some sort of interface. Now the concept makes complete sense to me. I guess
like the iterator protocol, I will just state in the documentation which
objects and variables should not be modified and which methods control internal
state and leave it up to the programmer to abide by the "protocol".

I think that I too am becoming accustomed to the Pythonic ways.

Alan, thanks for the comments. I come from the background of Java, which is
very strict and it has made Python feel somewhat unnatural to me. Although, the
more often I use Python the more it grows on me.

Regards,

Marc

>From: "Alan Gauld" <alan.gauld@blueyonder.co.uk>
>To: "Marc Barry" <marc_barry@hotmail.com>,<tutor@python.org>
>Subject: Re: [Tutor] Public, private and protected member variables.
>Date: Fri, 17 Oct 2003 23:45:43 +0100
>
> > I have a question regarding the existence of protected members in
>Python.
>
>We had a longish thread on variable scoping in Python just recently,
>try searching the archives.
>
> > Basically, in a language like Java we have public, private and
>protected
> > member variables.
>
>Indeed, Java copied the concept from C++ which introduced it
>in version 2, partly to help manage complexity in the face of
>multiple inheritance(also introduced in version 2).
>
> > But in Python I only know of public and private.
>
>And even private can be bypassed fairly easily (as it can
>in C++!) and in practice public variables are the norm.
>
> > inherit from a class and be able to modify parent member variables,
> > but I would not like any class that doesn't inherit from the parent
> > to be able to modify the member variables
>
>Why? Apart from paranoia born from exposure to languages
>like C++ and Java(which as I say just played copycat?)
>
>OO programmers have been using inheritance for many years
>without protected scopes (and originally often without
>private either!) and it very rarely causes problems.
>If you really do need to hide the variables completely
>then simply make them private and then provide accessor
>functions(yuk!) or make them properties(slightly better).
>The accessor can if you really want to, check the immediate
>parent of the calling class...if you really want to...
>
>But do you habitually find yourself breaking your own design
>by trying to directly access internal state? Or do you really
>distrust your fellow programmers that much? And what about
>the occasions when internal access is actually needed by
>a non child class? C++ provides the friend construct,
>should Python do likewise?
>
>Its easier to just go with the flow when using a new language.
>One of the reasons that C++ and Java are so verbose and
>difficult to use is that they introduce all manner of
>artificial restictions which programmers have to work around.
>(And I say that as someone who used C++ almost exclusively
>from 1988 through to 1996 - then I found Delphi, hooray!
>Then I found Python, double hooray! And I haven't written
>any serious C++ since 1999. And I studiously avoid Java as
>much as possible) Python tries to make the programmers life
>easy at the expense of expecting a little courtesy to be
>exercised.
>
> > If I expose a variable in Car as public ,then I will allow users of
>the
> > class to modify it directly. I would like to avoid this since that
>fixes my
> > implementation to being always having to provide a variable named
>"colour"
> > for example.
>
>If that's your concern you could override setattr and getattr
>to prevent access to anything that wasn't a method. That
>way all attributes are private. Then you have to provide
>accessor functions - is that really any better?
>
>Alternatively, in your documentation just tell users not
>to access the attributes directly. And that doing so may result
>in undefined behaviour!
>
> > is much more complicated with a lot of gettable and settable
>properties in
> > the parent object (Which I want to inherit).
>
>Yep, that's why lots of gettable/settable properties are a pain.
>See the previous thread... Sorry but the gettable/settable stuff
>is one of my hot buttons :-(
>
>Alan G
>Author of the Learn to Program web tutor
>http://www.freenetpages.co.uk/hp/alan.gauld
>

__________________________________
Do you Yahoo!?
The New Yahoo! Shopping - with improved product search
http://shopping.yahoo.com

From pythontutor at venix.com  Tue Oct 21 10:36:32 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Tue Oct 21 10:36:43 2003
Subject: [Tutor] Public, private and protected member variables.
In-Reply-To: <20031021094042.58659.qmail@web11702.mail.yahoo.com>
References: <20031021094042.58659.qmail@web11702.mail.yahoo.com>
Message-ID: <3F954470.20703@venix.com>

Marc Barry wrote:

> I do find myself using a lot of setFoo and getFoo. I
> too would like to better understand how to design
> classes to get around this problem. Right now, I have
> a class that I reuse in many different situations and
> depending on the situation the class requires
> different properties. Basically, what I have done is I
> use a dictionary inside the class that uses a string
> as the key and any object as a value. Therefore, I
> have methods of the form:
> 
> setProperty(key, value)
> getProperty(key)
> 
> I cannot come up with a better way to design the class
> to avoid using these types of accessor functions. I
> hear many comments that this type of design is ugly
> and lots of people hate getFoo/setFoo, but I guess I
> can't seem to find a better way to handle the type of
> situation where you have an object that has different
> properties depending on the situation it is used.
> 
Python has built in functions getattr(obj, key) and setattr(obj,key,value)
that are generic equivalents to the get/setProperty methods except that
you must supply the object.

If the property names are known when you are writing your code, you can simply
create attributes in a class by assigning to the attribute name:
	some_obj.foo = "some value"
The object: some_obj now has a new attribute: foo.

I have a "generic" class for dealing with database tables.  When connected to
a specific database table, the list of fieldnames are determined and stored
with the class.  The __setattr__ method verifies attribute names are valid
for this table and keeps a list of changed attributes for INSERTs and UPDATEs.
The __getattr__ method will catch references to database fields that are not yet
assigned/defined and return None.  For other attribute names it raises an
AttributeError.

If it is necessary to enforce some consistancy between fields,
e.g. startdate < enddate, this can be done in the __setattr__ method.

(Most of these ideas were borrowed from examples in Python Programming
on Win32)

The good side of this approach:
	easy to read object references (obj.attribute)
	reasonable enforcement of object requirements
	fewer methods to write

The bad side:
	__setattr__ can become complex to maintain
	encourages habit of direct manipulation of attributes

Once I start grabbing attributes, I can go overboard.  A simple example:
build a formatted string for a customer record by writing code that grabs
cust.firstname and cust.lastname and so on.  The better approach is to have a
customer method that returns the formatted string.  Then the logic is written once
and placed where you would expect to find it.

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582


From sigurd at 12move.de  Tue Oct 21 10:46:48 2003
From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Tue Oct 21 10:50:45 2003
Subject: [Tutor] this is ugly
In-Reply-To: <3F94CD8F.3070105@fish.co.uk> (Gerhard's message of "Tue, 21
	Oct 2003 07:09:19 +0100")
References: <3F94CD8F.3070105@fish.co.uk>
Message-ID: <m3d6cqlkvi.fsf@hamster.pflaesterer.de>

On 21 Oct 2003, Gerhard <- gventer@fish.co.uk wrote:

> Can line 3 of the following be improved (especially since I might want
> to search for even more strings within each line):

> myfile=open(r'F:\logs\myfile.txt', 'r')
> for line in myfile.readlines():
>    if line.find("KeC 923") != -1 or line.find("ZEF 156") != -1 or
>    line.find("pBX 88347") != -1 or line.find("FZX 17255") != -1:
>          #code if found

You could write a simple function which calls the find method.

def myfind(s, *args):
    sf = s.find
    for x in args:
        if sf(x) != -1: return True
    return False


myfile=open(r'F:\logs\myfile.txt', 'r')
for line in myfile.readlines():
    if myfind(line,
              "KeC 923",
              "ZEF 156",
              "pBX 88347",
              "FZX 17255")
         #code if found



   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


From guillermo.fernandez at epfl.ch  Tue Oct 21 12:05:29 2003
From: guillermo.fernandez at epfl.ch (Guillermo Fernandez)
Date: Tue Oct 21 12:06:47 2003
Subject: [Tutor] Unimporting modules
Message-ID: <3F955949.50603@epfl.ch>

Hi,

I'm trying to unimport modules.

I try into the python interactive command line
import os
del os
and it works just fine.

But when I enter it into a function, it creates me problems.

import os

def run():
     try:
         global os
         del os
     finally:
         import os

and it makes me errors...

Could someone point me where and why I'm wrong?

Thanks,

Guille


From amk at amk.ca  Tue Oct 21 12:33:37 2003
From: amk at amk.ca (amk@amk.ca)
Date: Tue Oct 21 12:33:43 2003
Subject: [Tutor] Unimporting modules
In-Reply-To: <3F955949.50603@epfl.ch>
References: <3F955949.50603@epfl.ch>
Message-ID: <20031021163337.GB29550@rogue.amk.ca>

On Tue, Oct 21, 2003 at 06:05:29PM +0200, Guillermo Fernandez wrote:
> I'm trying to unimport modules.

This isn't possible, in general.  A statement such as "del os" deletes the
binding for the name 'os' in the current namespace, but it doesn't remove
the module from sys.modules or free up the space used by its code.

--amk


From jeff at ccvcorp.com  Tue Oct 21 12:58:05 2003
From: jeff at ccvcorp.com (Jeff Shannon)
Date: Tue Oct 21 12:54:06 2003
Subject: [Tutor] Unimporting modules
In-Reply-To: <3F955949.50603@epfl.ch>
References: <3F955949.50603@epfl.ch>
Message-ID: <3F95659D.80304@ccvcorp.com>

Guillermo Fernandez wrote:
> Hi,
> 
> I'm trying to unimport modules.
> [...]

As Andrew Kuchling already said, that's not generally possible.  My 
question for you is, *why* do you want to do this?  Is there something 
that you're trying to accomplish by it?  If so, there may be some 
other way to do that.

For instance, if you're trying to "unimport" a module so that you can 
then reimport it and make changes to the module show up, you can do 
that by calling reload(module).  If you have some other goal, there's 
likely another way to accomplish that, too.

Jeff Shannon
Technician/Programmer
Credit International


From jeff at ccvcorp.com  Tue Oct 21 13:24:31 2003
From: jeff at ccvcorp.com (Jeff Shannon)
Date: Tue Oct 21 13:20:22 2003
Subject: [Tutor] Unimporting modules
In-Reply-To: <3F9568AA.7050909@epfl.ch>
References: <3F955949.50603@epfl.ch> <3F95659D.80304@ccvcorp.com>
	<3F9568AA.7050909@epfl.ch>
Message-ID: <3F956BCF.8080708@ccvcorp.com>

Hi Guillermo,

I don't know anything about how pdb works (PythonWin's integrated 
debugger is pretty much the only one I've used), so I can't really 
offer specific advice.  (If breakpoints are being retained even after 
Python is exited and restarted, then I doubt that reload()ing modules 
will help much -- maybe there's some data file that pdb is using?) 
I'm forwarding this back to the list, in hopes that someone else there 
will have some ideas...

Guillermo Fernandez wrote:

> Hi,
> 
> Thanks for the answer.
> 
> I'm trying to integrate the pdb into the editor spe
> (http://projects.blender.org/projects/spe/)
> 
> The problem is I start the python (and it works well) but when I start 
> it again, he keeps in memory all the breakpoints that I setted in the 
> previous session. I thought that to clear those, I could delete the 
> module and import it again...
> 
> Here is the Shell output:
>  >>>     # I start the debugger with Crt-P
> Running 'C:\Python23\Lib\site-packages\sm\pdbtest.py' ...
>  > <string>(1)?()
> Breakpoint 1 at c:\python23\lib\site-packages\sm\pdbtest.py:5
> (Pdb) q
> Script 'pdbtest.py' returned exit code 0
>  >>>     # I start again the debugger with Crt-P
> Running 'C:\Python23\Lib\site-packages\sm\pdbtest.py' ...
>  > <string>(1)?()
> Breakpoint 2 at c:\python23\lib\site-packages\sm\pdbtest.py:5
> (Pdb) break
> Num Type         Disp Enb   Where
> 1   breakpoint    keep yes at c:\python23\lib\site-packages\sm\pdbtest.py:5
> 2   breakpoint    keep yes at c:\python23\lib\site-packages\sm\pdbtest.py:5
> (Pdb) q
> Script 'pdbtest.py' returned exit code 0
>  >>>
> 
> As you can see, when I start again the debugger, the breakpoint added 
> has number 1 still there (I do a break and the 2 are listed...). I would 
> like to have a brand new instance of the debugger at each start :-)
> 
> I tried to reload pdb with:
>     try:
>         global pdb
>         del pdb
>     finally:
>         import pdb
> and I did the same with spedb (I extended pdb in the class spedb to 
> include breaks automatically at the start of the debugger).
> 
> Thanks in advance!
> 
> Guille
> 
> Jeff Shannon wrote:
> 
>> Guillermo Fernandez wrote:
>>
>>> Hi,
>>>
>>> I'm trying to unimport modules.
>>> [...]
>>
>>
>>
>> As Andrew Kuchling already said, that's not generally possible.  My 
>> question for you is, *why* do you want to do this?  Is there something 
>> that you're trying to accomplish by it?  If so, there may be some 
>> other way to do that.
>>
>> For instance, if you're trying to "unimport" a module so that you can 
>> then reimport it and make changes to the module show up, you can do 
>> that by calling reload(module).  If you have some other goal, there's 
>> likely another way to accomplish that, too.
>>
>> Jeff Shannon
>> Technician/Programmer
>> Credit International
>>
> 



From dyoo at hkn.eecs.berkeley.edu  Tue Oct 21 13:54:15 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Oct 21 13:54:20 2003
Subject: [Tutor] this is ugly
In-Reply-To: <3F94CD8F.3070105@fish.co.uk>
Message-ID: <Pine.LNX.4.44.0310211039490.28719-100000@hkn.eecs.berkeley.edu>



On Tue, 21 Oct 2003, Gerhard wrote:

> Can line 3 of the following be improved (especially since I might want
> to search for even more strings within each line):
>
> myfile=open(r'F:\logs\myfile.txt', 'r')
> for line in myfile.readlines():
>    if line.find("KeC 923") != -1 or line.find("ZEF 156") != -1 or
> line.find("pBX 88347") != -1 or line.find("FZX 17255") != -1:
>          #code if found

Hi Gerhard,

If the number of strings is a bit longer, perhaps a regular expression
might be applicable?  Also, it might be useful to write some function that
takes a bunch of keywords, as well as the text, and does the
mass-searching for us.  That may help the readability of the code.

Here's an example of one keyword-finding function:

###
>>> import re
>>> def find_keywords(keywords, text):
...     """Returns true if any of the keywords exist in the text."""
...     pattern = "|".join(map(re.escape, keywords))
...     return re.search(pattern, text)
...
>>> find_keywords(['alpha', 'beta', 'gamma', 'delta', 'epsilon'],
...               "this is an alpha test")
<_sre.SRE_Match object at 0x16e860>
>>> find_keywords(['alpha', 'beta', 'gamma', 'delta', 'epsilon'],
...               "this is a test")
>>>
###

Karl's approach is similar to this.  So even if you don't use regular
expressions, at least use functions.  *grin*


Good luck to you!


From charlie at begeistert.org  Tue Oct 21 15:27:49 2003
From: charlie at begeistert.org (Charlie Clark)
Date: Tue Oct 21 15:27:12 2003
Subject: [Tutor] this is ugly
In-Reply-To: <E1ABz2J-0007jx-Uo@mail.python.org>
References: <E1ABz2J-0007jx-Uo@mail.python.org>
Message-ID: <20031021212749.3006.11@bepc.gormenghast>

> 
> > Can line 3 of the following be improved (especially since I might 
want 
> > to search for even more strings within each line):
> 
> > myfile=open(r'F:\logs\myfile.txt', 'r')
> > for line in myfile.readlines():
> >    if line.find("KeC 923") != -1 or line.find("ZEF 156") != -1 or 
> >    line.find("pBX 88347") != -1 or line.find("FZX 17255") != -1:
> >          #code if found

These methods are fine but regular expressions are much better for this 
task. Danny Yoo gave me some help on using re.compile() earlier this 
year so if you check the archives you should find what you need.

Charlie

From alan.gauld at blueyonder.co.uk  Tue Oct 21 17:27:05 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Tue Oct 21 17:26:29 2003
Subject: [Tutor] 2nd Python Book
References: <200310201537.09775.john@duartedailey.org>
Message-ID: <002901c3981a$139947d0$6401a8c0@xp>


> I have seen recommendations for a first Python book,
> ie Alan Guald's Learn to Program Using Python,

Thanks for the plug :-)

> I was glancing through Deitel & Deitel's How to Program Python, and
it looks
> very thorough. Are their any opinions about this book specifically.

HTPP is a good "advanced intro". It covers a huge amount of
ground but, in my opinion, stops just short of being useful
in any of them. It gives a taster in loys of things but if
you venture out on your own you'll find yourself struggling
I suspect.

Lutz's Programming Python 2nd ed is less broad but much more
detailed in the areas it covers and would be my choice for
a general book. However really I'd suggest picking a subject
area and buying a book for that - Win32 programming,
Tkinter, Web/XML, Database(MySQL say), Text processing etc.

There are specialist books on each of these areas.

Plus of course one of the must have references: Either
"Python in a Nutshell" or "Python Essential reference".

The Nutshell is the most recent but both are good, I
have both!

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


From alan.gauld at blueyonder.co.uk  Tue Oct 21 17:31:01 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Tue Oct 21 17:30:25 2003
Subject: [Tutor] this is ugly
References: <3F94CD8F.3070105@fish.co.uk>
Message-ID: <004301c3981a$9ff151f0$6401a8c0@xp>

> Can line 3 of the following be improved (especially since I might
want
> to search for even more strings within each line):
>
> myfile=open(r'F:\logs\myfile.txt', 'r')
> for line in myfile.readlines():
>    if line.find("KeC 923") != -1 or line.find("ZEF 156") != -1 or
> line.find("pBX 88347") != -1 or line.find("FZX 17255") != -1:
>          #code if found

Yes use a regular expression. You can combine conditions in one
expression and it will only search the string once instead of
once per condition.

I'll leave it to someone else to explain how to combine the
regexs! I'm going to bed and my brain is tired.... :-)

Alan G.


From alan.gauld at blueyonder.co.uk  Tue Oct 21 17:32:12 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Tue Oct 21 17:31:37 2003
Subject: [Tutor] this is ugly
References: <3F94CD8F.3070105@fish.co.uk> <3F94D3EE.6090202@aon.at>
Message-ID: <004801c3981a$ca9463c0$6401a8c0@xp>

> A quick suggestion:
> 
>     if -1 not in [line.find(x) for x in ["KeC 923","ZEF 156","pBX 
> 88347","FZX 17255"]]:
>         # etc.

Still searches three times but at least its more maintainable.
A regex in this case will almost certainly be faster than 
repeated searching.

Alan G.


From alan.gauld at blueyonder.co.uk  Tue Oct 21 17:46:09 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Tue Oct 21 17:45:45 2003
Subject: [Tutor] Public, private and protected member variables.
References: <20031021094042.58659.qmail@web11702.mail.yahoo.com>
Message-ID: <005901c3981c$bd499c10$6401a8c0@xp>

> classes to get around this problem. Right now, I have
> a class that I reuse in many different situations and
> depending on the situation the class requires
> different properties. 

In that case they are different classes. Although Python 
allows you to add properties (aka attributes) at run time
this probably is the wrong way to tackle it here.

Is the interface constant between the classes - in other 
words are the multitude of classes polymorphic? If so 
then use inheritance to define the classes you need.
(and if not then they are definitely different classes!)

If you don't know which class you need until runtime 
build a factory method(or class!) that will look at the 
context and return an instance of the right variation.

> use a dictionary inside the class that uses a string
> as the key and any object as a value. 

Thats how Python builds a class internally, you are 
duplicating Python's work...

> setProperty(key, value)
> getProperty(key)

Which is what the getattr and setattr methods do internally 
in Python...

> I cannot come up with a better way to design the class
> to avoid using these types of accessor functions. 

What is the class doing? What data does it manage and 
what needs to be done to that data? And whatever it is 
a method of the class should do it.

> can't seem to find a better way to handle the type of
> situation where you have an object that has different
> properties depending on the situation it is used.

By definition those are different classes. An class is 
defined by its identity, state values and behaviour. 
By having different sets of state variables you are 
effectively changing the class! You are just doing it 
at run time!

Without more details on what the design looks like and 
what you are trying to achieve its impossible to be 
more specific. However generally this situation is handled 
by creating a class heirarchy(eg a UI event heirarchy) 
or by creating a generic data carrier collection class
(a bit like your dictionary) that is itself an attribute 
of the dynamic object. This latter solution can be messy 
and is only normally done when the multi class approach 
leads to an explosion in the number of classes (over a 
dozen say). But if you are currently managing it by adding 
attributes in code then I'd guess creating a class tree is
not going to be unreasonable.

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

From alan.gauld at blueyonder.co.uk  Tue Oct 21 17:51:15 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Tue Oct 21 17:50:39 2003
Subject: [Tutor] Public, private and protected member variables.
References: <20031021123449.99844.qmail@web11708.mail.yahoo.com>
Message-ID: <005e01c3981d$73a5dff0$6401a8c0@xp>

> I guess my reasoning for most of my statements comes from all of
those Java
> design principles that I have become so accustomed too.

I had similar problems when I moved to Delphi from C++ because
the original Delphi had no protected and only a loose form of
Private. Then when I moved to Smalltalk(much like Python,
except all variables are private) I was forced to rethink
my approach to objects and access etc.

> Alan, thanks for the comments. I come from the background of
> Java, which is very strict and it has made Python feel
> somewhat unnatural to me.

Yep, it's part of learning a new language. The good news is the
more languages you learn you become more pliable in your
approach. I'm currently learning Objective C (using Cocoa
on Mac OS X) and it takes a really strange (to me!)
approach to memory management. I'm slowly getting there
but my initial reaction was to feel very uncomfortable.

Its all part of the fun of learning a new language. And each
lessonlearnt will be useful in the other languages too!

Alan G.


From alan.gauld at blueyonder.co.uk  Tue Oct 21 17:54:48 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Tue Oct 21 17:54:14 2003
Subject: [Tutor] Public, private and protected member variables.
References: <20031021094042.58659.qmail@web11702.mail.yahoo.com>
	<3F954470.20703@venix.com>
Message-ID: <006301c3981d$f2a551a0$6401a8c0@xp>

> Once I start grabbing attributes, I can go overboard.  
> A simple example: build a formatted string for a 
> customer record by writing code that grabs cust.firstname 
> and cust.lastname and so on.  The better approach is 
> to have a customer method that returns the formatted string.  

A good example, Lloyd, of getting the object to do it to itself 
so that there is no need for the get/set methods or direct 
access to the fields.

> Then the logic is written once and placed where you would 
> expect to find it.

Exactly so - inside the class with the data it manipulates.

Thanks for posting,

Alan G.



From project5 at redrival.net  Tue Oct 21 18:05:26 2003
From: project5 at redrival.net (Andrei)
Date: Tue Oct 21 18:08:27 2003
Subject: [Tutor] Re: this is ugly
In-Reply-To: <004301c3981a$9ff151f0$6401a8c0@xp>
References: <3F94CD8F.3070105@fish.co.uk> <004301c3981a$9ff151f0$6401a8c0@xp>
Message-ID: <bn4an6$b68$1@sea.gmane.org>

Alan Gauld wrote:
>>Can line 3 of the following be improved (especially since I might
> 
> want
> 
>>to search for even more strings within each line):
>>
>>myfile=open(r'F:\logs\myfile.txt', 'r')
>>for line in myfile.readlines():
>>   if line.find("KeC 923") != -1 or line.find("ZEF 156") != -1 or
>>line.find("pBX 88347") != -1 or line.find("FZX 17255") != -1:
>>         #code if found
> 
> 
> Yes use a regular expression. You can combine conditions in one
> expression and it will only search the string once instead of
> once per condition.
> 
> I'll leave it to someone else to explain how to combine the
> regexs! I'm going to bed and my brain is tired.... :-)

Well, here's a RE which would match any of those things:

   KeC 923|ZEF 156|pBX 88347|FZX 17255

I don't know if evaling that regex would be faster/easier than using the 
find methods, especially not with one of the shortcut notations 
mentioned earlier in this thread. Perhaps a more generic RE would be in 
order, e.g.:

   \S{3}\s\d{3,5}

which (if compiled with the IGNORECASE flag) matches any sequence of 3 
letters followed by a space and 3 to 5 digits. Of course I don't know 
the type of input, perhaps this would match more than desired.

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V 
ernq gur yvfg, fb gurer'f ab arrq gb PP.



From druidmatt at yahoo.com  Tue Oct 21 18:10:23 2003
From: druidmatt at yahoo.com (Matt Hehman)
Date: Tue Oct 21 18:10:27 2003
Subject: [Tutor] Request for code critique
Message-ID: <20031021221023.98586.qmail@web10309.mail.yahoo.com>

I've written a program of about 40 lines including
comments.  I am teaching myself to program in my spare
time, working through the various online tutorials.  I
started with "Instant Hacking" by Hetland and built on
the example to calculate prime numbers.  Basically, I
looked for better ways to do it, then expanded its
functionality by throwing code at it and seeing what
stuck.  Before I try to refine it any further, I think
it would be good to get some feedback before I develop
any bad habits.  Rather than clog your inboxes by way
of asking for a big favor, any volunteers, please
e-mail me directly.

Thanks,
Matt Hehman

__________________________________
Do you Yahoo!?
SBC Yahoo! DSL - Now only $29.95 per month!
http://sbc.yahoo.com

From clay at shirky.com  Tue Oct 21 18:19:24 2003
From: clay at shirky.com (Clay Shirky)
Date: Tue Oct 21 18:19:02 2003
Subject: [Tutor] Request for code critique
In-Reply-To: <20031021221023.98586.qmail@web10309.mail.yahoo.com>
Message-ID: <BBBB292C.10069%clay@shirky.com>

> I've written a program of about 40 lines including
> comments.  I am teaching myself to program in my spare
> time, working through the various online tutorials.  I
> started with "Instant Hacking" by Hetland and built on
> the example to calculate prime numbers.  Basically, I
> looked for better ways to do it, then expanded its
> functionality by throwing code at it and seeing what
> stuck.  Before I try to refine it any further, I think
> it would be good to get some feedback before I develop
> any bad habits.  Rather than clog your inboxes by way
> of asking for a big favor, any volunteers, please
> e-mail me directly.

As a fellow newbie, I'd love to see it, and I'm sure it makes more sense to
post it here than to do it via CC. That sort of thing is what tutor is good
for.

-clay


From project5 at redrival.net  Tue Oct 21 18:21:21 2003
From: project5 at redrival.net (Andrei)
Date: Tue Oct 21 18:23:35 2003
Subject: [Tutor] Re: Request for code critique
In-Reply-To: <BBBB292C.10069%clay@shirky.com>
References: <20031021221023.98586.qmail@web10309.mail.yahoo.com>
	<BBBB292C.10069%clay@shirky.com>
Message-ID: <bn4bl1$fu5$1@sea.gmane.org>

Clay Shirky wrote:

>>I've written a program of about 40 lines including
>>comments.  I am teaching myself to program in my spare
>>time, working through the various online tutorials.  I
>>started with "Instant Hacking" by Hetland and built on
>>the example to calculate prime numbers.  Basically, I
>>looked for better ways to do it, then expanded its
>>functionality by throwing code at it and seeing what
>>stuck.  Before I try to refine it any further, I think
>>it would be good to get some feedback before I develop
>>any bad habits.  Rather than clog your inboxes by way
>>of asking for a big favor, any volunteers, please
>>e-mail me directly.
> 
> 
> As a fellow newbie, I'd love to see it, and I'm sure it makes more sense to
> post it here than to do it via CC. That sort of thing is what tutor is good
> for.

I agree, I can fit more than 50 lines of code on my screen so 40 doesn't 
seem like such a big problem. Make sure your mail interface doesn't 
break the code though.

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V 
ernq gur yvfg, fb gurer'f ab arrq gb PP.



From arkamir at softhome.net  Tue Oct 21 18:42:42 2003
From: arkamir at softhome.net (Conrad Koziol)
Date: Tue Oct 21 18:43:52 2003
Subject: [Tutor] can someone explain to me how this works
Message-ID: <1066776162.5035.4.camel@quercus>

Hey thanks for the tips !!!

def compare(a,b):
         if a[1]>b[1]: return 0
         else: return -1

i tried this out and it works, but i dont understand the logic behind it
:(
can someone help me out

i also dont get how it compares all the tuples in a list. Dont you need to enter
in two values not just one list?????

From dyoo at hkn.eecs.berkeley.edu  Tue Oct 21 19:13:22 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Oct 21 19:18:42 2003
Subject: [Tutor] can someone explain to me how this works  [comparsion
	functions and sort()]
In-Reply-To: <1066776162.5035.4.camel@quercus>
Message-ID: <Pine.LNX.4.44.0310211601260.20770-100000@hkn.eecs.berkeley.edu>



On Tue, 21 Oct 2003, Conrad Koziol wrote:

> Hey thanks for the tips !!!
>
> def compare(a,b):
>          if a[1]>b[1]: return 0
>          else: return -1
>
> i tried this out and it works, but i dont understand the logic behind it
> :( can someone help me out

Hi Conrad,

A "comparison function" is something that takes two things, and checks to
see if one is smaller than another.  In math notation:

    compare(a,b)  =    {  -1     if a < b
                           0     if a == b
                           1     if a > b
                       }

The important thing to see is that a comparison function is not meant to
be a "boolean" true-false thing: it's meant to return either a positive,
zero, or negative value.

Is this what's confusing, or is it something else?  Please feel free to
ask more questions about this, as it is definitely a confusing topic when
we first see it.



> i also dont get how it compares all the tuples in a list. Dont you need
> to enter in two values not just one list?????

Yes, this would be true if we were directly calling compare() on the list
itself.  However, that's not what's happening: instead, we're calling
sort, and sort() itself is calling compare() on pairs of elements on our
list.


Here's a concrete toy example of a similar situation:

###
>>> def applyOnList(function, L):
...     """Destructivly applies a 'function' on the list 'L'."""
...     for index, element in enumerate(L):
...         L[index] = function(element)
...
>>> def square(x): return x * x
...
>>> numbers = range(10)
>>> applyOnList(square, numbers)
>>> numbers
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
###

In this case, we've written a function called applyOnList() that takes in
a function, as well as a list of things.  Notice that the function we pass
in isn't being called on the whole list, but only on single elements of
that list.


sort() does something somewhat similar when it takes in that comparison
function.  sort() uses it as a helper toward some greater goal --- sorting
things --- but doesn't need to try applying it to the whole list at once.


Hope that made some sort of sense.  *grin* Please feel free to ask more
questions: if you'd like, we can talk about how comparsion functions
actually help sort() figure out how to sort.


From arkamir at softhome.net  Tue Oct 21 18:42:42 2003
From: arkamir at softhome.net (Conrad Koziol)
Date: Tue Oct 21 19:19:07 2003
Subject: [Tutor] can someone explain to me how this works
Message-ID: <1066776162.5035.4.camel@quercus>

Hey thanks for the tips !!!

def compare(a,b):
         if a[1]>b[1]: return 0
         else: return -1

i tried this out and it works, but i dont understand the logic behind it
:(
can someone help me out

i also dont get how it compares all the tuples in a list. Dont you need to enter
in two values not just one list?????

From erikprice at mac.com  Tue Oct 21 20:43:41 2003
From: erikprice at mac.com (Erik Price)
Date: Tue Oct 21 20:21:20 2003
Subject: [Tutor] 2nd Python Book
In-Reply-To: <200310201537.09775.john@duartedailey.org>
Message-ID: <C8614AFE-0428-11D8-ADEC-00039351FE6A@mac.com>


On Monday, October 20, 2003, at 06:37  PM, John Duarte wrote:

> I have seen recommendations for a first Python book, ie Alan Guald's 
> Learn to
> Program Using Python, and Lutz & Asher's Learning Python. (Which are 
> both
> terrific books!)
>
> I was wondering if anyone could recommend a '2nd book'.

The Python Cookbook.  You already know Python, this book teaches you 
how to do specific tasks or sophisticated programming idioms specific 
to Python.  It's one of my favorite Python books.

> I was glancing through Deitel & Deitel's How to Program Python, and it 
> looks
> very thorough. Are their any opinions about this book specifically.

I didn't even know these guys had a Python book.  Neat.



Erik


From Harm_Kirchhoff at mail.digital.co.jp  Tue Oct 21 20:07:57 2003
From: Harm_Kirchhoff at mail.digital.co.jp (Harm_Kirchhoff@mail.digital.co.jp)
Date: Tue Oct 21 20:21:56 2003
Subject: [Tutor] Nested Lists / Array Module
Message-ID: <OFD7D369B7.88885204-ON49256DC6.00830C0C-49256DC7.00009D65@jp.schneider-electric.com>

Python supports nested lists, which is very nice and can be used for very 
simple databases.

However, I could not find a way to write nested lists to files & retrieve 
them easily.
The .writelines() method expects a string as an argument.

Is there a method to dump any list on disk & read it back, or is it 
necessary to code this task ?

The array module seems to have such method, however, I could not find 
sufficient code examples to understand how the array module works. The 
Python Library Reference mentions the .fromfile() and .tofile() methods, 
does anyone have experience with the array module, especially whether it 
allows to write & retrieve nested arrays without problems ? Could you pass 
me some sample code ?

 
Harm 


From project5 at redrival.net  Tue Oct 21 20:33:27 2003
From: project5 at redrival.net (Andrei)
Date: Tue Oct 21 20:35:42 2003
Subject: [Tutor] Re: Nested Lists / Array Module
In-Reply-To: <OFD7D369B7.88885204-ON49256DC6.00830C0C-49256DC7.00009D65@jp.schneider-electric.com>
References: <OFD7D369B7.88885204-ON49256DC6.00830C0C-49256DC7.00009D65@jp.schneider-electric.com>
Message-ID: <bn4jcm$1jt$1@sea.gmane.org>

Harm_Kirchhoff@mail.digital.co.jp wrote:
> Python supports nested lists, which is very nice and can be used for very 
> simple databases.
> 
> However, I could not find a way to write nested lists to files & retrieve 
> them easily.
> The .writelines() method expects a string as an argument.
> 
> Is there a method to dump any list on disk & read it back, or is it 
> necessary to code this task ?

Not too long ago a similar question (or was it the same?) was on the list
I believe. You can either pickle or convert your list to a string using 
str(),
e.g. str(MyList). It doesn't matter how deep that list is.

<snip>

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V 
ernq gur yvfg, fb gurer'f ab arrq gb PP.



From dyoo at hkn.eecs.berkeley.edu  Tue Oct 21 20:54:28 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Oct 21 20:54:34 2003
Subject: [Tutor] Nested Lists / Array Module
In-Reply-To: <OFD7D369B7.88885204-ON49256DC6.00830C0C-49256DC7.00009D65@jp.schneider-electric.com>
Message-ID: <Pine.LNX.4.44.0310211749100.27613-100000@hkn.eecs.berkeley.edu>



On Wed, 22 Oct 2003 Harm_Kirchhoff@mail.digital.co.jp wrote:

> Python supports nested lists, which is very nice and can be used for very
> simple databases.
>
> However, I could not find a way to write nested lists to files &
> retrieve them easily. The .writelines() method expects a string as an
> argument.
>
> Is there a method to dump any list on disk & read it back, or is it
> necessary to code this task ?


Hi Harm,

Yes.  For simple cases, the 'shelve' module can help to "serialize"
these nested structures to and from disk.  "Serialization" is a term we
use to transform arbitrary Python objects to byte strings, and it's pretty
easy to do in Python.

In fact, we talked about this about a week ago:

    http://mail.python.org/pipermail/tutor/2003-October/025741.html

The example at that link uses only a flat list, but 'shelve' should work
with lists in lists too.


If you have more questions, please feel free to ask.  Good luck!


From clay at shirky.com  Tue Oct 21 21:42:46 2003
From: clay at shirky.com (Clay Shirky)
Date: Tue Oct 21 21:42:29 2003
Subject: [Tutor] General construction of alpha lists?
Message-ID: <BBBB58D6.1009C%clay@shirky.com>

So I have this bit of code:

class_groups = [ 'A', 'B', 'C', 'D', 'E' ]

while class_groups:
      next = random.choice( range( len(class_groups) ))
      print class_groups[next]
      class_groups[next:next+1] = []

which will give me some random permutation of the items in the list
class_groups.

Next stop, making it possible to generate an alphabetical list, based on the
array number. I'd like to do something like

class_groups = range(12)

and then have it print from A through L. Is there an easy way to specify a
list that is simply letters in order, or do I have to write out

alpha = [ 'A', 'B', ... 'Z', 'a', 'b', ... 'z' ]

Thanks

-clay


From contrasutra at myrealbox.com  Tue Oct 21 23:08:05 2003
From: contrasutra at myrealbox.com (Ben Mazer)
Date: Tue Oct 21 23:34:54 2003
Subject: [Tutor] Timing a loop
Message-ID: <3F95F495.4050102@myrealbox.com>

I have written a small script that creates a bunch of small text files. 
I'm doing this because I want to benchmark file creation/deletion times 
on different file systems.

Im looking right now about how to time how long it takes to create the 
files. I looked at the Timeit() module, and that doesn't seem to work, 
its for small algorithms.

I also looked at time.clock(), but I can't get that to display an 
accurate readout, so I dont think that works (or Im not using it right).

I know I could use the UNIX "time" command, but it would be nice if 
Python had a built in function. They probably do, but I can't find it. :P

Any help you could provide on timing a loop would be really helpful.

OT: How many files can reiserfs hold? I keep hitting "file system full" 
limits when I get into large amounts of files (hundreds of thousands).

Thanks.
-- 
/"\ Ben Mazer <contrasutra@myrealbox.com>
\ /
  X  ASCII RIBBON CAMPAIGN AGAINST HTML MAIL
/ \


From karl.fast at pobox.com  Tue Oct 21 23:42:06 2003
From: karl.fast at pobox.com (Karl Fast)
Date: Tue Oct 21 23:42:16 2003
Subject: [Tutor] General construction of alpha lists?
In-Reply-To: <BBBB58D6.1009C%clay@shirky.com>;
	from clay@shirky.com on Tue, Oct 21, 2003 at 09:42:46PM -0400
References: <BBBB58D6.1009C%clay@shirky.com>
Message-ID: <20031021214206.E8821@signal.lights.com>

> Is there an easy way to specify a list that is simply letters in
> order, or do I have to write out
> 
> alpha = [ 'A', 'B', ... 'Z', 'a', 'b', ... 'z' ]

The string module defines various constants that have the characters
you want. If you do this in the shell you can see what's in these
constants.

  >>> import string
  >>> print string.uppercase
  ABCDEFGHIJKLMNOPQRSTUVWXYZ??????????????????????????????????
  >>> print string.lowercase
  abcdefghijklmnopqrstuvwxyz????????????????????????????????????
  >>> print string.printable
  0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;<=>?@[\]^_{|}~

There are other constants too. Details in the string module docs.

I'm new to python myself, but this should do what you want.


--karl

From tbrauch at mindless.com  Wed Oct 22 00:07:36 2003
From: tbrauch at mindless.com (Timothy M. Brauch)
Date: Wed Oct 22 00:07:39 2003
Subject: [Tutor] Bit Strings
Message-ID: <005801c39852$07468c30$6600a8c0@winxp>

There has to be an easy way to do this that I am just not seeing.  I am
trying to create all bit strings of length n.  Right now my code is as
follows:

bitStrings = []
for a0 in [0,1]:
    for a1 in  [0,1]:
        for a2 in [0,1]:
            oneString = str(a0)+str(a1)+str(a2)
            bitStrings.append(oneString)
print bitStrings

I know this is ugly and when I need longer strings, say n = 10, the code
gets way too repetitive with 10 nested for loops.  Surely there is an easier
way to do this, but I just can't figure it out.  I have a function that will
generate the above functions, but it is uglier and probably way not the
correct way to go about this.

def generator(n):
    tb = "    "
    stringMaker = ""
    print "bitStrings = []"
    for i in xrange(0,n+1):
        print i*tb + "for a"+str(i)+" in [0,1]:"
        stringMaker = stringMaker + "str"+chr(40)+"a"+str(i)+chr(41)+chr(43)
    stringMaker = stringMaker[:-1] #strip the last chr(43)
    print (i+1)*tb + "oneString = "+stringMaker
    print (i+1)*tb + "bitStrings.append(oneString)"
    print "print bitStrings"


Any suggestions?

 - Tim


---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.528 / Virus Database: 324 - Release Date: 10/17/2003


From idiot1 at netzero.net  Wed Oct 22 00:41:29 2003
From: idiot1 at netzero.net (Kirk Bailey)
Date: Wed Oct 22 00:42:12 2003
Subject: [Tutor] can someone explain to me how this works
In-Reply-To: <1066776162.5035.4.camel@quercus>
References: <1066776162.5035.4.camel@quercus>
Message-ID: <3F960A79.3030501@netzero.net>

I will give it a shot. Try not to laugh too hard if I mung it into kruftyness.

Conrad Koziol wrote:

> Hey thanks for the tips !!!
> 
> def compare(a,b):
>          if a[1]>b[1]: return 0
>          else: return -1
> 
ok. a[1] returns a char from a string, or a number in a list or tuple of 
numbers. So does b[1]. I am ASSUMING they are numbers in a list or tuple. Look 
at the values they would return.

if a[1]=12, and b[1]=4, well, 12>4 is true, so it would return a 1, which is a 
logical TRUE. so the condition after the test would happen, which is 'return 0', 
so your function ends, returning the value 0. now a -1 would be returned if the 
test was NOT true, by executing the other leg in the if/else structure.

First, it's neater to put the conditional after a if statement indented on the 
next line, and I cannot gurantee that placing it on the SAME line as the test 
will work in future versions of python. so let's do this:

def compare(a,b):
	if a[1]>b[1]:
		return 0
	else:
		return -1

This is your function, nice nad neat and quite properly pythonesque. But we can 
make it easier.

def compare(a,b):
	return not a[1]>b[1]

Not inverts the logical vallue of a returned logical value.
Again, a[1]=12 and b[1]=4. with this test, and those values, the return is 0. 
Were the values reversed, this would be a 1 return, which is true, as is a -1 
return value. IF the value HAS to be 0  or -1, we need to define the function 
with customized values. And a simple way to do it is:

def compare(a,b):
	return (a[1]>b[1])-1

Dig; if true, the returned value of a test is 1. If false, it is 0. These are 
plain old fashioned interger values, and you can do basic math on them just 
fine. Subtract 1 from that result, and you get 0 and -1 respectively. Python 
treats 0 as false, and any non 0 value as true, therefore the logic holds and 
you get your desired result faster and simpler.

Any discussion gang?




> i tried this out and it works, but i dont understand the logic behind it
> :(
> can someone help me out
> 
> i also dont get how it compares all the tuples in a list. Dont you need to enter
> in two values not just one list?????
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 

-- 

end

Cheers!
         Kirk D Bailey

  +                              think                                +
   http://www.howlermonkey.net  +-----+        http://www.tinylist.org
   http://www.listville.net     | BOX |  http://www.sacredelectron.org
   Thou art free"-ERIS          +-----+     'Got a light?'-Prometheus
  +                              kniht                                +

Fnord.


From thomi at imail.net.nz  Wed Oct 22 00:53:11 2003
From: thomi at imail.net.nz (Thomi Richards)
Date: Wed Oct 22 01:03:56 2003
Subject: [Tutor] Bit Strings
In-Reply-To: <005801c39852$07468c30$6600a8c0@winxp>
References: <005801c39852$07468c30$6600a8c0@winxp>
Message-ID: <200310221753.11830.thomi@imail.net.nz>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Hi,

>
> Any suggestions?
>

I may have an idea ;)

essentially, what your code does is a binary count from 0 to 2^n (where n is 
the number of iterations / bits). right?

here's a sampel run of your code: (using 3 bits / iterations):

>>> bitStrings = []
>>> for a0 in [0,1]:
...     for a1 in  [0,1]:
...         for a2 in [0,1]:
...             oneString = str(a0)+str(a1)+str(a2)
...             bitStrings.append(oneString)
...                
>>> bitStrings
['000', '001', '010', '011', '100', '101', '110', '111']


Unless I'm mistaken, couldn't you do something like this:

>>> def bitStrings(iterations=3):
...     binary_strlist = []
...     for num in range(2**iterations):
...             binary_strlist.append(binary(num))
...     return binary_strlist
... 


which leaves us with the task of coding a decimal to binary converter. This is 
actually quite simple...One way to do it is to use a dictionary to convert 
from a hex value to a binary one (AFAIK, python doesn't have a binary 
converter. It does however have a hex converter). 

However, there are a couple of complications in this function:

1.- we could/should? pad the binary values with zero's.. so binary 1 becomes 
001, or 00000001 (for an 8 bit number)

2.- we can't do a direct map from decimal->hex-> binary, because we might be 
given a decimal larger than 15, which will result in a two digit hex 
number...

So, something like this:
>>> def binary(decimal):
...     bin_string = ''
...     map_dict = {
...     '0' : '0000',
...     '1' : '0001',
...     '2' : '0010',
...     '3' : '0011',
...     '4' : '0100',
...     '5' : '0101',
...     '6' : '0110',
...     '7' : '0111',
...     '8' : '1000',
...     '9' : '1001',
...     'a' : '1010',
...     'b' : '1011',
...     'c' : '1100',
...     'd' : '1101',
...     'e' : '1110',
...     'f' : '1111' }
...     for hexdigit in hex(decimal)[2:]:       #ignore the leading '0x'
...             bin_string += map_dict[hexdigit]
...     return bin_string

to test our decimal -> binary converter:
>>> binary(5)
'0101'
>>> binary(50)
'00110010'

Now we can test the whole thing:

bitStrings()

(this uses the default, 3 places)

for more places:
>>> bitStrings(5)
['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', 
'1001', '1010', '1011', '1100', '1101', '1110', '1111', '00010000', 
'00010001', '00010010', '00010011', '00010100', '00010101', '00010110', 
'00010111', '00011000', '00011001', '00011010', '00011011', '00011100', 
'00011101', '00011110', '00011111']

As you can see, there's still some problems here.

I've been doing this all in the interactive window, and it's getting a bit 
cumbersome. Perhaps it's time for someone else to continue this ;P

It's pretty much there, and it's prettyextendable as well. (I would appreciate 
some feedback on this from some of the more experienced tutor list members as 
well ;)

anyway, i hope this helps!

Thanks,

- -- 
Thomi Richards,
http://once.sourceforge.net/


-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.3 (GNU/Linux)

iD8DBQE/lg032tSuYV7JfuERAjW7AKCQXafrATb5HcJwtBWdheoGFDQWCQCfUZ1X
8dKMIJ4hZvSueTUSfvhycUQ=
=bMx+
-----END PGP SIGNATURE-----


From thomi at imail.net.nz  Wed Oct 22 00:59:22 2003
From: thomi at imail.net.nz (Thomi Richards)
Date: Wed Oct 22 01:10:06 2003
Subject: [Tutor] Bit Strings
In-Reply-To: <200310221753.11830.thomi@imail.net.nz>
References: <005801c39852$07468c30$6600a8c0@winxp>
	<200310221753.11830.thomi@imail.net.nz>
Message-ID: <200310221759.22986.thomi@imail.net.nz>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

> 1.- we could/should? pad the binary values with zero's.. so binary 1
> becomes 001, or 00000001 (for an 8 bit number)
>
> 2.- we can't do a direct map from decimal->hex-> binary, because we might
> be given a decimal larger than 15, which will result in a two digit hex
> number...
>
Sorry.. I just realised that these really don't make any sense whatsoever, 
when you look at the code ;) sorry, it's been a long day ;(

- -- 
Thomi Richards,
http://once.sourceforge.net/


-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.3 (GNU/Linux)

iD8DBQE/lg6q2tSuYV7JfuERAmh6AJ94FJeBUxbdlhoUWoJMOEEdk7TI4wCePDb2
Bt56N6CMAkvgSdnSdGKOcPk=
=lKD3
-----END PGP SIGNATURE-----


From dyoo at hkn.eecs.berkeley.edu  Wed Oct 22 02:03:26 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Oct 22 02:03:33 2003
Subject: [Tutor] General construction of alpha lists?
In-Reply-To: <BBBB58D6.1009C%clay@shirky.com>
Message-ID: <Pine.LNX.4.44.0310212256340.17656-100000@hkn.eecs.berkeley.edu>



On Tue, 21 Oct 2003, Clay Shirky wrote:

> Next stop, making it possible to generate an alphabetical list, based on
> the array number. I'd like to do something like
>
> class_groups = range(12)
>
> and then have it print from A through L.


Hi Clay,

Yes, there's a nice way to do it.  Karl Fast's approach is probably the
best one.  But if we didn't have that nice string constant handy, we can
still do it easily.

Here are two ingredients:

    chr()  --  http://www.python.org/doc/lib/built-in-funcs.html#l2h-15

    ord()  --  http://www.python.org/doc/lib/built-in-funcs.html#l2h-56

With some list manipulation, you should be able to cook something up
pretty nicely.  *grin*


Talk to you later!



From tbrauch at mindless.com  Wed Oct 22 02:13:34 2003
From: tbrauch at mindless.com (Timothy M. Brauch)
Date: Wed Oct 22 02:13:35 2003
Subject: [Tutor] Bit Strings
References: <005801c39852$07468c30$6600a8c0@winxp>
	<200310221753.11830.thomi@imail.net.nz>
Message-ID: <007201c39863$a01179f0$6600a8c0@winxp>

From: "Thomi Richards" <thomi@imail.net.nz>
>
> I may have an idea ;)
>
> essentially, what your code does is a binary count from 0 to 2^n (where n
is
> the number of iterations / bits). right?
>
> Unless I'm mistaken, couldn't you do something like this:
>
> >>> def bitStrings(iterations=3):
> ...     binary_strlist = []
> ...     for num in range(2**iterations):
> ...             binary_strlist.append(binary(num))
> ...     return binary_strlist
> ...
> >>> bitStrings(5)
> ['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000',
> '1001', '1010', '1011', '1100', '1101', '1110', '1111', '00010000',
> '00010001', '00010010', '00010011', '00010100', '00010101', '00010110',
> '00010111', '00011000', '00011001', '00011010', '00011011', '00011100',
> '00011101', '00011110', '00011111']
>
> As you can see, there's still some problems here.
>
>
> - -- 
> Thomi Richards,
> http://once.sourceforge.net/

Ah, very good, very good indeed.  Your result for bitStrings(5) was so close
to being right.  The only thing left to do would be to clean up the strings
so that they all have 5 digits.  Thus '0000' becomes '00000' and '00011001'
becomes '11001' and so forth.  I think that can be done pretty easily.
Something like the following before we append...

bits = binary(num)
while len(bits) < iterations:
    bits = '0' + bits
while len(bits) > iterations:
    if bits[0] != '1':  #check to be sure first digit isn't a one,
        bits = bits[1:] #but it shouldn't be anyway
binary_strlist.append(bits)

Let's put it all together and see what we get...

def bitStrings(iterations=3):
    binary_strlist = []
    for num in range(2**iterations):
        bits = binary(num)
        while len(bits) < iterations:
            bits = '0' + bits
        while len(bits) > iterations:
            if bits[0] != '1':  #check to be sure first digit isn't a one,
                bits = bits[1:] #but it shouldn't be anyway
        binary_strlist.append(bits)
    return binary_strlist

>>> bitStrings(5)
['00000', '00001', '00010', '00011', '00100', '00101', '00110', '00111',
'01000', '01001', '01010', '01011', '01100', '01101', '01110', '01111',
'10000', '10001', '10010', '10011', '10100', '10101', '10110', '10111',
'11000', '11001', '11010', '11011', '11100', '11101', '11110', '11111']

Checking bitStrings(6) and bitStrings(7) gives the correct answer as well.
Perfect.  I'm sure the padding/stripping part could be written a little more
effective, but it fits my needs for right now.  Thanks.

The next task would be what if I needed strings that used 0, 1, and 2.  We'd
need a decimal to trinary function.  Or if I needed strings that used all
digits from 0 to (n-1).  Hmm, I think I know how I will be spending my
weekend.

 - Tim


---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.528 / Virus Database: 324 - Release Date: 10/17/2003


From dyoo at hkn.eecs.berkeley.edu  Wed Oct 22 02:33:37 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Oct 22 02:34:46 2003
Subject: [Tutor] Bit Strings  [a recursive approach]
In-Reply-To: <005801c39852$07468c30$6600a8c0@winxp>
Message-ID: <Pine.LNX.4.44.0310212304000.17656-100000@hkn.eecs.berkeley.edu>



On Wed, 22 Oct 2003, Timothy M. Brauch wrote:

> There has to be an easy way to do this that I am just not seeing.  I am
> trying to create all bit strings of length n.

Hi Timothy,


Have you tried a recursive approach?  It might be useful to outline how to
solve this recursively, so here goes!  *grin*


Let's say that we have a function called bitstrings(n) that gives us all
the bit strings of length n.  Then we can say a few things about it:

    bitstrings(0) = []
    bitstrings(1) = ["0", "1"]
    bitstrings(2) = ["00", "01", "10", "11"]
    bitstrings(3) = ["000", "001", "010", "011",
                     "100", "101", "110", "111"]

With this, we can already write something down in Python:

###
>>> def bitstrings(n):
...     if n == 0: return []
...     if n == 1: return ["0", "1"]
...     if n == 2: return ["00", "01", "10", "11"]
...     if n == 3: return ["000", "001", "010", "011", "100", "101",
"110", "111"]
...
>>> bitstrings(0)
[]
>>> bitstrings(1)
['0', '1']
>>> bitstrings(2)
['00', '01', '10', '11']
>>> bitstrings(3)
['000', '001', '010', '011', '100', '101', '110', '111']
>>> bitstrings(4)
>>>
###

And this sorta works, except it handles things up only up to n=4.  *grin*
How do we define it for larger values of n?


One key to a recursive solution is to look at how the smaller solutions
are built up.  Let's look at the difference between bitstrings(2) and
bitstrings(3):

###
>>> bitstrings(2)
['00', '01', '10', '11']
>>> bitstrings(3)
['000', '001', '010', '011', '100', '101', '110', '111']
###

Here's a weird question: if we want to build up bitstrings(3) out of
components of bitstrings(2), is there a way to do it?


The key here is to see that bitstrings(3) almost looks like two copies of
bitstrings(2):

###
>>> bitstrings(3)
['000', '001', '010', '011', '100', '101', '110', '111']
>>> bitstrings(2) + bitstrings(2)
['00', '01', '10', '11', '00', '01', '10', '11']
###

It's really darn close, except we need to augment the the first half of
that result list so that each element has a '0' in front of it, and
augment the second half with '1' in front.


But that's not too difficult to do:

###
>>> def appendInFront(x, L):
...     return [x + element for element in L]
...
>>> appendInFront("0", bitstrings(2))
['000', '001', '010', '011']
###


So now that we have something like appendInFront(), we can rewrite
bitstrings() this way:

###
def bitstrings(n):
    if n == 0: return []
    if n == 1: return ["0", "1"]
    if n == 2: return ["00", "01", "10", "11"]
    if n == 3:
        return (appendInFront("0", bitstrings(2))
                + appendInFront("1", bitstrings(2)))
###



In fact, with some thought, we can even expand this to work for n=4:

###
def bitstrings(n):
    if n == 0: return []
    if n == 1: return ["0", "1"]
    if n == 2: return ["00", "01", "10", "11"]
    if n == 3:
        return (appendInFront("0", bitstrings(2))
                + appendInFront("1", bitstrings(2)))
    if n == 4:
        return (appendInFront("0", bitstrings(3))
                + appendInFront("1", bitstrings(3)))
###

Or even n=5.


###
def bitstrings(n):
    if n == 0: return []
    if n == 1: return ["0", "1"]
    if n == 2: return ["00", "01", "10", "11"]
    if n == 3:
        return (appendInFront("0", bitstrings(2))
                + appendInFront("1", bitstrings(2)))
    if n == 4:
        return (appendInFront("0", bitstrings(3))
                + appendInFront("1", bitstrings(3)))
    if n == 5:
        return (appendInFront("0", bitstrings(4))
                + appendInFront("1", bitstrings(4)))
###

We can go on this this for some time.  *grin*

(By the way, notice that when n=4, we end up doing something like:

    bitstrings(4) --> appendInFront(0, bitstrings(3))   +  ... [repeat]
                                       /         \
                                      /           \
                                     /             \
                          appendInFront('0',    appendInFront('1',
                               bitstrings(2))        bitstrings(2))
)

But that's ok, since bitstrings(2) is something our bitstrings() function
can handle perfectly well.


Here's the punchline: things will work if we take a leap of faith, and
just write:

###
def bitstrings(n):
    if n == 0: return []
    if n == 1: return ["0", "1"]
    if n == 2: return ["00", "01", "10", "11"]
    else:
        return (appendInFront("0", bitstrings(n-1))
                + appendInFront("1", bitstrings(n-1)))
###


Does this make sense so far?  Please feel free to ask questions on this.


Good luck to you!


From dyoo at hkn.eecs.berkeley.edu  Wed Oct 22 03:20:10 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Oct 22 03:20:39 2003
Subject: [Tutor] can someone explain to me how this works  [comparison
	functions]
In-Reply-To: <3F960A79.3030501@netzero.net>
Message-ID: <Pine.LNX.4.44.0310212347270.17656-100000@hkn.eecs.berkeley.edu>



On Wed, 22 Oct 2003, Kirk Bailey wrote:

> Not inverts the logical vallue of a returned logical value. Again,
> a[1]=12 and b[1]=4. with this test, and those values, the return is 0.
> Were the values reversed, this would be a 1 return, which is true, as is
> a -1 return value. IF the value HAS to be 0 or -1, we need to define the
> function with customized values. And a simple way to do it is:
>
> def compare(a,b):
> 	return (a[1]>b[1])-1


Hi Kirk,

True, it's simpler for the computer, but it's depending on the fact that
True and False are represented as 1 and 0.  Personally, I like:

###
def compare(a,b):
    if a[1] > b[1]:
        return 0
    else:
        return -1
###

better.  Even though it's more wordy, it won't surprise anyone who is
coming from a language with stricter boolean types.


But even so, I feel:

###
def compare(a,b):
    if a[1] < b[1]:
        return -1
    elif a[1] == b[1]:
        return 0
    else:
        return 1
###

is clearer as a comparison function.  Comparison functions are meant to be
triple-valued.  The original function obscured this point because it only
returned either -1 or 0, which isn't quite right.  By making three
distinct cases, we can convince anyone reading this that it is
triple-valued.

(By the way, the shortest definition I can think that's equivalent to the
above example is:  "def compare(a,b): return cmp(a[1], b[1])".)



It's very important to know that comparison functions must not be boolean
functions.  We can even see sort() malfunction if we accidently make it
return either 0 or 1!

###
>>> def brokenCompare(a, b):
...     if a > b: return 1
...     return 0
...
>>> numbers = [5,4,3,2,1]
>>> numbers.sort(brokenCompare)
>>> numbers
[5, 4, 3, 2, 1]
###

It's only by a coincidence of implementation that sort() works on a
comparison function that returns either 0 or -1.  Even so, we should
strive to make a comparison function return either -1, 0, or 1.



One last point: I've been fudging.  *grin* Comparison functions don't have
to return -1, 0, or 1: they can return negatives, zero, or positives.  If
we know this, then it's tempting to avoid writing:

###
def compare(a,b):
    if a[1] < b[1]:
        return -1
    elif a[1] == b[1]:
        return 0
    else:
        return 1
###

and instead say something like

###
def compare(a, b):
    return a[1] - b[1]
###

to avoid all that wordy comparison logic.  It's fast, it involves a single
numeric operation, so what can be the problem with it?  Actually, it is
dangerous.  It's not so bad in Python, since we have long ints, but in a
language that doesn't automagically use bignums, this definition is
broken: subtraction can overflow!

That's one reason why I personally remind myself that the range of a
comparison function is (-1, 0, 1), and not (negative, zero, positive) ---
it pretty much forces me to do the explicit comparisons.  *grin*


Talk to you later!


From tbrauch at mindless.com  Wed Oct 22 03:48:59 2003
From: tbrauch at mindless.com (Timothy M. Brauch)
Date: Wed Oct 22 03:48:58 2003
Subject: [Tutor] Bit Strings  [a recursive approach]
References: <Pine.LNX.4.44.0310212304000.17656-100000@hkn.eecs.berkeley.edu>
Message-ID: <009a01c39870$f4402730$6600a8c0@winxp>

Whilst trying to find all bit strings of a certain length, I struggled.
Danny Yoo was helpful with:

> Have you tried a recursive approach?  It might be useful to outline how to
> solve this recursively, so here goes!  *grin*

I should have thought of this, since the way I was doing it by hand was
basically recursive...

> >>> def appendInFront(x, L):
> ...     return [x + element for element in L]
> ...
> >>> appendInFront("0", bitstrings(2))
> ['000', '001', '010', '011']
> ###
...
> Here's the punchline: things will work if we take a leap of faith, and
> just write:
>
> ###
> def bitstrings(n):
>     if n == 0: return []
>     if n == 1: return ["0", "1"]
>     if n == 2: return ["00", "01", "10", "11"]
>     else:
>         return (appendInFront("0", bitstrings(n-1))
>                 + appendInFront("1", bitstrings(n-1)))
> ###
>
>
> Does this make sense so far?  Please feel free to ask questions on this.

Yes, that is the way I was doing it by hand.  First right down the n=1 case.
Then for n=2, write it down a second time and put a zero in front of the
first half, a 1 in front of the second half.  For n=3, write down n=2 twice,
putting a 0 infront of the first half, a 1 in front of the second...

I guess I just didn't realize what I was doing by hand would have worked if
I had coded it correctly.  And, the nice thing about this is that it should
be pretty easy to extend the idea if my strings need to have more
characters.  Just a few more base cases and the else:return needs to be have
a few more lines. Thanks.

 - Timothy

P.S. I guess it is the mathematician in me that doesn't like recursively
defined functions.  We tend to like closed form things better.  And it was
my stumbling block in my algorithm classes.  Although, recursive is often
much more elegant...



---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.528 / Virus Database: 324 - Release Date: 10/17/2003


From alan.gauld at blueyonder.co.uk  Wed Oct 22 04:36:44 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Wed Oct 22 04:36:02 2003
Subject: [Tutor] Bit Strings  [a recursive approach]
References: <Pine.LNX.4.44.0310212304000.17656-100000@hkn.eecs.berkeley.edu>
Message-ID: <00cc01c39877$9fb8bb80$6401a8c0@xp>

> Here's the punchline: things will work if we take a leap of faith,
and
> just write:
>
> ###
> def bitstrings(n):
>     if n == 0: return []
>     if n == 1: return ["0", "1"]
>     if n == 2: return ["00", "01", "10", "11"]
>     else:
>         return (appendInFront("0", bitstrings(n-1))
>                 + appendInFront("1", bitstrings(n-1)))
> ###

And in fact you could even remove the if n== 2 line.
It works just fine using the appendInFRont function!

def bitstrings(n):
     if n == 0: return []
     if n == 1: return ["0", "1"]
     else:
         return (appendInFront("0", bitstrings(n-1))
                 + appendInFront("1", bitstrings(n-1)))
:-)

Alan G.


From charlie at begeistert.org  Wed Oct 22 04:41:45 2003
From: charlie at begeistert.org (Charlie Clark)
Date: Wed Oct 22 04:40:57 2003
Subject: [Tutor] Re: Bit strings
In-Reply-To: <E1ACDJW-000359-Ar@mail.python.org>
References: <E1ACDJW-000359-Ar@mail.python.org>
Message-ID: <20031022104145.542.1@bepc.gormenghast>


On 2003-10-22 at 09:21:50 [+0200], tutor-request@python.org wrote:
> >>> bitStrings(5)
> ['00000', '00001', '00010', '00011', '00100', '00101', '00110', '00111', 
> '01000', '01001', '01010', '01011', '01100', '01101', '01110', '01111', 
> '10000', '10001', '10010', '10011', '10100', '10101', '10110', '10111', 
> '11000', '11001', '11010', '11011', '11100', '11101', '11110', '11111']
> 
> Checking bitStrings(6) and bitStrings(7) gives the correct answer as 
> well. Perfect.  I'm sure the padding/stripping part could be written a 
> little more effective, but it fits my needs for right now.  Thanks.
> 
> The next task would be what if I needed strings that used 0, 1, and 2.  
> We'd need a decimal to trinary function.  Or if I needed strings that 
> used all digits from 0 to (n-1).  Hmm, I think I know how I will be 
> spending my weekend.

Reading this last paragraph makes me think that you are looking for a 
generic base converter. I'm sure there are lots of examples around there 
but it should be quite easy to come up with your own using a recursive 
function. I'm very bad at designing these myself but in theory you can 
convert any decimal to another base by dividing recursively and adding the 
modulus to the result. You can build this into a lazy function which can 
operate on a range for you and use "zfill" to generate your formatted 
strings.

Quick sketch 
9 / 2, 9 % 2 = 4, 1
4 / 2, 4 % 2 = 2, 0
2 / 2, 2 % 2 = 1, 0
1 / 2, 2 % 1 = 0, 0 # this tells us we're at the end of anaylsis

The trick is to turn this into something like 1 0 0 + 1 and to test it with 
other values. The nice thing about division and modulo is that we don't 
have to worry about what is the maximal value in any particular base.

Charlie

From dhanvik at gmx.net  Wed Oct 22 06:20:58 2003
From: dhanvik at gmx.net (dhanvik@gmx.net)
Date: Wed Oct 22 06:20:16 2003
Subject: [Tutor] Python Class functionality idiosyncrasy..
Message-ID: <200310221550.58631.dhanvik@gmx.net>

Dear Friends,
  While just playing arnd with Python .. I just came across 
this curious implementation of Python Object Oriented 
Techniques.. 

The base class here is calling a function of the derived 
class even befre the function of the derived class is 
defined..A similar implementation in C++ would not even 
compile.. My question is doesnt this implementation break 
some tennants of OO techniques ?? How can the base class 
call functions of the derived class ?? 

>>> class base1 :
...     def baseFunc1( self ):
...             print "Base class Function"
...             self.derivedFunc()
...
>>> class derived( base1 ):
...     def derivedFunc(self ):
...             print "derived Func.."
...
>>> b = base1()
>>> b.baseFunc1()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: unbound method baseFunc1() must be called with 
base1 instance as first argument (got nothing instead)

>>> d  = derived()
>>> d.baseFunc1()
Base class Function
derived Func..
>>>


Cheers
Dhanvi K

From project5 at redrival.net  Wed Oct 22 06:47:54 2003
From: project5 at redrival.net (Andrei)
Date: Wed Oct 22 06:50:11 2003
Subject: [Tutor] Re: Python Class functionality idiosyncrasy..
In-Reply-To: <200310221550.58631.dhanvik@gmx.net>
References: <200310221550.58631.dhanvik@gmx.net>
Message-ID: <bn5ncq$cfu$1@sea.gmane.org>

dhanvik@gmx.net wrote:

> Dear Friends,
> The base class here is calling a function of the derived 
> class even befre the function of the derived class is 
 > defined..A similar implementation in C++ would not even
 > compile.. My question is doesnt this implementation break

No, it doesn't call it because no calling is performed at compile time. 
Note that Python has no compile-time checking of whether a method is 
defined or not. After all, what's not there at compile-time, can be 
there at runtime (dynamic as opposed to static languages).

> some tennants of OO techniques ?? How can the base class 
> call functions of the derived class ?? 

It doesn't. I think you've done something wrong, here's my run:

 >>> class base1:
...     def baseFunc1(self):
...         print "Base class Function"
...         self.derivedFunc()
...
 >>> class derived(base1):
...     def derivedFunc(self):
...         print "derived Func..."
...
 >>> b = base1()
 >>> b.baseFunc1()
Base class Function
Traceback (most recent call last):
   File "<input>", line 1, in ?
   File "<input>", line 4, in baseFunc1
AttributeError: base1 instance has no attribute 'derivedFunc'
>>> d = derived()
>>> d.baseFunc1()
Base class Function
derived Func...

So I get an AttributeError, mentioning there's no derivedFunc. Seems 
about right to me (not sure why you got a typeerror). If we look at the 
dicts of b and de:

 >>> dir(b)
['__doc__', '__module__', 'baseFunc1']
 >>> dir(d)
['__doc__', '__module__', 'baseFunc1', 'derivedFunc']

See, d has both methods. So when you call baseFunc1 on it, derivedFunc 
is there for baseFunc1 to access. The method is there at runtime and 
that's all baseFunc1 cares about.


-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V 
ernq gur yvfg, fb gurer'f ab arrq gb PP.



From dhanvik at gmx.net  Wed Oct 22 07:06:18 2003
From: dhanvik at gmx.net (dhanvik@gmx.net)
Date: Wed Oct 22 07:05:48 2003
Subject: [Tutor] Re: Python Class functionality idiosyncrasy..
In-Reply-To: <bn5ncq$cfu$1@sea.gmane.org>
References: <200310221550.58631.dhanvik@gmx.net> <bn5ncq$cfu$1@sea.gmane.org>
Message-ID: <200310221636.18552.dhanvik@gmx.net>

Dear Andrei,
thats right .. Dynamic Checking in Python is the reason that 
the base class is allowing the using of function that is 
yet to be defined any there else in the program. But the 
function can be accessed using the 'self' variable..

Any program that would be implemented this way would be bad 
programming and more than that bad designing of OO 
structure for the prgram. 

this was something that struck immediately as being wrong 
and coming form C++ background to Python, I found it 
blasphemous ( :)) )..after all the base class is something 
thats supposed to be the mother of all later classes and 
hence how can it call the functions of the derived class 
which hasnt even been defined... but some thgt and it falls 
in line with the basic line of thgt of python 
implementation..

- Dhanvi

On Wednesday 22 October 2003 04:17 pm, Andrei wrote:
> dhanvik@gmx.net wrote:
> > Dear Friends,
> > The base class here is calling a function of the
> > derived class even befre the function of the derived
> > class is
> >
>  > defined..A similar implementation in C++ would not
>  > even compile.. My question is doesnt this
>  > implementation break
>
> No, it doesn't call it because no calling is performed at
> compile time. Note that Python has no compile-time
> checking of whether a method is defined or not. After
> all, what's not there at compile-time, can be there at
> runtime (dynamic as opposed to static languages).
>
> > some tennants of OO techniques ?? How can the base
> > class call functions of the derived class ??
>
> It doesn't. I think you've done something wrong, here's my 
run:
>  >>> class base1:
>
> ...     def baseFunc1(self):
> ...         print "Base class Function"
> ...         self.derivedFunc()
> ...
>
>  >>> class derived(base1):
> ...     def derivedFunc(self):
> ...         print "derived Func..."
> ...
>
>  >>> b = base1()
>  >>> b.baseFunc1()
>
> Base class Function
> Traceback (most recent call last):
>    File "<input>", line 1, in ?
>    File "<input>", line 4, in baseFunc1
> AttributeError: base1 instance has no attribute
> 'derivedFunc'
>
> >>> d = derived()
> >>> d.baseFunc1()
>
> Base class Function
> derived Func...
>
> So I get an AttributeError, mentioning there's no
> derivedFunc. Seems about right to me (not sure why you
> got a typeerror). If we look at the
>
> dicts of b and de:
>  >>> dir(b)
>
> ['__doc__', '__module__', 'baseFunc1']
>
>  >>> dir(d)
>
> ['__doc__', '__module__', 'baseFunc1', 'derivedFunc']
>
> See, d has both methods. So when you call baseFunc1 on
> it, derivedFunc is there for baseFunc1 to access. The
> method is there at runtime and that's all baseFunc1 cares
> about.


From project5 at redrival.net  Wed Oct 22 07:13:04 2003
From: project5 at redrival.net (Andrei)
Date: Wed Oct 22 07:15:17 2003
Subject: [Tutor] Re: Python Class functionality idiosyncrasy..
In-Reply-To: <200310221636.18552.dhanvik@gmx.net>
References: <200310221550.58631.dhanvik@gmx.net> <bn5ncq$cfu$1@sea.gmane.org>
	<200310221636.18552.dhanvik@gmx.net>
Message-ID: <bn5os0$l04$1@sea.gmane.org>

dhanvik@gmx.net wrote:

> Dear Andrei,
> thats right .. Dynamic Checking in Python is the reason that 
> the base class is allowing the using of function that is 
> yet to be defined any there else in the program. But the 
> function can be accessed using the 'self' variable..
> 
> Any program that would be implemented this way would be bad 
> programming and more than that bad designing of OO 
> structure for the prgram. 
> 
<snip>
Hm... well, if it makes you feel more comfortable (and I suppose it 
would be better design too), you can define a dummy method in base1:

 >>> class base1:
...     def baseFunc1(self):
...         self.derivedFunc()
...     def derivedFunc(self):
...         """Dummy method, override by children"""
...         pass

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V 
ernq gur yvfg, fb gurer'f ab arrq gb PP.



From amk at amk.ca  Wed Oct 22 07:17:42 2003
From: amk at amk.ca (amk@amk.ca)
Date: Wed Oct 22 07:17:47 2003
Subject: [Tutor] General construction of alpha lists?
In-Reply-To: <BBBB58D6.1009C%clay@shirky.com>
References: <BBBB58D6.1009C%clay@shirky.com>
Message-ID: <20031022111742.GB1331@rogue.amk.ca>

On Tue, Oct 21, 2003 at 09:42:46PM -0400, Clay Shirky wrote:
> So I have this bit of code:
>       class_groups[next:next+1] = []

'del class_groups[next]' will also work.

BTW, there is a random.shuffle() function which generates a permutation of a
list, though it does it by randomly exchanging list elements.

> and then have it print from A through L. Is there an easy way to specify a
> list that is simply letters in order, or do I have to write out

Easiest is probably list(string.ascii_letters), or
list(string.ascii_lowercase).  string.letters is the list of letters for the
current locale, and therefore will usually include a bunch of accented
characters; the .ascii_* variables are fixed.

--amk

From amk at amk.ca  Wed Oct 22 07:27:55 2003
From: amk at amk.ca (amk@amk.ca)
Date: Wed Oct 22 07:28:01 2003
Subject: [Tutor] Timing a loop
In-Reply-To: <3F95F495.4050102@myrealbox.com>
References: <3F95F495.4050102@myrealbox.com>
Message-ID: <20031022112755.GC1331@rogue.amk.ca>

On Tue, Oct 21, 2003 at 11:08:05PM -0400, Ben Mazer wrote:
> I also looked at time.clock(), but I can't get that to display an 
> accurate readout, so I dont think that works (or Im not using it right).

time.clock() displays CPU time for the process; for an I/O bound task like
file creation, the process likely won't use much CPU -- it'll spend its time
idly waiting for disk blocks to be read.

You want time.time(), which returns "wall clock" time.  Your results will
therefore vary depending on your system's load; if cron runs in the middle
of your timing interval, you'll measure a longer time, so usually people
make several runs, discard outliers, and average them.

> Any help you could provide on timing a loop would be really helpful.

If you're using a big loop such as 'for i in range(100000)', you don't want
to measure the time to create the list of 100000 integer objects, so you
should write something like:

L = range(100000)
s = time.time()
for i in L:
    ....
e = time.time()
print 'Total time:', e-s, 'sec'.

> OT: How many files can reiserfs hold? I keep hitting "file system full" 
> limits when I get into large amounts of files (hundreds of thousands).

Look at the output of os.statvfs('/filesystem').   files, ffree, favail are
the number of free i-nodes.  (Though on my ReiserFS partition they're all
reported as 2**32-1 -- does ReiserFS have a fixed i-node limit?)

--amk

From amk at amk.ca  Wed Oct 22 07:40:10 2003
From: amk at amk.ca (amk@amk.ca)
Date: Wed Oct 22 07:40:36 2003
Subject: [Tutor] Re: Python Class functionality idiosyncrasy..
In-Reply-To: <200310221636.18552.dhanvik@gmx.net>
References: <200310221550.58631.dhanvik@gmx.net> <bn5ncq$cfu$1@sea.gmane.org>
	<200310221636.18552.dhanvik@gmx.net>
Message-ID: <20031022114010.GD1331@rogue.amk.ca>

On Wed, Oct 22, 2003 at 04:36:18PM +0530, dhanvik@gmx.net wrote:
> Any program that would be implemented this way would be bad 
> programming and more than that bad designing of OO 
> structure for the prgram.

No, it's not necessarily bad style.  In fact it's fairly common to provide
an abstract base class that isn't usable on its own; the user is supposed to
subclass it and provide one method that implements some particular
behaviour.  A good example from the Python stdlib is the SocketServer
module, which is used like this:

from SocketServer import ForkingTCPServer

class NNTPServer (ForkingTCPServer):
    def handle (self):
        ... process request ...
	
--amk

From dhanvik at gmx.net  Wed Oct 22 07:51:20 2003
From: dhanvik at gmx.net (dhanvik@gmx.net)
Date: Wed Oct 22 07:50:34 2003
Subject: [Tutor] Re: Python Class functionality idiosyncrasy..
In-Reply-To: <20031022114010.GD1331@rogue.amk.ca>
References: <200310221550.58631.dhanvik@gmx.net>
	<200310221636.18552.dhanvik@gmx.net>
	<20031022114010.GD1331@rogue.amk.ca>
Message-ID: <200310221721.20113.dhanvik@gmx.net>

Abstract classes have the abstract keyword preceeding then 
and hence it makes sense for  a reader of the program to 
know that the function would be implemented in the derived 
classes..but in this case theres no way of knowing whether 
the function was defined or not.. 
Hence, I was talking in terms of programming in Python.  :-)

 
On Wednesday 22 October 2003 05:10 pm, amk@amk.ca wrote:
> On Wed, Oct 22, 2003 at 04:36:18PM +0530, dhanvik@gmx.net 
wrote:
> > Any program that would be implemented this way would be
> > bad programming and more than that bad designing of OO
> > structure for the prgram.
>
> No, it's not necessarily bad style.  In fact it's fairly
> common to provide an abstract base class that isn't
> usable on its own; the user is supposed to subclass it
> and provide one method that implements some particular
> behaviour.  A good example from the Python stdlib is the
> SocketServer module, which is used like this:
>
> from SocketServer import ForkingTCPServer
>
> class NNTPServer (ForkingTCPServer):
>     def handle (self):
>         ... process request ...
>
> --amk
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor


From project5 at redrival.net  Wed Oct 22 08:07:38 2003
From: project5 at redrival.net (Andrei)
Date: Wed Oct 22 08:09:52 2003
Subject: [Tutor] Re: Python Class functionality idiosyncrasy..
In-Reply-To: <200310221721.20113.dhanvik@gmx.net>
References: <200310221550.58631.dhanvik@gmx.net>	<200310221636.18552.dhanvik@gmx.net>	<20031022114010.GD1331@rogue.amk.ca>
	<200310221721.20113.dhanvik@gmx.net>
Message-ID: <bn5s2a$9hg$1@sea.gmane.org>

dhanvik@gmx.net wrote:
> Abstract classes have the abstract keyword preceeding then 
> and hence it makes sense for  a reader of the program to 
> know that the function would be implemented in the derived 
> classes..but in this case theres no way of knowing whether 
> the function was defined or not.. 

That's what docstrings are for :). Providing dummy methods which are just meant 
to be implemented by subclasses is extremely common practice indeed; even I do 
it :).

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur 
yvfg, fb gurer'f ab arrq gb PP.



From ms_barry2000 at yahoo.com  Wed Oct 22 08:27:37 2003
From: ms_barry2000 at yahoo.com (=?iso-8859-1?q?Marc=20Barry?=)
Date: Wed Oct 22 08:27:42 2003
Subject: [Tutor] Bit Strings
In-Reply-To: <005801c39852$07468c30$6600a8c0@winxp>
Message-ID: <20031022122737.46247.qmail@web11701.mail.yahoo.com>

Tim:

Here is an example script of what I think you were looking for. It is fairly
simple and doesn't use any recursion. See explanation after script.

#----

def decToBin(dec_number):

	bit_string = ""

	# The following just does simple decimal to binary conversion.
	if(dec_number == 0):
		bit_string = "0"
	else:
		while(dec_number != 0):
			if(dec_number % 2 == 1):
				bit_string = "1" + bit_string
				dec_number = dec_number - 1
				dec_number = dec_number / 2
			else:
				bit_string = "0" + bit_string
				dec_number = dec_number / 2

	return bit_string

def createBitStrings(bit_string_length):

	bit_strings = []
	bit_string = ""

	# This just here to illustrate a point that the maximum decimal number
	# represented by n bits is (2^n)-1. We have to add 1 below when using
	# range because it generates values in the range [start, end).
	max_decimal_number = (2**bit_string_length) - 1

	# This for loop just loops through all the decimal numbers that can be
	# represented by n bits.
	for i in range(0, max_decimal_number + 1):
		bit_string = decToBin(i)
		# At this point the bit string needs to be padded with 0's so
		# that it contains n bits.
		while(len(bit_string) < bit_string_length):
			bit_string = "0" + bit_string
		bit_strings.append(bit_string)

	return bit_strings

# Print the list of bit strings.
print createBitStrings(4)

#---

The output from the above script is:

['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000',
'1001', '1010', '1011', '1100', '1101', '1110', '1111']

Basically, what I have done is created two functions called decToBin and
createBitStrings. The decToBin function takes as input a decimal number and
convertes it to it binary string representation. The createBitStrings function
takes the length of the bit string for which all possible combinations should
be generated. It just loops through all possible decimal numbers, converts them
to binary and pads with 0's as necessary so that you have n bits.

I hope this helps.

Regards,

Marc


 --- "Timothy M. Brauch" <tbrauch@mindless.com> wrote: > There has to be an
easy way to do this that I am just not seeing.  I am
> trying to create all bit strings of length n.  Right now my code is as
> follows:
> 
> bitStrings = []
> for a0 in [0,1]:
>     for a1 in  [0,1]:
>         for a2 in [0,1]:
>             oneString = str(a0)+str(a1)+str(a2)
>             bitStrings.append(oneString)
> print bitStrings
> 
> I know this is ugly and when I need longer strings, say n = 10, the code
> gets way too repetitive with 10 nested for loops.  Surely there is an easier
> way to do this, but I just can't figure it out.  I have a function that will
> generate the above functions, but it is uglier and probably way not the
> correct way to go about this.
> 
> def generator(n):
>     tb = "    "
>     stringMaker = ""
>     print "bitStrings = []"
>     for i in xrange(0,n+1):
>         print i*tb + "for a"+str(i)+" in [0,1]:"
>         stringMaker = stringMaker + "str"+chr(40)+"a"+str(i)+chr(41)+chr(43)
>     stringMaker = stringMaker[:-1] #strip the last chr(43)
>     print (i+1)*tb + "oneString = "+stringMaker
>     print (i+1)*tb + "bitStrings.append(oneString)"
>     print "print bitStrings"
> 
> 
> Any suggestions?
> 
>  - Tim
> 
> 
> ---
> Outgoing mail is certified Virus Free.
> Checked by AVG anti-virus system (http://www.grisoft.com).
> Version: 6.0.528 / Virus Database: 324 - Release Date: 10/17/2003
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor 

________________________________________________________________________
Want to chat instantly with your online friends?  Get the FREE Yahoo!
Messenger http://mail.messenger.yahoo.co.uk

From op73418 at mail.telepac.pt  Wed Oct 22 06:58:34 2003
From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=)
Date: Wed Oct 22 08:29:07 2003
Subject: [Tutor] Python Class functionality idiosyncrasy..
In-Reply-To: <200310221550.58631.dhanvik@gmx.net>
References: <200310221550.58631.dhanvik@gmx.net>
Message-ID: <9sncpv4nu6vt07qlb89c9rl3l95rgolvq0@4ax.com>

On Wed, 22 Oct 2003 15:50:58 +0530, you wrote:

>Dear Friends,
>  While just playing arnd with Python .. I just came across 
>this curious implementation of Python Object Oriented 
>Techniques.. 
>
>The base class here is calling a function of the derived 
>class even befre the function of the derived class is 
>defined..A similar implementation in C++ would not even 
>compile.. My question is doesnt this implementation break 
>some tennants of OO techniques ?? 

What tenets (not tennants I believe :-) are being broken?

>How can the base class 
>call functions of the derived class ?? 
>

I'm not sure I understand your question. Your example below shows how
that is done.

>>>> class base1 :
>...     def baseFunc1( self ):
>...             print "Base class Function"
>...             self.derivedFunc()
>...
>>>> class derived( base1 ):
>...     def derivedFunc(self ):
>...             print "derived Func.."
>...
>>>> b = base1()
>>>> b.baseFunc1()
>Traceback (most recent call last):
>  File "<stdin>", line 1, in ?
>TypeError: unbound method baseFunc1() must be called with 
>base1 instance as first argument (got nothing instead)
>
>>>> d  = derived()
>>>> d.baseFunc1()
>Base class Function
>derived Func..
>>>>
>

This is called the template pattern. You have a base class providing
some functionality implemented in terms of some other, *not*
implemented methods. This class is not meant to be intantiated by
itself, it is what is called an abstract class, and it's customary to
put:

class AbstractClass(object):

    def __init__(self, *args, **kwargs):
        raise NotImplementedError("Class not to be intantiated.")

   ...

What you do is derive from that class and implement the missing
methods. The example you gave explains it: The base class implements a
method baseFunc1 in terms of derivedFunc. If you call it on a base1
instance and it will obviously fail because there is no such method.
But on a derived instance, it does not fail because you have
implemented the derivedFunc method.

Somewhere in the net there are some slides by Alex Martelli (the
martellibot) explaining the template pattern. I'm having trouble with
the internet right now, but I'll get back to you if I can get hold of
the url.

Hope it helps, with my best regards,
G. Rodrigues

From clay at shirky.com  Wed Oct 22 08:31:49 2003
From: clay at shirky.com (Clay Shirky)
Date: Wed Oct 22 08:31:30 2003
Subject: [Tutor] General construction of alpha lists?
In-Reply-To: <20031022111742.GB1331@rogue.amk.ca>
Message-ID: <BBBBF0F5.10104%clay@shirky.com>

> On Tue, Oct 21, 2003 at 09:42:46PM -0400, Clay Shirky wrote:
>> So I have this bit of code:
>>       class_groups[next:next+1] = []
> 
> 'del class_groups[next]' will also work.

...and, as I later figured out, 'print class_groups.pop(next)' actually
combines two lines into one.

I thought perl was the one where there was more than one way to do it? ;)
 
> BTW, there is a random.shuffle() function which generates a permutation of a
> list, though it does it by randomly exchanging list elements.

Right, this isn't so much a pressing need as me exploring the language.

> Easiest is probably list(string.ascii_letters),

Perfect, thanks.

The chr(next+65) thing had also occurred to me, but seemed too bletcherous.

-c

> list(string.ascii_lowercase).  string.letters is the list of letters for the
> current locale, and therefore will usually include a bunch of accented
> characters; the .ascii_* variables are fixed.
> 
> --amk
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


From rhseabrook at aacc.edu  Wed Oct 22 09:12:24 2003
From: rhseabrook at aacc.edu (Seabrook, Richard)
Date: Wed Oct 22 09:12:25 2003
Subject: FW: [Tutor] Bit Strings  [an iterative approach]
Message-ID: <74DAD2F23F03F7438D9BE3436C6846F701290940@AACC-MAIL.aacc.cc.md.us>




-----Original Message-----
From:	Timothy M. Brauch [mailto:tbrauch@mindless.com]
Sent:	Wed 10/22/2003 3:48 AM
To:	Python Tutor
Cc:	
Subject:	Re: [Tutor] Bit Strings  [a recursive approach]
Whilst trying to find all bit strings of a certain length, I struggled.
Danny Yoo was helpful with:

> Have you tried a recursive approach?  It might be useful to outline how to
> solve this recursively, so here goes!  *grin*

============================
I'd not give up the iterative approach so quickly.
As others have noted, you can generate the set of values you want
but merely counting up to 2^N.  However, the values seldom have leading
0 padding to make them N-digit binary numbers, easily convertable to
bit-strings, so the old-fashioned solution is to start counting
at 2^N and count up to 2^(N+1)-1, converting the right-most N digits
in each case.   For example, to get all bit strings of size 5, start
at 2^5 = 32 and count up to 2^(5+1)-1 = 63 converting the right-most
5 digits, like this:
    100000
    100001
    100010
    100011
      ...
      ...
    111111
Dick S.


From druidmatt at yahoo.com  Wed Oct 22 10:47:46 2003
From: druidmatt at yahoo.com (Matt Hehman)
Date: Wed Oct 22 10:47:58 2003
Subject: [Tutor] Re: Request for code critique
Message-ID: <20031022144746.48588.qmail@web10309.mail.yahoo.com>

Well, here goes.  Some of the comments wrapped, as did
two of the longer lines, which I stuck in parentheses,
so this should be about right.  Besides anything
really glaring, what would I need to do if this was
going to be a mere feature of a much longer program?  

##retrieve list of known primes
import shelve
d=shelve.open('primesfile')
primes=d['primesfile']
##defines function for finding common factors
def Euclid(a,b):
    while b>0:
        a,b=b,a%b
    return a
##user inputs number for testing
(bignum=input("Enter a number to evaluate for
primeness."))
##upper limit for primes to be tested
ceiling=int(bignum**0.5)
##new primes are calculated if current list is
##insufficient
if primes[-1]+1<ceiling:
    candidates=range((primes[-1]+2),ceiling+1,2)
    n=1
    result=[]
    while candidates:
        limit=int(candidates[0]**0.5)
        while primes[n]<=limit and len(candidates)>0:
            limit=int(candidates[0]**0.5)
            if candidates[0]%primes[n]==0:
                del candidates[0]
                n=0
            n=n+1
        if len(candidates)>0:
            result.append(candidates[0])
            del candidates[0]
            n=1
##newly generated primes are saved to file
    primes.extend(result)
    d['primesfile']=primes
    d.close
##primes generated/retrieved are tested as possible
##factors
##progressively slower with larger numbers - next
##planned revision
factors=[]
while primes and primes[0]<ceiling+1:
    if Euclid(bignum,primes[0])>1:
        factors.append(Euclid(bignum,primes[0]))
    del primes[0]
if factors:
    (print bignum,"is not a prime.  Its prime factors
up to its square root include:",factors)
else:
    print bignum,"is prime."



__________________________________
Do you Yahoo!?
SBC Yahoo! DSL - Now only $29.95 per month!
http://sbc.yahoo.com

From m.evanetich at att.net  Wed Oct 22 10:49:38 2003
From: m.evanetich at att.net (m.evanetich@att.net)
Date: Wed Oct 22 10:49:45 2003
Subject: [Tutor] Question about tkFileDialog
Message-ID: <102220031449.3797.4bbd@att.net>

I am attempting to write a simple data consolidation script that opens files 
in subtrees and combines the data into a single file at the root.  The script 
starts by asking the user to specify a subtree.  Currently I am stumped by 
the behavior of tkFileDialog. When I try:

>>> import tkFileDialog
>>> projectFolder = tkFileDialog.askdirectory(initialdir='c:/projectDev',
...                                            mustexist=1,
...                                            title='Choose root directory 
for the desired project.')
>>> print projectFolder
C:/projectDev/Foo

I get the desired result, but I also get a small application named tk on my 
desktop and with a taskbar button that I cannot close as a side effect.  It 
is disconcerting and I have not found a way to banish it.  Can anyone point 
me to the relevant documentation or provide advice?

Thank you.

--
Mark Evanetich
> Send Tutor mailing list submissions to
> 	tutor@python.org
> 
> To subscribe or unsubscribe via the World Wide Web, visit
> 	http://mail.python.org/mailman/listinfo/tutor
> or, via email, send a message with subject or body 'help' to
> 	tutor-request@python.org
> 
> You can reach the person managing the list at
> 	tutor-owner@python.org
> 
> When replying, please edit your Subject line so it is more specific
> than "Re: Contents of Tutor digest..."
> 
> 
> Today's Topics:
> 
>    1. Re: this is ugly (Andrei)
>    2. Request for code critique (Matt Hehman)
>    3. Re: Request for code critique (Clay Shirky)
>    4. Re: Request for code critique (Andrei)
>    5. can someone explain to me how this works (Conrad Koziol)
>    6. Re: can someone explain to me how this works  [comparsion
>       functions and sort()] (Danny Yoo)
>    7. can someone explain to me how this works (Conrad Koziol)
>    8. Re: 2nd Python Book (Erik Price)
>    9. Nested Lists / Array Module (Harm_Kirchhoff@mail.digital.co.jp)
>   10. Re: Nested Lists / Array Module (Andrei)
>   11. Re: Nested Lists / Array Module (Danny Yoo)
>   12. General construction of alpha lists? (Clay Shirky)
>   13. Timing a loop (Ben Mazer)
> 
> 
> ----------------------------------------------------------------------
> 
> Message: 1
> Date: Wed, 22 Oct 2003 00:05:26 +0200
> From: Andrei <project5@redrival.net>
> Subject: [Tutor] Re: this is ugly
> To: tutor@python.org
> Message-ID: <bn4an6$b68$1@sea.gmane.org>
> Content-Type: text/plain; charset=us-ascii; format=flowed
> 
> Alan Gauld wrote:
> >>Can line 3 of the following be improved (especially since I might
> > 
> > want
> > 
> >>to search for even more strings within each line):
> >>
> >>myfile=open(r'F:\logs\myfile.txt', 'r')
> >>for line in myfile.readlines():
> >>   if line.find("KeC 923") != -1 or line.find("ZEF 156") != -1 or
> >>line.find("pBX 88347") != -1 or line.find("FZX 17255") != -1:
> >>         #code if found
> > 
> > 
> > Yes use a regular expression. You can combine conditions in one
> > expression and it will only search the string once instead of
> > once per condition.
> > 
> > I'll leave it to someone else to explain how to combine the
> > regexs! I'm going to bed and my brain is tired.... :-)
> 
> Well, here's a RE which would match any of those things:
> 
>    KeC 923|ZEF 156|pBX 88347|FZX 17255
> 
> I don't know if evaling that regex would be faster/easier than using the 
> find methods, especially not with one of the shortcut notations 
> mentioned earlier in this thread. Perhaps a more generic RE would be in 
> order, e.g.:
> 
>    \S{3}\s\d{3,5}
> 
> which (if compiled with the IGNORECASE flag) matches any sequence of 3 
> letters followed by a space and 3 to 5 digits. Of course I don't know 
> the type of input, perhaps this would match more than desired.
> 
> -- 
> Yours,
> 
> Andrei
> 
> =====
> Mail address in header catches spam. Real contact info (decode with rot13):
> cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V 
> ernq gur yvfg, fb gurer'f ab arrq gb PP.
> 
> 
> 
> 
> 
> ------------------------------
> 
> Message: 2
> Date: Tue, 21 Oct 2003 15:10:23 -0700 (PDT)
> From: Matt Hehman <druidmatt@yahoo.com>
> Subject: [Tutor] Request for code critique
> To: tutor@python.org
> Message-ID: <20031021221023.98586.qmail@web10309.mail.yahoo.com>
> Content-Type: text/plain; charset=us-ascii
> 
> I've written a program of about 40 lines including
> comments.  I am teaching myself to program in my spare
> time, working through the various online tutorials.  I
> started with "Instant Hacking" by Hetland and built on
> the example to calculate prime numbers.  Basically, I
> looked for better ways to do it, then expanded its
> functionality by throwing code at it and seeing what
> stuck.  Before I try to refine it any further, I think
> it would be good to get some feedback before I develop
> any bad habits.  Rather than clog your inboxes by way
> of asking for a big favor, any volunteers, please
> e-mail me directly.
> 
> Thanks,
> Matt Hehman
> 
> __________________________________
> Do you Yahoo!?
> SBC Yahoo! DSL - Now only $29.95 per month!
> http://sbc.yahoo.com
> 
> 
> 
> ------------------------------
> 
> Message: 3
> Date: Tue, 21 Oct 2003 18:19:24 -0400
> From: Clay Shirky <clay@shirky.com>
> Subject: Re: [Tutor] Request for code critique
> To: Matt Hehman <druidmatt@yahoo.com>,	<tutor@python.org>
> Message-ID: <BBBB292C.10069%clay@shirky.com>
> Content-Type: text/plain; charset="US-ASCII"
> 
> > I've written a program of about 40 lines including
> > comments.  I am teaching myself to program in my spare
> > time, working through the various online tutorials.  I
> > started with "Instant Hacking" by Hetland and built on
> > the example to calculate prime numbers.  Basically, I
> > looked for better ways to do it, then expanded its
> > functionality by throwing code at it and seeing what
> > stuck.  Before I try to refine it any further, I think
> > it would be good to get some feedback before I develop
> > any bad habits.  Rather than clog your inboxes by way
> > of asking for a big favor, any volunteers, please
> > e-mail me directly.
> 
> As a fellow newbie, I'd love to see it, and I'm sure it makes more sense to
> post it here than to do it via CC. That sort of thing is what tutor is good
> for.
> 
> -clay
> 
> 
> 
> 
> ------------------------------
> 
> Message: 4
> Date: Wed, 22 Oct 2003 00:21:21 +0200
> From: Andrei <project5@redrival.net>
> Subject: [Tutor] Re: Request for code critique
> To: tutor@python.org
> Message-ID: <bn4bl1$fu5$1@sea.gmane.org>
> Content-Type: text/plain; charset=us-ascii; format=flowed
> 
> Clay Shirky wrote:
> 
> >>I've written a program of about 40 lines including
> >>comments.  I am teaching myself to program in my spare
> >>time, working through the various online tutorials.  I
> >>started with "Instant Hacking" by Hetland and built on
> >>the example to calculate prime numbers.  Basically, I
> >>looked for better ways to do it, then expanded its
> >>functionality by throwing code at it and seeing what
> >>stuck.  Before I try to refine it any further, I think
> >>it would be good to get some feedback before I develop
> >>any bad habits.  Rather than clog your inboxes by way
> >>of asking for a big favor, any volunteers, please
> >>e-mail me directly.
> > 
> > 
> > As a fellow newbie, I'd love to see it, and I'm sure it makes more sense to
> > post it here than to do it via CC. That sort of thing is what tutor is good
> > for.
> 
> I agree, I can fit more than 50 lines of code on my screen so 40 doesn't 
> seem like such a big problem. Make sure your mail interface doesn't 
> break the code though.
> 
> -- 
> Yours,
> 
> Andrei
> 
> =====
> Mail address in header catches spam. Real contact info (decode with rot13):
> cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V 
> ernq gur yvfg, fb gurer'f ab arrq gb PP.
> 
> 
> 
> 
> 
> ------------------------------
> 
> Message: 5
> Date: Tue, 21 Oct 2003 15:42:42 -0700
> From: Conrad Koziol <arkamir@softhome.net>
> Subject: [Tutor] can someone explain to me how this works
> To: tutor@python.org
> Message-ID: <1066776162.5035.4.camel@quercus>
> Content-Type: text/plain
> 
> Hey thanks for the tips !!!
> 
> def compare(a,b):
>          if a[1]>b[1]: return 0
>          else: return -1
> 
> i tried this out and it works, but i dont understand the logic behind it
> :(
> can someone help me out
> 
> i also dont get how it compares all the tuples in a list. Dont you need to enter
> in two values not just one list?????
> 
> 
> 
> ------------------------------
> 
> Message: 6
> Date: Tue, 21 Oct 2003 16:13:22 -0700 (PDT)
> From: Danny Yoo <dyoo@hkn.eecs.berkeley.edu>
> Subject: Re: [Tutor] can someone explain to me how this works
> 	[comparsion	functions and sort()]
> To: Conrad Koziol <arkamir@softhome.net>
> Cc: tutor@python.org
> Message-ID:
> 	<Pine.LNX.4.44.0310211601260.20770-100000@hkn.eecs.berkeley.edu>
> Content-Type: TEXT/PLAIN; charset=US-ASCII
> 
> 
> 
> On Tue, 21 Oct 2003, Conrad Koziol wrote:
> 
> > Hey thanks for the tips !!!
> >
> > def compare(a,b):
> >          if a[1]>b[1]: return 0
> >          else: return -1
> >
> > i tried this out and it works, but i dont understand the logic behind it
> > :( can someone help me out
> 
> Hi Conrad,
> 
> A "comparison function" is something that takes two things, and checks to
> see if one is smaller than another.  In math notation:
> 
>     compare(a,b)  =    {  -1     if a < b
>                            0     if a == b
>                            1     if a > b
>                        }
> 
> The important thing to see is that a comparison function is not meant to
> be a "boolean" true-false thing: it's meant to return either a positive,
> zero, or negative value.
> 
> Is this what's confusing, or is it something else?  Please feel free to
> ask more questions about this, as it is definitely a confusing topic when
> we first see it.
> 
> 
> 
> > i also dont get how it compares all the tuples in a list. Dont you need
> > to enter in two values not just one list?????
> 
> Yes, this would be true if we were directly calling compare() on the list
> itself.  However, that's not what's happening: instead, we're calling
> sort, and sort() itself is calling compare() on pairs of elements on our
> list.
> 
> 
> Here's a concrete toy example of a similar situation:
> 
> ###
> >>> def applyOnList(function, L):
> ...     """Destructivly applies a 'function' on the list 'L'."""
> ...     for index, element in enumerate(L):
> ...         L[index] = function(element)
> ...
> >>> def square(x): return x * x
> ...
> >>> numbers = range(10)
> >>> applyOnList(square, numbers)
> >>> numbers
> [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
> ###
> 
> In this case, we've written a function called applyOnList() that takes in
> a function, as well as a list of things.  Notice that the function we pass
> in isn't being called on the whole list, but only on single elements of
> that list.
> 
> 
> sort() does something somewhat similar when it takes in that comparison
> function.  sort() uses it as a helper toward some greater goal --- sorting
> things --- but doesn't need to try applying it to the whole list at once.
> 
> 
> Hope that made some sort of sense.  *grin* Please feel free to ask more
> questions: if you'd like, we can talk about how comparsion functions
> actually help sort() figure out how to sort.
> 
> 
> 
> 
> ------------------------------
> 
> Message: 7
> Date: Tue, 21 Oct 2003 15:42:42 -0700
> From: Conrad Koziol <arkamir@softhome.net>
> Subject: [Tutor] can someone explain to me how this works
> To: tutor@python.org
> Message-ID: <1066776162.5035.4.camel@quercus>
> Content-Type: text/plain
> 
> Hey thanks for the tips !!!
> 
> def compare(a,b):
>          if a[1]>b[1]: return 0
>          else: return -1
> 
> i tried this out and it works, but i dont understand the logic behind it
> :(
> can someone help me out
> 
> i also dont get how it compares all the tuples in a list. Dont you need to enter
> in two values not just one list?????
> 
> 
> 
> ------------------------------
> 
> Message: 8
> Date: Tue, 21 Oct 2003 20:43:41 -0400
> From: Erik Price <erikprice@mac.com>
> Subject: Re: [Tutor] 2nd Python Book
> To: John Duarte <john@duartedailey.org>
> Cc: tutor@python.org
> Message-ID: <C8614AFE-0428-11D8-ADEC-00039351FE6A@mac.com>
> Content-Type: text/plain; charset=US-ASCII; format=flowed
> 
> 
> On Monday, October 20, 2003, at 06:37  PM, John Duarte wrote:
> 
> > I have seen recommendations for a first Python book, ie Alan Guald's 
> > Learn to
> > Program Using Python, and Lutz & Asher's Learning Python. (Which are 
> > both
> > terrific books!)
> >
> > I was wondering if anyone could recommend a '2nd book'.
> 
> The Python Cookbook.  You already know Python, this book teaches you 
> how to do specific tasks or sophisticated programming idioms specific 
> to Python.  It's one of my favorite Python books.
> 
> > I was glancing through Deitel & Deitel's How to Program Python, and it 
> > looks
> > very thorough. Are their any opinions about this book specifically.
> 
> I didn't even know these guys had a Python book.  Neat.
> 
> 
> 
> Erik
> 
> 
> 
> 
> ------------------------------
> 
> Message: 9
> Date: Wed, 22 Oct 2003 09:07:57 +0900
> From: Harm_Kirchhoff@mail.digital.co.jp
> Subject: [Tutor] Nested Lists / Array Module
> To: tutor@python.org
> Message-ID:
> 	
> <OFD7D369B7.88885204-ON49256DC6.00830C0C-49256DC7.00009D65@jp.schneider-electric
> .com>
> 	
> Content-Type: text/plain; charset="us-ascii"
> 
> Python supports nested lists, which is very nice and can be used for very 
> simple databases.
> 
> However, I could not find a way to write nested lists to files & retrieve 
> them easily.
> The .writelines() method expects a string as an argument.
> 
> Is there a method to dump any list on disk & read it back, or is it 
> necessary to code this task ?
> 
> The array module seems to have such method, however, I could not find 
> sufficient code examples to understand how the array module works. The 
> Python Library Reference mentions the .fromfile() and .tofile() methods, 
> does anyone have experience with the array module, especially whether it 
> allows to write & retrieve nested arrays without problems ? Could you pass 
> me some sample code ?
> 
>  
> Harm 
> 
> 
> 
> 
> ------------------------------
> 
> Message: 10
> Date: Wed, 22 Oct 2003 02:33:27 +0200
> From: Andrei <project5@redrival.net>
> Subject: [Tutor] Re: Nested Lists / Array Module
> To: tutor@python.org
> Message-ID: <bn4jcm$1jt$1@sea.gmane.org>
> Content-Type: text/plain; charset=us-ascii; format=flowed
> 
> Harm_Kirchhoff@mail.digital.co.jp wrote:
> > Python supports nested lists, which is very nice and can be used for very 
> > simple databases.
> > 
> > However, I could not find a way to write nested lists to files & retrieve 
> > them easily.
> > The .writelines() method expects a string as an argument.
> > 
> > Is there a method to dump any list on disk & read it back, or is it 
> > necessary to code this task ?
> 
> Not too long ago a similar question (or was it the same?) was on the list
> I believe. You can either pickle or convert your list to a string using 
> str(),
> e.g. str(MyList). It doesn't matter how deep that list is.
> 
> <snip>
> 
> -- 
> Yours,
> 
> Andrei
> 
> =====
> Mail address in header catches spam. Real contact info (decode with rot13):
> cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V 
> ernq gur yvfg, fb gurer'f ab arrq gb PP.
> 
> 
> 
> 
> 
> ------------------------------
> 
> Message: 11
> Date: Tue, 21 Oct 2003 17:54:28 -0700 (PDT)
> From: Danny Yoo <dyoo@hkn.eecs.berkeley.edu>
> Subject: Re: [Tutor] Nested Lists / Array Module
> To: Harm_Kirchhoff@mail.digital.co.jp
> Cc: tutor@python.org
> Message-ID:
> 	<Pine.LNX.4.44.0310211749100.27613-100000@hkn.eecs.berkeley.edu>
> Content-Type: TEXT/PLAIN; charset=US-ASCII
> 
> 
> 
> On Wed, 22 Oct 2003 Harm_Kirchhoff@mail.digital.co.jp wrote:
> 
> > Python supports nested lists, which is very nice and can be used for very
> > simple databases.
> >
> > However, I could not find a way to write nested lists to files &
> > retrieve them easily. The .writelines() method expects a string as an
> > argument.
> >
> > Is there a method to dump any list on disk & read it back, or is it
> > necessary to code this task ?
> 
> 
> Hi Harm,
> 
> Yes.  For simple cases, the 'shelve' module can help to "serialize"
> these nested structures to and from disk.  "Serialization" is a term we
> use to transform arbitrary Python objects to byte strings, and it's pretty
> easy to do in Python.
> 
> In fact, we talked about this about a week ago:
> 
>     http://mail.python.org/pipermail/tutor/2003-October/025741.html
> 
> The example at that link uses only a flat list, but 'shelve' should work
> with lists in lists too.
> 
> 
> If you have more questions, please feel free to ask.  Good luck!
> 
> 
> 
> 
> ------------------------------
> 
> Message: 12
> Date: Tue, 21 Oct 2003 21:42:46 -0400
> From: Clay Shirky <clay@shirky.com>
> Subject: [Tutor] General construction of alpha lists?
> To: <tutor@python.org>
> Message-ID: <BBBB58D6.1009C%clay@shirky.com>
> Content-Type: text/plain; charset="US-ASCII"
> 
> So I have this bit of code:
> 
> class_groups = [ 'A', 'B', 'C', 'D', 'E' ]
> 
> while class_groups:
>       next = random.choice( range( len(class_groups) ))
>       print class_groups[next]
>       class_groups[next:next+1] = []
> 
> which will give me some random permutation of the items in the list
> class_groups.
> 
> Next stop, making it possible to generate an alphabetical list, based on the
> array number. I'd like to do something like
> 
> class_groups = range(12)
> 
> and then have it print from A through L. Is there an easy way to specify a
> list that is simply letters in order, or do I have to write out
> 
> alpha = [ 'A', 'B', ... 'Z', 'a', 'b', ... 'z' ]
> 
> Thanks
> 
> -clay
> 
> 
> 
> 
> ------------------------------
> 
> Message: 13
> Date: Tue, 21 Oct 2003 23:08:05 -0400
> From: Ben Mazer <contrasutra@myrealbox.com>
> Subject: [Tutor] Timing a loop
> To: tutor@python.org
> Message-ID: <3F95F495.4050102@myrealbox.com>
> Content-Type: text/plain; charset=us-ascii; format=flowed
> 
> I have written a small script that creates a bunch of small text files. 
> I'm doing this because I want to benchmark file creation/deletion times 
> on different file systems.
> 
> Im looking right now about how to time how long it takes to create the 
> files. I looked at the Timeit() module, and that doesn't seem to work, 
> its for small algorithms.
> 
> I also looked at time.clock(), but I can't get that to display an 
> accurate readout, so I dont think that works (or Im not using it right).
> 
> I know I could use the UNIX "time" command, but it would be nice if 
> Python had a built in function. They probably do, but I can't find it. :P
> 
> Any help you could provide on timing a loop would be really helpful.
> 
> OT: How many files can reiserfs hold? I keep hitting "file system full" 
> limits when I get into large amounts of files (hundreds of thousands).
> 
> Thanks.
> -- 
> /"\ Ben Mazer <contrasutra@myrealbox.com>
> \ /
>   X  ASCII RIBBON CAMPAIGN AGAINST HTML MAIL
> / \
> 
> 
> 
> 
> ------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
> End of Tutor Digest, Vol 3, Issue 37
> ************************************

From m.evanetich at att.net  Wed Oct 22 11:22:28 2003
From: m.evanetich at att.net (m.evanetich@att.net)
Date: Wed Oct 22 11:22:33 2003
Subject: [Tutor] Re: Tutor Digest, Vol 3, Issue 40
Message-ID: <102220031522.6599.73c4@att.net>

My apology for including the digest.  It was a newbie mistake.

--
Mark Evanetich

From dyoo at hkn.eecs.berkeley.edu  Wed Oct 22 12:25:30 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Oct 22 12:26:16 2003
Subject: [Tutor] Bit Strings  [a recursive approach / Herbert Wilf's
	Algorithms and Complexity]
In-Reply-To: <009a01c39870$f4402730$6600a8c0@winxp>
Message-ID: <Pine.LNX.4.44.0310220915180.24299-100000@hkn.eecs.berkeley.edu>


> I guess I just didn't realize what I was doing by hand would have worked
> if I had coded it correctly.  And, the nice thing about this is that it
> should be pretty easy to extend the idea if my strings need to have more
> characters.  Just a few more base cases and the else:return needs to be
> have a few more lines. Thanks.

Hi Timothy,

Yes, the recursive approach generalizes easily beyond binary strings.  So
you should be able to get this done well before the weekend.  *grin*


> P.S. I guess it is the mathematician in me that doesn't like recursively
> defined functions.  We tend to like closed form things better.  And it
> was my stumbling block in my algorithm classes.  Although, recursive is
> often much more elegant...

By the way, I just discovered that the mathematician Herbert Wilf has made
his book "Algorithms and Complexity", freely available from his web site!

    http://www.cis.upenn.edu/%7Ewilf/AlgComp2.html

It's a nice 2**6 pages of quirky mathy goodness.  Chapter 2 gives a talk
about recursive algorithms, so this is not totally off topic.  *grin* I
wish I had seen it earlier, as well as his other book
"generatingfunctionology", which is also available off his web site.


From python at dhumketu.cjb.net  Wed Oct 22 06:57:59 2003
From: python at dhumketu.cjb.net (Shantanoo Mahajan)
Date: Wed Oct 22 13:36:35 2003
Subject: [Tutor] Re: Nested Lists / Array Module
In-Reply-To: <OFD7D369B7.88885204-ON49256DC6.00830C0C-49256DC7.00009D65@jp.schneider-electric.com>
References: <OFD7D369B7.88885204-ON49256DC6.00830C0C-49256DC7.00009D65@jp.schneider-electric.com>
Message-ID: <20031022105759.GA219@dhumketu.homeunix.net>

  +-- Harm_Kirchhoff@mail.digital.co.jp [python-tutor] [22-10-03 05:37 IST]:
  | Python supports nested lists, which is very nice and can be used for very 
  | simple databases.
  | 
  | However, I could not find a way to write nested lists to files & retrieve 
  | them easily.
  | The .writelines() method expects a string as an argument.
  | 
  | Is there a method to dump any list on disk & read it back, or is it 
  | necessary to code this task ?
  | 
  | The array module seems to have such method, however, I could not find 
  | sufficient code examples to understand how the array module works. The 
  | Python Library Reference mentions the .fromfile() and .tofile() methods, 
  | does anyone have experience with the array module, especially whether it 
  | allows to write & retrieve nested arrays without problems ? Could you pass 
  | me some sample code ?
  | 
  |  
  | Harm 

import pickle
f=open('test','w+')
a=[[1,2,3,4],[1,2,[123]]]
pickle.dump(a,f)
f.seek(0)
b=pickle.load(f)
print a,b


-- 
With Best Regards,
Shantanoo Mahajan

From project5 at redrival.net  Wed Oct 22 13:59:41 2003
From: project5 at redrival.net (Andrei)
Date: Wed Oct 22 14:02:01 2003
Subject: [Tutor] Re: Request for code critique
In-Reply-To: <20031022144746.48588.qmail@web10309.mail.yahoo.com>
References: <20031022144746.48588.qmail@web10309.mail.yahoo.com>
Message-ID: <bn6gmj$v4n$1@sea.gmane.org>

Matt Hehman wrote:

> Well, here goes.  Some of the comments wrapped, as did
> two of the longer lines, which I stuck in parentheses,
> so this should be about right.  Besides anything
> really glaring, what would I need to do if this was
> going to be a mere feature of a much longer program?  

For one thing, wrap everything up in classes or at the very least functions. If 
you import your module in a larger program, everything is executed at import 
time so the larger program can't really use it. Not to mention that if you 
program without classes (and even more so when you program without functions), 
the results are unmaintainable.

<snip>
> ##new primes are calculated if current list is
> ##insufficient
> if primes[-1]+1<ceiling:
>     candidates=range((primes[-1]+2),ceiling+1,2)

For the sake of clarity, I think it would be better if you added 1 to ceiling 
the first time you defined it.

>     n=1
>     result=[]

Why do you need results? You could just as well work directly on your primes 
list. Btw, I prefer spaces to the left and right of equal signs and to the richt 
of commas; makes code easier to read.

>     while candidates:
>         limit=int(candidates[0]**0.5)
>         while primes[n]<=limit and len(candidates)>0:
>             limit=int(candidates[0]**0.5)
>             if candidates[0]%primes[n]==0:
>                 del candidates[0]
>                 n=0
>             n=n+1
>         if len(candidates)>0:
>             result.append(candidates[0])
>             del candidates[0]
>             n=1

You should look into the pop() method which deletes an item and returns it as 
well. Also I think that your while-solution is not as pythonic as it could be 
(making it harder to follow for me). It's more common to use a break statement 
than to define a loop variable outside the while-loop:

# no limit variable outside the while loop
while len(candidates)>0:
     limit = int(candidates[0] ** 0.5)
     if primes[n]>limit: # stops the loop
         break
     # the rest of your code

Regardless of this, I'm not sure that deleting items is the fastest possible way 
to do it. In fact, I'm tempted to think that looping through the items in 
candidates would be faster (and IMO looks better too), using a for-loop:

for candidate in candidates:
     # find out if the candidate is indeed a prime
     limit = int(candidate ** 0.5)
     for prime in primes:
         if prime > limit:
             # we've found a new prime, go to next one
             primes.append(candidate)
             break
         elif candidate % prime == 0:
             # candidate is not a prime, go to next one
             break

This does assume that you start out with primes containing at least [2, 3] and 
is 50% shorter than your solution (not counting comments). Bonus points if you 
can get that in a list comprehension :).

> ##progressively slower with larger numbers - next
> ##planned revision
> factors=[]
> while primes and primes[0]<ceiling+1:
>     if Euclid(bignum,primes[0])>1:
>         factors.append(Euclid(bignum,primes[0]))
>     del primes[0]

Again, I think a for-loop might be more appropriate here, looping "for prime in 
primes".

<snip>

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur 
yvfg, fb gurer'f ab arrq gb PP.



From jim_938 at hotmail.com  Wed Oct 22 14:18:43 2003
From: jim_938 at hotmail.com (Jimmy verma)
Date: Wed Oct 22 14:18:48 2003
Subject: [Tutor] xml question
Message-ID: <Sea1-F132V6ASUc9LNY000238ea@hotmail.com>

Hello,

I am getting caught in a problem for which i need some suggestions.

I have an xml file like

<XYZ Version="0">
    <header>
       <A = "1"/>
       <B = "2"/>
       <C = "0"/>
       <D = "0"/>
       <E = "0"/>
    </header>

    <dir>
       <table0>
          <P = "0"/>
          <Q = "1"/>
          <R = "2"/>
          <S = "3"/>
       </table0>
       <table1>
          <P = "4"/>
          <Q= "5"/>
          <R = "6"/>
          <S = "7"/>
       </table1>
     <\dir>

<\XYZ>

I want to make two tables out of this: one is 'header' and other is 'dir'.

Tables can be in the form of list:


like
header = [1,2,0,0,0]

dir = [ [0,1,2,3], [4,5,6,7] ]


I just want the values in the tables not the tags. Is there some pythonic 
way of doing it.


Thanks in advance.

Regards,

J+

_________________________________________________________________
Special offer from American Express.Don't miss out. 
http://server1.msn.co.in/features/amex/index.asp  Apply now!


From klappnase at freenet.de  Wed Oct 22 14:27:07 2003
From: klappnase at freenet.de (Michael Lange)
Date: Wed Oct 22 14:25:06 2003
Subject: [Tutor] Question about tkFileDialog
In-Reply-To: <102220031449.3797.4bbd@att.net>
References: <102220031449.3797.4bbd@att.net>
Message-ID: <20031022202707.54488a8d.klappnase@freenet.de>

On Wed, 22 Oct 2003 14:49:38 +0000
m.evanetich@att.net wrote:

> I am attempting to write a simple data consolidation script that opens files 
> in subtrees and combines the data into a single file at the root.  The script 
> starts by asking the user to specify a subtree.  Currently I am stumped by 
> the behavior of tkFileDialog. When I try:
> 
> >>> import tkFileDialog
> >>> projectFolder = tkFileDialog.askdirectory(initialdir='c:/projectDev',
> ...                                            mustexist=1,
> ...                                            title='Choose root directory 
> for the desired project.')
> >>> print projectFolder
> C:/projectDev/Foo
> 
> I get the desired result, but I also get a small application named tk on my 
> desktop and with a taskbar button that I cannot close as a side effect.  It 
> is disconcerting and I have not found a way to banish it.  Can anyone point 
> me to the relevant documentation or provide advice?
> 
> Thank you.
> 
Hi, 

the File Dialog window is called as a Toplevel window of a Tk window that is usually defined before.
If you haven't defined this root window before, it is automatically created (otherwise an exception had
to be raised). I must admit I have never tried this before, but that seems to be what happens here.
If you don't want to see the root window, try this:

>>> from Tkinter import *
>>> import tkFileDialog
>>> r = Tk()
>>> r.withdraw()# removes r from the screen
''
>>> f = tkFileDialog.askdirectory(<options>)
>>>etc.

Hope this helps

Michael

From project5 at redrival.net  Wed Oct 22 14:34:51 2003
From: project5 at redrival.net (Andrei)
Date: Wed Oct 22 14:37:03 2003
Subject: [Tutor] Re: Request for code critique
In-Reply-To: <bn6gmj$v4n$1@sea.gmane.org>
References: <20031022144746.48588.qmail@web10309.mail.yahoo.com>
	<bn6gmj$v4n$1@sea.gmane.org>
Message-ID: <bn6ioa$416$1@sea.gmane.org>

Andrei wrote:

> Matt Hehman wrote:
> 
> for candidate in candidates:
>     # find out if the candidate is indeed a prime
>     limit = int(candidate ** 0.5)
>     for prime in primes:
>         if prime > limit:
>             # we've found a new prime, go to next one
>             primes.append(candidate)
>             break
>         elif candidate % prime == 0:
>             # candidate is not a prime, go to next one
>             break
> 
> This does assume that you start out with primes containing at least [2, 
> 3] and is 50% shorter than your solution (not counting comments). Bonus 
> points if you can get that in a list comprehension :).

Just because I like torturing myself (don't ask), I ended up writing the 
comprehension too:

[ primes.append(C) for C in candidates if not [1 for P in primes if not C%P ] ]

Much shorter, but I should point out that when running up to 100000000, the 
comprehension is 30-50 times slower than the explicit for-loops :).
The while loop in Matt's code is ~3 times slower than the for-loops.

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur 
yvfg, fb gurer'f ab arrq gb PP.



From alan.gauld at blueyonder.co.uk  Wed Oct 22 14:46:39 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Wed Oct 22 14:45:50 2003
Subject: [Tutor] Python Class functionality idiosyncrasy..
References: <200310221550.58631.dhanvik@gmx.net>
Message-ID: <011201c398cc$d416f310$6401a8c0@xp>

> The base class here is calling a function of the derived 
> class even befre the function of the derived class is 
> defined..

Actually its not actually calling it at that point. 
Its just a reference stored for future resolution. 
It doesn't actually call the function until the method 
gets called.

> A similar implementation in C++ would not even 
> compile.. 

In fact you can do this in C++ but it involves some 
clever magic using templates. Stroustrup gives an 
example in his book "The Design & Evolution of C++"

> My question is doesnt this implementation break 
> some tennants of OO techniques ?? How can the base class 
> call functions of the derived class ?? 

It isn't in an OO sense doing that, its simply sending 
a message to itself. The fact that the implementation 
is in the baseclass is irrelevant. It simply means that 
the class cannot be safely used on its own. This 
technique is most commonly used in the OO style known 
as "mixin" programming. This technique is possible in 
many OO languages including C++, Lisp, Smalltalk (via 
class methods I think) and I suspect Objective C plus 
others - almost any dynamically dispatched message 
based implenentation. Its a good example of the very real
difference between sending a message and calling a 
function!

PS IN Java you could implement the same design trick by 
defining an interface...

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


From tpc at csua.berkeley.edu  Wed Oct 22 14:52:12 2003
From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu)
Date: Wed Oct 22 14:52:36 2003
Subject: [Tutor] xml question
In-Reply-To: <Sea1-F132V6ASUc9LNY000238ea@hotmail.com>
Message-ID: <20031022114638.R49312-100000@localhost.name>


hi Jimmy,

If you want to extract the PCDATA from your XML file you may want to look
at xmllib:

http://www.python.org/doc/current/lib/module-xmllib.html

I have experience parsing XHTML with HTMLParser.HTMLParser and I imagine
this class shouldn't be that much different.  Here's an example of an
XHTML Parser that ignores stuff inside <style> (which for me tends to
break parsing of the page), gathers title and content, and keeps a list
of last element parsed of a page before encountering an error:

class XHTMLParser(HTMLParser.HTMLParser):
# Simple class used to parse title and text outside of XHTML tags.
# Also stores a list of XHTML pages that contained errors.

        def __init__(self):
                HTMLParser.HTMLParser.__init__(self)
                self.extracted_text = ''
                self.title = ''
                self.in_title = False
                self.in_style = False
                self.last_parsed_tag = ''

        def handle_starttag(self, tag, attrs):
                length = len(attrs)
                if length == 0:
                        self.last_parsed_tag = ' Last parsed element: <' +
tag + '>'
                        if (tag == "title"):
                                self.in_title = True
                        elif (tag == "style"):
                                self.in_style = True
                elif length > 0:
                        strattrs = ''.join([ ' %s="%s"' % (key, value) for
key, value in attrs])
                        self.last_parsed_tag = ' Last parsed element: <' +
tag + strattrs + '>'

        def handle_endtag(self, tag):
                self.last_parsed_tag = ' Last parsed element: </' + tag +
'>'
                if (tag == "title"):
                        self.in_title = False
                elif (tag == "style"):
                        self.in_style = False

        def handle_data(self, data):
                if data.isspace():
                        pass
                elif self.in_title:
                        self.title = self.title + data
                elif self.in_style:
                        pass
                else:
                        self.extracted_text = self.extracted_text + " " +
data

        def get_text(self):
                result = self.extracted_text
                self.extracted_text = ""
                return result

        def get_title(self):
                result = self.title
                self.title = ""
                return result



On Wed, 22 Oct 2003, Jimmy verma wrote:

> Hello,
>
> I am getting caught in a problem for which i need some suggestions.
>
> I have an xml file like
>
> <XYZ Version="0">
>     <header>
>        <A = "1"/>
>        <B = "2"/>
>        <C = "0"/>
>        <D = "0"/>
>        <E = "0"/>
>     </header>
>
>     <dir>
>        <table0>
>           <P = "0"/>
>           <Q = "1"/>
>           <R = "2"/>
>           <S = "3"/>
>        </table0>
>        <table1>
>           <P = "4"/>
>           <Q= "5"/>
>           <R = "6"/>
>           <S = "7"/>
>        </table1>
>      <\dir>
>
> <\XYZ>
>
> I want to make two tables out of this: one is 'header' and other is 'dir'.
>
> Tables can be in the form of list:
>
>
> like
> header = [1,2,0,0,0]
>
> dir = [ [0,1,2,3], [4,5,6,7] ]
>
>
> I just want the values in the tables not the tags. Is there some pythonic
> way of doing it.
>
>
> Thanks in advance.
>
> Regards,
>
> J+
>
> _________________________________________________________________
> Special offer from American Express.Don't miss out.
> http://server1.msn.co.in/features/amex/index.asp  Apply now!
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>


From alan.gauld at blueyonder.co.uk  Wed Oct 22 15:03:11 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Wed Oct 22 15:02:20 2003
Subject: [Tutor] Re: Python Class functionality idiosyncrasy..
References: <200310221550.58631.dhanvik@gmx.net>	<200310221636.18552.dhanvik@gmx.net>	<20031022114010.GD1331@rogue.amk.ca><200310221721.20113.dhanvik@gmx.net>
	<bn5s2a$9hg$1@sea.gmane.org>
Message-ID: <012d01c398cf$237617e0$6401a8c0@xp>

> That's what docstrings are for :). 
> Providing dummy methods which are just meant 
> to be implemented by subclasses is extremely common practice 
> indeed; 

Yes, but the OP was asking about calling methods that haven't 
even been defined as dummy methods. Thats much less common, 
especially in statically compiled languages. However in Lisp/CLOS 
for example its a very common technique indeed. And in Lisp/Flavors
it was almost the normal mode of operation!

Alan G.

From tpc at csua.berkeley.edu  Wed Oct 22 15:12:51 2003
From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu)
Date: Wed Oct 22 15:12:55 2003
Subject: [Tutor] invalid literal for float 
Message-ID: <20031022115902.O49312-100000@localhost.name>


hello everyone, I am coming to you as a last resort because I am stuck on
a strange problem.  I am trying to index and search mp3s in my Apache
document root:

<code>
#!/usr/bin/env python
"""Created to solve bug that outputs invalid literal for float, int, long.
Simplifies main search script and assumes query will always be one word
long
"""
import MySQLdb

DB = 'test'

def getMP3SearchResults(terms):
        conn = MySQLdb.Connection(db=DB)
        cursor = conn.cursor()
        createTemporaryTable(cursor)
        identifyMatchingURLs(terms, cursor)
        results = getMatchingURLs(cursor)
        cursor.close()
        conn.close()
        return results

def createTemporaryTable(cursor):
        try:
                sql = """CREATE TEMPORARY TABLE URLs_WITH_MATCHES (
                      url_id INT NOT NULL,
                      ) TYPE = InnoDB;"""
                cursor.execute(sql)
        except:
                print "Error in creating URLs_WITH_MATCHES table"

def identifyMatchingURLs(terms, cursor):
        sql = """INSERT INTO URLs_WITH_MATCHES
              SELECT DISTINCT WORDS_X_URL.url_id
              FROM WORDS_X_URL
              INNER JOIN WORDS ON WORDS_X_URL.word_id = WORDS.id
              WHERE WORDS.word = '% s' """ % terms
        cursor.execute(sql)

def getMatchingURLs(cursor):
        sql = """SELECT URLs.url, URLs.title FROM URLs_WITH_MATCHES, URLs
              WHERE URLs_WITH_MATCHES.url_id = URLs.id
              GROUP BY URLs_WITH_MATCHES.url_id"""
        cursor.execute(sql)
        results = cursor.fetchall()
        return results

def search(terms):
        results = getMP3SearchResults(terms)
        return results

</code>

My program works just fine when run from the command line or in IDLE, but
when mod_python runs my script to retrieve the URL and title (i.e., the
filename minus the .mp3 extension) of mp3s whose filenames contain the
words I type into a web form, I get:

<paste>
Mod_python error: "PythonHandler mod_python.publisher"

Traceback (most recent call last):

  File "/usr/lib/python2.2/site-packages/mod_python/apache.py", line 335,
in HandlerDispatch
    result = object(req)

  File "/usr/lib/python2.2/site-packages/mod_python/publisher.py", line
194, in handler
    result = apply(object, (), args)

  File "/var/www/html/python/temp-invalidtest.py", line 48, in search

  File "/var/www/html/python/temp-invalidtest.py", line 17, in
getMP3SearchResults
    conn.close()

  File "/var/www/html/python/temp-invalidtest.py", line 43, in
getMatchingURLs
    return results

  File "/usr/lib/python2.2/site-packages/MySQLdb/cursors.py", line 95, in
execute
    return self._execute(query, args)

  File "/usr/lib/python2.2/site-packages/MySQLdb/cursors.py", line 114, in
_execute
    self.errorhandler(self, exc, value)

  File "/usr/lib/python2.2/site-packages/MySQLdb/connections.py", line 33,
in defaulterrorhandler
    raise errorclass, errorvalue

ValueError: invalid literal for float(): <insert any mp3 title here>
</paste>

The error messages vary, sometimes I see "invalid literal for int" or
"invalid literal for long" though lately I have just been getting "invalid
literal for float".  The error seems to come and go, where sometimes I get
the results I want.  Initially I thought it was a mod_python problem so I
asked the mod_python list but no one has a clue.  They suggest it may be a
MySQL or MySQLdb problem.  I don't believe so because MySQLdb works just
fine when run from the command line and in IDLE, and the MySQL statements
work just fine in MySQL shell.  I searched MySQLdb support and apparently
one other guy had this problem back in May, and he got further than me in
trying to debug this, but no one has any ideas for him either:

<paste>
By: mcjason222 ( Jason McDonald )
Invalid literal for float()
2003-05-18 22:57
I'm having trouble with MySQL-python being unable to handle string rows.
Whenever a command attempts to execute and returns a string value in a
column, it throws a ValueError exception: "invalid literal for float()"
(ie, it looks like it's trying to turn everything into a float).

import MySQLdb
conn = MySQLdb.connect(db="database", user="user")
c = conn.cursor()
c.execute("SELECT * FROM table")

Traceback (most recent call last):
File "test.py", line 9, in ?
c.execute("SELECT * FROM table")
File "/usr/local/lib/python2.2/site-packages/MySQLdb/cursors.py", line 95,
in execute
return self._execute(query, args)
File "/usr/local/lib/python2.2/site-packages/MySQLdb/cursors.py", line
114, in _execute
self.errorhandler(self, exc, value)
File "/usr/local/lib/python2.2/site-packages/MySQLdb/connections.py", line
33, in defaulterrorhandler
raise errorclass, errorvalue
ValueError: invalid literal for float(): A String

Using the debugger, the actual source of the exception is in _fetch_row(),
line 201, in cursors.py: return self._result.fetch_row(size,
self._fetch_type) is throwing it. Size and self._fetch_type are both 0
when it's called.

I'm using Python 2.2.2, MySQL 4.0.12, and MySQL-python 0.9.2

Any ideas?
</paste>

Do I need to change something in cursors.py ?  I am running:

Python 2.2.3
MySQL 4.0.14
MySQL-python 0.9.2
mod_python-3.0.1-3


From abli at freemail.hu  Wed Oct 22 15:31:01 2003
From: abli at freemail.hu (Abel Daniel)
Date: Wed Oct 22 15:31:21 2003
Subject: [Tutor] Re: Question about tkFileDialog
In-Reply-To: <102220031449.3797.4bbd@att.net> (m. evanetich's message of
	"Wed, 22 Oct 2003 14:49:38 +0000")
References: <102220031449.3797.4bbd@att.net>
Message-ID: <E1ACOhD-0000l5-00@hooloovoo>


[...Tkinter root window appearing when using tkFileDialog.askdirectory()...]

> I get the desired result, but I also get a small application named
> tk on my desktop and with a taskbar button that I cannot close as a
> side effect.  It is disconcerting and I have not found a way to
> banish it.  Can anyone point me to the relevant documentation or
> provide advice?

Well, I can show a workaround:

import Tkinter
import tkFileDialog

Tkinter.Tk().withdraw()
projectFolder = tkFileDialog.askdirectory()

... rest of program ...

The problem is that tkFileDialog creates not only the window you need,
but also a 'root window'. I guess it's because tkFileDialog creates a
new window, (so that it works even if you have other Tkinter windows
around), but Tkinter insits on creating the root window even if no
widgets are placed in it. For example 

import Tkinter
Tkinter.Toplevel()

gives _two_ windows, one is the 'root window' (which isn't special in
any way except thats the default window to place widgets in) and the
other is the Toplevel window we actually wanted.

I'm pretty suprised tkFileDialog has a bug like this. Anyway, in the
workaround, the line

Tkinter.Tk().withdraw()

explicitly creates this window, and immediatelly hides it.

-- 
Abel Daniel




From contrasutra at myrealbox.com  Wed Oct 22 16:41:18 2003
From: contrasutra at myrealbox.com (Ben Mazer)
Date: Wed Oct 22 16:41:28 2003
Subject: [Tutor] Timing a loop
In-Reply-To: <20031022112755.GC1331@rogue.amk.ca>
References: <3F95F495.4050102@myrealbox.com>
	<20031022112755.GC1331@rogue.amk.ca>
Message-ID: <3F96EB6E.8080306@myrealbox.com>

amk@amk.ca wrote:
> You want time.time(), which returns "wall clock" time.  Your results will
> therefore vary depending on your system's load; if cron runs in the middle
> of your timing interval, you'll measure a longer time, so usually people
> make several runs, discard outliers, and average them.

> If you're using a big loop such as 'for i in range(100000)', you don't want
> to measure the time to create the list of 100000 integer objects, so you
> should write something like:
> 
> L = range(100000)
> s = time.time()
> for i in L:
>     ....
> e = time.time()
> print 'Total time:', e-s, 'sec'.

Thanks, that worked great. I can't believe I missed time.time().

:-D
-- 
/"\ Ben Mazer <contrasutra@myrealbox.com>
\ /
  X  ASCII RIBBON CAMPAIGN AGAINST HTML MAIL
/ \


From druidmatt at yahoo.com  Wed Oct 22 17:11:19 2003
From: druidmatt at yahoo.com (Matt Hehman)
Date: Wed Oct 22 17:11:24 2003
Subject: [Tutor] Request for code critique
Message-ID: <20031022211119.22192.qmail@web10302.mail.yahoo.com>

Sorry if this shows up twice, it got bounced once.

Okay, lots of good feedback to digest.  Lloyd Kvam
sent me a complete revised program.  The highlights
were as follows:

#retrieve list of known primes
def main_shelve():
	try:
		d=shelve.open('primesfile')
		try:
			primes=d['primesfile']
		except KeyError:
			primes = [2,3,5]
			d['primesfile'] = primes
		main(primes)
	finally:
		d['primesfile'] = primes
		d.close()

#defines function for finding common factors
def Euclid(a,b):
<snip>

def main(primes):
<snip a neatened up version of the rest of my program>

if __name__ = '__main__':
        main_shelve()

The use of "try:" and "finally:" is new to me (docs?) 
The last two lines are a total mystery, as is the fact
that the program actually runs (and quite nicely) when
all I can make out is that functions have been
defined.  Why does it execute?



__________________________________
Do you Yahoo!?
The New Yahoo! Shopping - with improved product search
http://shopping.yahoo.com

From alan.gauld at blueyonder.co.uk  Wed Oct 22 17:55:32 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Wed Oct 22 17:54:43 2003
Subject: [Tutor] Re: Request for code critique
References: <20031022144746.48588.qmail@web10309.mail.yahoo.com>
	<bn6gmj$v4n$1@sea.gmane.org>
Message-ID: <015901c398e7$377b4a40$6401a8c0@xp>

> >         while primes[n]<=limit and len(candidates)>0:
> >             limit=int(candidates[0]**0.5)
> >             if candidates[0]%primes[n]==0:
> >                 del candidates[0]
> >                 n=0
> >             n=n+1

> well. Also I think that your while-solution is not as pythonic as it
could be
> (making it harder to follow for me). It's more common to use a break
statement
> than to define a loop variable outside the while-loop:

While that's a frequently seen Python thing I'm not sure its
necessarily a good thing. Break is one of those features
introduced into C (and whence into many other languages)
which breaks the rules of structured programming and by
so doing makes code more difficult to read reliably.
Break is properly intended to be used to break out of
infinite loops, however because Python cannot support
the common C idiom of:

while value = getValue():
    # do something with value

Nor does it have a do/while loop (Or a repeat/until)

repeat:
     # do something
     until <some condition>

or

do:
    # something
    while <some condition>


so that it has become common practice to do:

while 1:
    value = getValue()
    if not value:
        break
    # do something with value

This seems to have evolved to the point where break is now
seen as being a normal while style. In fact the above is
just using a trick (introducing an infinite loop plus break)
to get around a perceived weakness of Python. If value can
legitimately be set up before entering the loop. This has
the plus point of making the while statement much more
natural - since both the terminating conditions are
combined in the loop test, (as Dijkstra & Wirth intended! :-)
and the minus point of requiring one extra line of code and
the attendant double maintenance issue.

> for candidate in candidates:

But I agree the for loop seems nicer overall.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


From pythontutor at venix.com  Wed Oct 22 17:58:04 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Wed Oct 22 17:58:07 2003
Subject: [Tutor] Request for code critique
In-Reply-To: <20031022211119.22192.qmail@web10302.mail.yahoo.com>
References: <20031022211119.22192.qmail@web10302.mail.yahoo.com>
Message-ID: <3F96FD6C.7020807@venix.com>

http://www.python.org/doc/current/ref/try.html#l2h-597
7.4 The try statement

I tried running the original code with no existing shelve file.  The
program failed and left behind an empty file which was invalid for
the next run.  The python garbage collection along with the well coded
modules will often do the right thing when your program fails.  However,
it's a good idea to use a try/finally to manage resources to ensure proper
shutdown even when the program fails.

Once the original script got turned into functions, it was necessary to
call the main function, in this case: main_shelve.  that could have been
done by simply adding this line at the left margin:

main_shelve()

However, this line would be executed if the module was imported.  The test
for __name__ == "__main__" allows us to distinguish between an import and a
direct execution.

http://www.python.org/doc/current/ref/naming.html#l2h-319
4.1 Naming and binding

Now you can import this script and call the main function with
a list of primes and bypass shelve.  Even better, you could break main
into useful functions (such as get_factors) that might be useful in
other contexts.

Someone else already suggested turning this into a class.  The prompt for
a number would go outside the class, but the use of shelve to cache primes
is a natural situation for using a class.  The class allows you to hide
the try/finally logic and the prime caching inside a simple interface where
a calling function would learn the factors or primality of a number.


Matt Hehman wrote:

> Sorry if this shows up twice, it got bounced once.
> 
> Okay, lots of good feedback to digest.  Lloyd Kvam
> sent me a complete revised program.  The highlights
> were as follows:
> 
> #retrieve list of known primes
> def main_shelve():
> 	try:
> 		d=shelve.open('primesfile')
> 		try:
> 			primes=d['primesfile']
> 		except KeyError:
> 			primes = [2,3,5]
> 			d['primesfile'] = primes
> 		main(primes)
> 	finally:
> 		d['primesfile'] = primes
> 		d.close()
> 
> #defines function for finding common factors
> def Euclid(a,b):
> <snip>
> 
> def main(primes):
> <snip a neatened up version of the rest of my program>
> 
> if __name__ = '__main__':
>         main_shelve()
> 
> The use of "try:" and "finally:" is new to me (docs?) 
> The last two lines are a total mystery, as is the fact
> that the program actually runs (and quite nicely) when
> all I can make out is that functions have been
> defined.  Why does it execute?
> 
> 
> 
> __________________________________
> Do you Yahoo!?
> The New Yahoo! Shopping - with improved product search
> http://shopping.yahoo.com
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582


From dyoo at hkn.eecs.berkeley.edu  Wed Oct 22 18:58:25 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Oct 22 18:58:32 2003
Subject: [Tutor] Re: Request for code critique  ['break' vs control flag]
In-Reply-To: <015901c398e7$377b4a40$6401a8c0@xp>
Message-ID: <Pine.LNX.4.44.0310221546380.24279-100000@hkn.eecs.berkeley.edu>



On Wed, 22 Oct 2003, Alan Gauld wrote:

> > >         while primes[n]<=limit and len(candidates)>0:
> > >             limit=int(candidates[0]**0.5)
> > >             if candidates[0]%primes[n]==0:
> > >                 del candidates[0]
> > >                 n=0
> > >             n=n+1
>
> > well. Also I think that your while-solution is not as pythonic as it
> > could be (making it harder to follow for me). It's more common to use
> > a break statement than to define a loop variable outside the
> > while-loop:
>
> While that's a frequently seen Python thing I'm not sure its necessarily
> a good thing. Break is one of those features introduced into C (and
> whence into many other languages) which breaks the rules of structured
> programming and by so doing makes code more difficult to read reliably.

Hi Alan,

On the other hand, the Refactoring folks talk about --- and encourage! ---
the use of 'break' with their section on "Remove Control Flag (245)".

But I've also met a lot of respected programmers who insist on the "one
entry point, and one exit point" viewpoint. 'break' drives them crazy.

So, like many style guidelines, it's a controversial issue. *grin*


From arkamir at softhome.net  Wed Oct 22 19:26:12 2003
From: arkamir at softhome.net (Conrad Koziol)
Date: Wed Oct 22 19:26:36 2003
Subject: [Tutor] Sort and compare
Message-ID: <1066865172.5029.2.camel@quercus>

def compare(a,b):
         if a[1]>b[1]: return 0
         else: return -1

x = [('hello', 2), ('goodbye', 3), ('python', 1)]

x.sort(compare(x))

can you explain what happens to me step by step. That'a were im lost.

Does x sort [-1, 0, 1, -1]????



From sigurd at 12move.de  Wed Oct 22 20:46:59 2003
From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Wed Oct 22 20:49:03 2003
Subject: [Tutor] Sort and compare
In-Reply-To: <1066865172.5029.2.camel@quercus> (Conrad Koziol's message of
	"Wed, 22 Oct 2003 16:26:12 -0700")
References: <1066865172.5029.2.camel@quercus>
Message-ID: <m3d6cols7w.fsf@hamster.pflaesterer.de>

On 23 Oct 2003, Conrad Koziol <- arkamir@softhome.net wrote:

> def compare(a,b):
>          if a[1]>b[1]: return 0
>          else: return -1

This function has two bugs.  First it returns the wrong value for a[1]>
b[1]; it must return 1.  Second there are three cases: a > b, a == b, a
< b.

Python has a builtin `cmp' which you could use here.

        def mycmp(a, b):
              return cmp(a[1], b[1])
  
(the example is directly from the Python libraray reference).

> x = [('hello', 2), ('goodbye', 3), ('python', 1)]

> x.sort(compare(x))

> can you explain what happens to me step by step. That'a were im lost.

> Does x sort [-1, 0, 1, -1]????

Well with your function maybe (but where does the `1' come from?), but
if you used the right function: no.

Let's see (we best ask Python):

In [6]: def comp(a ,b):
   ...: m   print a, b, cmp( a[1], b[1])
   ...: m   return cmp(a[1], b[1])
   ...: m

In [7]: x = [('hello', 2), ('goodbye', 3), ('python', 1)]

In [8]: x.sort(comp)
('goodbye', 3) ('hello', 2) 1
('python', 1) ('goodbye', 3) -1
('python', 1) ('goodbye', 3) -1
('python', 1) ('hello', 2) -1

In [9]: x
Out[9]: [('python', 1), ('hello', 2), ('goodbye', 3)]


(I used IPython here; a great interactive environment).

So you see how the sort function compared the values till it found the
right ascending sequence.

For the sort function  a is greater than b if the comparing functions
returns -1; a is equal b if the function returns 0 and a is greater b if
the function returns +1.

*But* when you have bigger lists there are better possibilities than
using a custom compare function.  That's also written in the libraray
reference.  I quote a part of it here:
,----
|      A more time-efficient approach for reasonably-sized data
|      structures can often be used:
| 
|           tmplist = [(x[1], x) for x in mylist]
|           tmplist.sort()
|           mylist = [x for (key, x) in tmplist]
`----

You will need more space but most of the time that approach (decorate,
sort, undecorate) is faster.


   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


From dyoo at hkn.eecs.berkeley.edu  Wed Oct 22 20:54:10 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Oct 22 20:54:52 2003
Subject: [Tutor] Sort and compare  [why compare when sorting?]
In-Reply-To: <1066865172.5029.2.camel@quercus>
Message-ID: <Pine.LNX.4.44.0310221720010.30190-100000@hkn.eecs.berkeley.edu>



On Wed, 22 Oct 2003, Conrad Koziol wrote:

> def compare(a,b):
>          if a[1]>b[1]: return 0
>          else: return -1
>
> x = [('hello', 2), ('goodbye', 3), ('python', 1)]
>
> x.sort(compare(x))


Hi Conrad,

This needs to be corrected to:

    x.sort(compare)


> can you explain what happens to me step by step. That'a were im lost.
>
> Does x sort [-1, 0, 1, -1]????


I think you're getting confused about how comparsion sorting works.  Do
you mind if we make the problem slightly simpler?  It may help make the
concept easier to understand, but this post is going to be a little long.
*grin*



Here's the simplification: let's say that we're trying to write a program
that sorts a list of three elements [a, b, c].  We're going to force this
length restriction just for the sake of understanding what's happening.
So say we have something like:

###
>>> numbers = [3, 1, 4]
###

Pretend that we're not allowed to use sort() directly, but we'd like to
rearrange the numbers here so that they're in sorted order.  We'd like a
function that takes something like [3, 1, 4] and transforms it to
[1, 3, 4].


Here's one way to do it:

###
>>> def sortThree(l):
...     l[0], l[1], l[2] = l[1], l[0], l[2]
...
>>> sortThree(numbers)
>>> numbers
[1, 3, 4]
###

... but of course, this is cheating!  *grin* Particular because if we send
numbers through it one more time, it just scrambles it all over again.

###
>>> numbers
[1, 3, 4]
>>> sortThree(numbers)
>>> numbers
[3, 1, 4]
###

So it's not a real sorter.  We want a more generalized sortThree() that
really works a list of three things.


What we can do is play something of a shell game: we can swap elements if
they're in the wrong order.  We can check the first two, check the second
two, and swing elements around till the list is sorted.  Here's one way to
do it:

###
>>> def sortThree(l):
...     if l[0] > l[1]:
...         l[0], l[1] = l[1], l[0]
...     if l[1] > l[2]:
...         l[1], l[2] = l[2], l[1]
...     if l[0] > l[1]:
...         l[0], l[1] = l[1], l[0]
...
>>> numbers
[3, 1, 4]
>>> sortThree(numbers)
>>> numbers
[1, 3, 4]
>>> sortThree(numbers)
>>> numbers
[1, 3, 4]
###

Yeah, the numbers stay sorted, even if we call sortThree() twice on the
list.  That's a good thing.  *grin*


And it works on lists of three words too:

###
>>> words = ["this", "is", "a"]
>>> sortThree(words)
>>> words
['a', 'is', 'this']
###

Do you understand how sortThree() is working at the moment?  The key is to
see that it's sorting by doing comparisons '<' and swaps.  Let's look at
it again:

###
def sortThree(l):
     if l[0] > l[1]:
         l[0], l[1] = l[1], l[0]
     if l[1] > l[2]:
         l[1], l[2] = l[2], l[1]
     if l[0] > l[1]:
         l[0], l[1] = l[1], l[0]
###


If we wanted to use this to solve your original problem of sorting:

    x = [('hello', 2), ('goodbye', 3), ('python', 1)]

then it sort of works:

###
>>> x = [('hello', 2), ('goodbye', 3), ('python', 1)]
>>> sortThree(x)
>>> x
[('goodbye', 3), ('hello', 2), ('python', 1)]
###

But the problem is that it's sorting by comparing tuples, and
    'goodbye' < 'hello' < python.

You want it so that it compares against the numbers within each tuple.
We want to change sortThree() so that, instead of doing:

     if l[0] > l[1] ...
     if l[1] > l[2] ...
     if l[0] > l[1] ...

it does something more like this:

     if l[0][1] > l[1][1] ...
     if l[1][1] > l[2][1] ...
     if l[0][1] > l[1][1] ...

And that's where comparison functions come in: we can rewrite sortThree()
and "teach" it how to do '>' the way we want it to.

###
def sortThree(l, mycmp):
     if mycmp(l[0], l[1]) > 0:
         l[0], l[1] = l[1], l[0]
     if mycmp(l[1], l[2]) > 0:
         l[1], l[2] = l[2], l[1]
     if mycmp(l[0], l[1]) > 0:
         l[0], l[1] = l[1], l[0]
###


Python comes with its own built-in comparison function called cmp(), so we
can use it:

###
>>> numbers = [3, 1, 4]
>>> sortThree(numbers, cmp)
>>> numbers
[1, 3, 4]
>>> words = ["this", "is", "a"]
>>> sortThree(words, cmp)
>>> words
['a', 'is', 'this']
>>> x = [('hello', 2), ('goodbye', 3), ('python', 1)]
>>> sortThree(x, cmp)
>>> x
[('goodbye', 3), ('hello', 2), ('python', 1)]
###


And we can now feed sortThree a new comparison function that looks at the
second component of each tuple:

###
>>> def compare(a, b):
...     if a[1] > b[1]: return 1
...     if a[1] == b[1]: return 0
...     if a[1] < b[1]: return -1
...
>>> sortThree(x, compare)
>>> x
[('python', 1), ('hello', 2), ('goodbye', 3)]
###


If you understand all of this, then Python's built-in sort() should not be
so mysterious anymore.  *grin*

But I went through this really fast, so please ask questions on the parts
of things that don't make sense yet.  One of us on Tutor will be happy to
talk about it more.


Good luck!


From fredm at smartypantsco.com  Wed Oct 22 21:15:19 2003
From: fredm at smartypantsco.com (Alfred Milgrom)
Date: Wed Oct 22 21:14:54 2003
Subject: [Tutor] Sort and compare
In-Reply-To: <1066865172.5029.2.camel@quercus>
Message-ID: <5.1.0.14.0.20031023105547.0342c080@192.168.1.1>

Hi Conrad:

Let me try to explain it.
If you have a list  and try to sort it, then obviously you have to use some 
type of sorting criteria.

x = [('hello', 2), ('goodbye', 3), ('python', 1)]
x.sort()

what you are saying is "sort the list x"  but you should note that this 
also implies "using the built-in function cmp()".

What the function cmp() does is check any two items and compare them. If 
the first element given to cmp() is greater than the second it returns 0, 
otherwise it returns -1.
The function cmp() can compare most types. In the case of a tuple if 
compares the first element of each item.

Think of of the sorting process as basically going through each pair of 
elements in the list and comparing them. If they are in the wrong order it 
swaps them, and if they are OK it goes on to the next pair. It keeps on 
doing this until there are no more swaps needed.

By defining a new comparison function, then we can use the statement

x.sort(compare)

This can be read as "sort the list x using the function compare() to 
compare adjacent items in the list".
You can define functions to do compares any way that you need for your 
particular application.

In this case, compare(a,b) compares a[1] and b[1]. In other words, when 
sort does its work, it uses the results from compare() which is based on 
the results of comparing each item[1].

Note that the syntax is
         x.sort(compare)
and not
         x.sort(compare(x))

As I mentioned in my original email, the compare function I wrote is not 
very good as it does not do error checking, etc.
A better and simpler implementation (as was pointed out by Danny on this 
list) is:

def compare(a,b):
         return cmp(a[1], b[1])

This uses the built-in function cmp to return the proper arguments for us.

Hope this helps,
Fred Milgrom

At 04:26 PM 22/10/03 -0700, Conrad Koziol wrote:
>def compare(a,b):
>          if a[1]>b[1]: return 0
>          else: return -1
>
>x = [('hello', 2), ('goodbye', 3), ('python', 1)]
>
>x.sort(compare(x))
>
>can you explain what happens to me step by step. That'a were im lost.
>
>Does x sort [-1, 0, 1, -1]????



From thomi at imail.net.nz  Thu Oct 23 00:31:47 2003
From: thomi at imail.net.nz (Thomi Richards)
Date: Thu Oct 23 00:42:32 2003
Subject: [Tutor] adding type methods?
Message-ID: <200310231731.47488.thomi@imail.net.nz>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1


Hi guys,


I'm just wondering whether it's possible to add methods to a python built in 
type. for example:

>>> s = "this is a string"
>>> dir(s)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', 
'__ge__', '__getattribute__', '__getitem__', '__getnewargs__', 
'__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', 
'__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', 
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', 
'__str__', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 
'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 
'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 
'replace', 'rfind', 'rindex', 'rjust', 'rstrip', 'split', 'splitlines', 
'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> s.upper()
'THIS IS A STRING'


Is there an easy way to add more functions to these built in types, without 
having to compile python from source?

This is simply a random thought, without any practical application intended 
for it (so feel free to ignore)...

any ideas?

- -- 
Thomi Richards,
http://once.sourceforge.net/


-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.3 (GNU/Linux)

iD8DBQE/l1mz2tSuYV7JfuERAqXeAJ9acB/Ktbu52jW+B1CUFUfQpqyt+gCfcqfT
bQPzQ4hWtEs1fblgUftFsFU=
=wKc1
-----END PGP SIGNATURE-----


From alan.gauld at blueyonder.co.uk  Thu Oct 23 01:00:22 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Thu Oct 23 01:01:21 2003
Subject: [Tutor] Re: Request for code critique  ['break' vs control flag]
References: <Pine.LNX.4.44.0310221546380.24279-100000@hkn.eecs.berkeley.edu>
Message-ID: <016001c39922$90589c90$6401a8c0@xp>

> > whence into many other languages) which breaks the rules of
structured
> > programming and by so doing makes code more difficult to read
reliably.

> But I've also met a lot of respected programmers who insist on the
"one
> entry point, and one exit point" viewpoint. 'break' drives them
crazy.
>
> So, like many style guidelines, it's a controversial issue. *grin*

I think the issue is that this is NOT a style thing. It's
one of the basic tenets of structured programming and based
on actual hard data. Having multiple exit points makes code
harder to comprehend and hence more prone to error.

Sometimes people forget the reasons behind some of these
early discoveries in Computer Science. In fact I just finished
reviewing a book by Robert Glass: "Facts and Fallacies of
Software Engineering" which is based entirely on the concept
that the faddy world of SE regularly forgets (and subsequently
rediscovers) some of the basic truths of our trade...

It falls into the same category as indentation style for
begin/end or {} block markers. People treat it as a personal
choice but hard evidence exists which shows that some styles
are significantly more comprehensible than others.

Alan G.


From abli at freemail.hu  Thu Oct 23 03:05:13 2003
From: abli at freemail.hu (Abel Daniel)
Date: Thu Oct 23 03:05:54 2003
Subject: [Tutor] Re: adding type methods?
In-Reply-To: <200310231731.47488.thomi@imail.net.nz> (Thomi Richards's
	message of "Thu, 23 Oct 2003 17:31:47 +1300")
References: <200310231731.47488.thomi@imail.net.nz>
Message-ID: <E1ACZX3-0000Dj-00@hooloovoo>


Thomi Richards writes:

> I'm just wondering whether it's possible to add methods to a python built in 
> type. for example:

> Is there an easy way to add more functions to these built in types, without 
> having to compile python from source?
>
> This is simply a random thought, without any practical application intended 
> for it (so feel free to ignore)...

Well, in newer pythons (it think after 2.3, with the introduction of
new-style classes) you can subclass any built-in type (in older ones
this wasn't possible, you had to use UserDict, UserList & UserString
modules).

Example:

Python 2.3.1 (#2, Sep 24 2003, 11:39:14) 
[GCC 3.3.2 20030908 (Debian prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class newstring(str):
...  def moo(self):
...   print 'moo'
... 
>>> s=newstring('foobar')
>>> s
'foobar'
>>> s.moo()
moo
>>> type(s)
<class '__main__.newstring'>
>>> dir(s)
['__add__', '__class__', '__contains__', '__delattr__', '__dict__',
'__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__',
'__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__',
'__le__', '__len__', '__lt__', '__mod__', '__module__', '__mul__',
'__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__rmod__', '__rmul__', '__setattr__', '__str__', 'capitalize',
'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs',
'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower',
'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip',
'moo', 'replace', 'rfind', 'rindex', 'rjust', 'rstrip', 'split',
'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate',
'upper', 'zfill']
>>> 

Now, this isn't what you asked, because the above example doesn't add
methods to and existing type, it creates a new type. (See the result
of type(s).) I think adding to a built-in type isn't possible:

Trying to add to our class:
>>> def foo(self):
...  print 'foo'
... 
>>> newstring.foo = foo
>>> s.foo()
foo

Trying to add to built-in:
>>> str.foo = foo
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: can't set attributes of built-in/extension type 'str'

So I guess you can do that only by writing C code. However, the
difference shouldn't matter. Typechecking isn't good python style. You
should be checking for interfaces not for types. So our newstring
class should be usable everywhere. (It won't be if somebody checks for
types with isinstance() or such, but such code could be considered
broken for not being pythonic.)

-- 
Abel Daniel

From Anish.Mehta at enst-bretagne.fr  Thu Oct 23 08:59:03 2003
From: Anish.Mehta at enst-bretagne.fr (Mehta, Anish)
Date: Thu Oct 23 08:30:46 2003
Subject: [Tutor] handling string!!
Message-ID: <3F97D097.5010800@antares.enst-bretagne.fr>

Hello,

Is there a pythonic way to handle this:

str = 'ABC   value="123" value="345"'

i have a string and i want to extract the values between the quotes(""). 
Like 123, 345

Do we have some builtin function to handle this.

Thanks in advance.

With best regards,

Anish






From project5 at redrival.net  Thu Oct 23 08:29:24 2003
From: project5 at redrival.net (Andrei)
Date: Thu Oct 23 08:31:39 2003
Subject: [Tutor] Re: Request for code critique
In-Reply-To: <015901c398e7$377b4a40$6401a8c0@xp>
References: <20031022144746.48588.qmail@web10309.mail.yahoo.com>	<bn6gmj$v4n$1@sea.gmane.org>
	<015901c398e7$377b4a40$6401a8c0@xp>
Message-ID: <bn8hn4$hgf$1@sea.gmane.org>

Alan Gauld wrote:

>>>        while primes[n]<=limit and len(candidates)>0:
>>>            limit=int(candidates[0]**0.5)
>>>            if candidates[0]%primes[n]==0:
>>>                del candidates[0]
>>>                n=0
>>>            n=n+1
> 
>>well. Also I think that your while-solution is not as pythonic as it
> could be
>>(making it harder to follow for me). It's more common to use a break
> statement
>>than to define a loop variable outside the while-loop:
 >
> 
> While that's a frequently seen Python thing I'm not sure its
> necessarily a good thing. Break is one of those features
> introduced into C (and whence into many other languages)
> which breaks the rules of structured programming and by
> so doing makes code more difficult to read reliably.

Although I agree that a repeat-until would be useful and I do kind of miss it 
(although I can't really imagine what syntax it would have in Python) and I too 
did that assignment outside the loop thing when I switched from Delphi because 
break seemed a bad choice, I now think that the benefit of not having that 
assignment outweigh the costs of having a break statement.

<snip>

> This seems to have evolved to the point where break is now
> seen as being a normal while style. In fact the above is
> just using a trick (introducing an infinite loop plus break)
> to get around a perceived weakness of Python. If value can
> legitimately be set up before entering the loop. This has
> the plus point of making the while statement much more
> natural - since both the terminating conditions are
> combined in the loop test, (as Dijkstra & Wirth intended! :-)
> and the minus point of requiring one extra line of code and
> the attendant double maintenance issue.

That double maintenance is my main concern actually. If loops are kept at a 
decent size, it's pretty easy to spot the exit points thanks to the marvels of 
syntax coloring :) - even though it may not be ideal.

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur 
yvfg, fb gurer'f ab arrq gb PP.



From python-tutor-list at tagancha.org  Thu Oct 23 11:50:21 2003
From: python-tutor-list at tagancha.org (Alex. M)
Date: Thu Oct 23 11:51:19 2003
Subject: [Tutor] Checking a windows share
Message-ID: <20031023155020.GA9146@purdue.edu>


 Hi,

Is there a nice way to check if a certain windows share is accessible
from across the network (linux client if that matters) instead of just
using the os.path.exists?

Thanks,

Alex.


From glingl at aon.at  Thu Oct 23 12:12:32 2003
From: glingl at aon.at (Gregor Lingl)
Date: Thu Oct 23 12:14:37 2003
Subject: [Tutor] Bit Strings  [a recursive approach]
In-Reply-To: <00cc01c39877$9fb8bb80$6401a8c0@xp>
References: <Pine.LNX.4.44.0310212304000.17656-100000@hkn.eecs.berkeley.edu>
	<00cc01c39877$9fb8bb80$6401a8c0@xp>
Message-ID: <3F97FDF0.1050503@aon.at>



Alan Gauld schrieb:

> ...
>
>>just write:
>>
>>###
>>def bitstrings(n):
>>...
>>
>And in fact you could even remove the if n== 2 line.
>It works just fine using the appendInFRont function!
>
>def bitstrings(n):
>     if n == 0: return []
>     if n == 1: return ["0", "1"]
>     else:
>         return (appendInFront("0", bitstrings(n-1))
>                 + appendInFront("1", bitstrings(n-1)))
>:-)
>
>Alan G.
>  
>
May I supply another flavourof the recursive approach, which even 
doesn't need
appendInFront (but incorporagtes it itself)? It's nevertheless very compact:

 >>> def bitstrings(n):
        if n==0: return ["0","1"]
        return [ digit+bitstring for digit in bitstrings(1)
                                 for bitstring in bitstrings(n-1)]

 >>> bitstrings(3)
['000', '001', '010', '011', '100', '101', '110', '111']

Regards, Gregor

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


From sigurd at 12move.de  Thu Oct 23 12:24:39 2003
From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Thu Oct 23 12:30:31 2003
Subject: [Tutor] handling string!!
In-Reply-To: <3F97D097.5010800@antares.enst-bretagne.fr> (Anish Mehta's
	message of "Thu, 23 Oct 2003 14:59:03 +0200")
References: <3F97D097.5010800@antares.enst-bretagne.fr>
Message-ID: <m3ismg54ic.fsf@hamster.pflaesterer.de>

On 23 Oct 2003, Mehta, Anish <- Anish.Mehta@enst-bretagne.fr wrote:

> str = 'ABC   value="123" value="345"'

`str' is a builtin.  Don't use it as variable.

> i have a string and i want to extract the values between the
> quotes(""). Like 123, 345

> Do we have some builtin function to handle this.

Not exactly.  If youre string is always in the way you described it,
then there is an easy possibilty.

You could transform the string in a list with the `split()' function and
use `"' as delimiter.

In [7]: s = 'ABC   value="123" value="345"'

In [8]: s.split('"')
Out[8]: ['ABC   value=', '123', ' value=', '345', '']


Now the only problem is to grab the first, third ... value from the
list.

In [9]: sp = s.split('"')

In [10]: for i in range(1, len(sp), 2):
   ....:     print sp[i]
   ....:
123
345


That's a bit ugly and in Python 2.3 with the itertools module we have a
better alternative.

In [17]: from itertools import islice

In [18]: for i in islice(sp, 1, None, 2):
   ....:     print i
   ....:     
123
345



   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


From hasan at in2p3.fr  Thu Oct 23 12:35:38 2003
From: hasan at in2p3.fr (Adil Hasan)
Date: Thu Oct 23 12:36:15 2003
Subject: [Tutor] executing multiple binaries from a python script
Message-ID: <Pine.LNX.3.96.1031023183511.2076A-100000@ccali08.in2p3.fr>

Hello,
       Can someone help me? I am trying to write a little script that will
 execute binaries one after the other. Ideally, I'd like to be able to
 create the shell session in the constructor, execute some commands, and
 then close the session. On the unix command line what I do is:

 shell> commandA  (this creates my session)
 shell>     commandB
 shell>     commandC
 shell>     commandD
 shell> commandE (ends my session)

 I'd like to be able to do this within a python class. I thought I might
 be able to use popen2, but that doesn't work (I get broken pipe errors).
 I was thinking about fork() but I cannot understand how to put this into
 a class like structure (ideally I'd like to get some handle to the fork
 and then pass that to the methods to allow me to run the other commands).

 Does anyone have an idea how to do this?
 thanks, adil



From dyoo at hkn.eecs.berkeley.edu  Thu Oct 23 14:19:55 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Oct 23 14:23:43 2003
Subject: [Tutor] Bit Strings  [a recursive approach]
In-Reply-To: <3F97FDF0.1050503@aon.at>
Message-ID: <Pine.LNX.4.44.0310231112070.28886-100000@hkn.eecs.berkeley.edu>



> >And in fact you could even remove the if n== 2 line. It works just fine
> >using the appendInFRont function!
> >
> >def bitstrings(n):
> >     if n == 0: return []
> >     if n == 1: return ["0", "1"]
> >     else:
> >         return (appendInFront("0", bitstrings(n-1))
> >                 + appendInFront("1", bitstrings(n-1)))

> May I supply another flavourof the recursive approach, which even
> doesn't need appendInFront (but incorporagtes it itself)? It's
> nevertheless very compact:
>
>  >>> def bitstrings(n):
>         if n==0: return ["0","1"]
>         return [ digit+bitstring for digit in bitstrings(1)
>                                  for bitstring in bitstrings(n-1)]

Hi Gregor,

Correction: the basis here needs to be repaired for n == 1;  otherwise,
this won't terminate.  With a recursive approach, we have to especially
careful about the boundary cases of our problem.


One way to fix the bug might be:

###
def bitstrings(n):
    if n == 0: return []
    if n == 1: return ["0","1"]
    return [ digit+bitstring for digit in bitstrings(1)
                             for bitstring in bitstrings(n-1) ]
###


Good luck!


From bwinton at latte.ca  Thu Oct 23 15:16:33 2003
From: bwinton at latte.ca (Blake Winton)
Date: Thu Oct 23 15:16:44 2003
Subject: [Tutor] Bit Strings  [a recursive approach]
In-Reply-To: <Pine.LNX.4.44.0310231112070.28886-100000@hkn.eecs.berkeley.edu>
Message-ID: <046b01c3999a$2d274ef0$6401a8c0@phantomfiber.com>

> def bitstrings(n):
>     if n == 0: return []
>     if n == 1: return ["0","1"]
>     return [ digit+bitstring for digit in bitstrings(1)
>                              for bitstring in bitstrings(n-1) ]

Along those lines, I've always thought that n=0 should
really return [""].  Which could make the function into:
###
def bitstrings(n):
    if n == 0: return [""]
    return [ digit+bitstring for digit in ["0","1"]
                             for bitstring in bitstrings(n-1) ]
###
(I prefer to use the explicit list ["0","1"] for the digits
 to avoid yet another call to the bitstrings function, and
 to avoid having to define what bitstrings(1) should return.
 But that's probably just me.)

And of course, this opens up the whole can of worms of how we
should represent emptyness, and what the proper result of
bitstrings(0) should really be.  As a mathematician, I seem
to remember that there's one way to choose 0 numbers out of
a set, and so the array returned by bitstrings(0) should
really contain one element.  It also makes for a nice regularity
as demonstrated in the following code:

###
for x in xrange(5):
    print x, len( bitstrings(x) )
###
0 1
1 2
2 4
3 8
4 16
###

If we special-case n=0 to return [], then the size of the list
returned by bitstrings(n) is no longer 2**n.  Just a thought.

Later,
Blake.


From littledanehren at yahoo.com  Thu Oct 23 16:06:17 2003
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Thu Oct 23 16:06:24 2003
Subject: [Tutor] handling string!!
In-Reply-To: <m3ismg54ic.fsf@hamster.pflaesterer.de>
Message-ID: <20031023200617.60725.qmail@web41809.mail.yahoo.com>

> Not exactly.  If youre string is always in the way
> you described it,
> then there is an easy possibilty.
> 
> You could transform the string in a list with the
> `split()' function and
> use `"' as delimiter.
> 
> In [7]: s = 'ABC   value="123" value="345"'
> 
> In [8]: s.split('"')
> Out[8]: ['ABC   value=', '123', ' value=', '345',
> '']
> 
> 
> Now the only problem is to grab the first, third ...
> value from the
> list.
> 
> In [9]: sp = s.split('"')
> 
> In [10]: for i in range(1, len(sp), 2):
>    ....:     print sp[i]
>    ....:
> 123
> 345
> 
> 
> That's a bit ugly and in Python 2.3 with the
> itertools module we have a
> better alternative.
> 
> In [17]: from itertools import islice
> 
> In [18]: for i in islice(sp, 1, None, 2):
>    ....:     print i
>    ....:     
> 123
> 345
> 
> 
> 
>    Karl

I have a somewhat related question. I am trying to
write a program to parse the simple markup language
used at Wikipedia.org. For this specific question, the
markup is the same as in MoinMoin.

The first feature is bolding and italics. Since I'm
using XHTML, I'll use the <strong> and <em> tags
instead of <b> and <i>. Here are some examples of
correctly parsed text from this part of the markup
language:

'''bold''' -> <strong>bold</strong>
''italics'' -> <em>italics</em>
'''''bold and italics''''' -> <strong><em>bold and
italics</em></strong>
'''''b & i'' b''' -> <strong><em>b & i</em> b</strong>
'''''b & i''' i'' -> <em><strong>b & i</strong> i</em>

and so on. If the tags couldn't be mixed as they are
in the last example, the code would be relatively
simple:

>>> list2parse = initialstring.split("'''")
>>> state = True
>>> parsedlist = []
>>> for i in slice(list2parse, 1, None, 1):
...     if state:
...         parsedlist.append("<strong>" + i +
"</strong>")
...     else:
...         parsedlist.append(i)
...     state = not state

would parse the bold parts of the text. It would be
similar for the code processing italics and the
combination of bold and italics, doing the ones with
the most apostrophies first and the least apostrophies
last (ie. first bold and italics, then bold, then
italics). However, I don't see how I could do the same
with the forth and fifth examples. Could you help me
with that?
Daniel Ehrenberg

__________________________________
Do you Yahoo!?
The New Yahoo! Shopping - with improved product search
http://shopping.yahoo.com

From alan.gauld at blueyonder.co.uk  Thu Oct 23 16:38:22 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Thu Oct 23 16:45:58 2003
Subject: [Tutor] Re: adding type methods?
References: <200310231731.47488.thomi@imail.net.nz>
	<E1ACZX3-0000Dj-00@hooloovoo>
Message-ID: <018f01c399a5$9cc67050$6401a8c0@xp>

> Now, this isn't what you asked, because the above example doesn't
add
> methods to and existing type, it creates a new type. (See the result
> of type(s).) I think adding to a built-in type isn't possible:

Not possible and potentially dangerous since you are changing
the behaviour of a standard type and some obscure bit of code
may depend on the methods that are there being fixed (because
it iterates over them doing something with the result say?)

Or some other module also adds a new method using the same
name and then you get all sorts of unexpected behaviours
occurring! And the fun of trying to work out which added
method gets called where!

One of the advantages of OOP is that you can add new behaviour
without changing the old behaviour.

Alan G.


From dyoo at hkn.eecs.berkeley.edu  Thu Oct 23 16:49:51 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Oct 23 16:49:56 2003
Subject: [Tutor] Bit Strings  [a recursive approach]
In-Reply-To: <046b01c3999a$2d274ef0$6401a8c0@phantomfiber.com>
Message-ID: <Pine.LNX.4.44.0310231226210.1731-100000@hkn.eecs.berkeley.edu>



On Thu, 23 Oct 2003, Blake Winton wrote:

> > def bitstrings(n):
> >     if n == 0: return []
> >     if n == 1: return ["0","1"]
> >     return [ digit+bitstring for digit in bitstrings(1)
> >                              for bitstring in bitstrings(n-1) ]
>
> Along those lines, I've always thought that n=0 should
> really return [""].


> def bitstrings(n):
>     if n == 0: return [""]
>     return [ digit+bitstring for digit in ["0","1"]
>                              for bitstring in bitstrings(n-1) ]


Hi Blake,

You're absolutely right!  I didn't think about the empty case clearly
enough.  There is only one bit-string of length 0, and your fix accounts
for this.  Now the bitstrings() function is very beautiful.  *grin*


Thanks again for the correction!


From project5 at redrival.net  Thu Oct 23 16:53:54 2003
From: project5 at redrival.net (Andrei)
Date: Thu Oct 23 17:02:26 2003
Subject: [Tutor] Re: handling string!!
In-Reply-To: <20031023200617.60725.qmail@web41809.mail.yahoo.com>
References: <m3ismg54ic.fsf@hamster.pflaesterer.de>
	<20031023200617.60725.qmail@web41809.mail.yahoo.com>
Message-ID: <bn9f9b$qeg$1@sea.gmane.org>

Daniel Ehrenberg wrote:

<snip>
> I have a somewhat related question. I am trying to
> write a program to parse the simple markup language
> used at Wikipedia.org. For this specific question, the
> markup is the same as in MoinMoin.

Kirk Bailey (who's around here too) has an open source Wiki at 
tinylist.org, written in Python:

http://www.tinylist.org/cgi-bin/wikinehesaed2.py

It handles this kinda thing quite well, I just tested it at the bottom of 
http://www.tinylist.org/cgi-bin/wikinehesaed2.py/SandBox. Perhaps you 
should look at its code.

> '''bold''' -> <strong>bold</strong>
> ''italics'' -> <em>italics</em>
> '''''bold and italics''''' -> <strong><em>bold and
> italics</em></strong>
> '''''b & i'' b''' -> <strong><em>b & i</em> b</strong>
> '''''b & i''' i'' -> <em><strong>b & i</strong> i</em>

<snip>

> would parse the bold parts of the text. It would be
> similar for the code processing italics and the
> combination of bold and italics, doing the ones with
> the most apostrophies first and the least apostrophies
> last (ie. first bold and italics, then bold, then
> italics). However, I don't see how I could do the same
> with the forth and fifth examples. Could you help me
> with that?

You just have to keep track of what you have open and apply the first open, 
last to close principle (use a list to which you append tags when you open 
them and then delete them when you close them starting from the last). In 
your 5th example:

 > '''''b & i''' i'' -> <em><strong>b & i</strong> i</em>

your parser would e.g. first hit ''' (open <strong> and append it to the 
OpenTags list), then the '' (open <em> and append it to the OpenTags list). 
When it finds the closing ''', it tries to close the <strong>, but it 
notices in the OpenTags list that there are tags before it. It closes those 
first (in this case, the last tag in OpenTags is <em>, so it closes it 
first, but places it in a different list, say RestoreTags), then it closes 
the <strong> and reopens the ones in RestoreTags - obviously, these end up 
being on the OpenTags list again. The generated code is then:

<strong><em>b & i</em></strong><em> i</em>

Which is not perfect, but it's valid XHTML :). Making it really intelligent 
would be quite a bit harder, especially if you consider you might be 
nesting more tags.

I'm not sure this is the way Kirk's Wiki does it, but I know it would work 
because I use this same principle in my regular expression tool to 
highlight parentheses.

I'm wondering how you'd handle '''''' though (can be two bolds or three 
italics).

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V 
ernq gur yvfg, fb gurer'f ab arrq gb PP.



From glingl at aon.at  Thu Oct 23 17:13:12 2003
From: glingl at aon.at (Gregor Lingl)
Date: Thu Oct 23 17:15:07 2003
Subject: [Tutor] Bit Strings  [a recursive approach]
In-Reply-To: <Pine.LNX.4.44.0310231112070.28886-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0310231112070.28886-100000@hkn.eecs.berkeley.edu>
Message-ID: <3F984468.5070209@aon.at>

....

>>nevertheless very compact:
>>
>> >>> def bitstrings(n):
>>        if n==0: return ["0","1"]
>>        return [ digit+bitstring for digit in bitstrings(1)
>>                                 for bitstring in bitstrings(n-1)]
>>    
>>
>
>Hi Gregor,
>
>Correction: the basis here needs to be repaired for n == 1;  otherwise,
>this won't terminate.  With a recursive approach, we have to especially
>careful about the boundary cases of our problem.
>
>
>One way to fix the bug might be:
>
>###
>def bitstrings(n):
>    if n == 0: return []
>    if n == 1: return ["0","1"]
>    return [ digit+bitstring for digit in bitstrings(1)
>                             for bitstring in bitstrings(n-1) ]
>###
>  
>
Hi Danny!
Back from a marvelous theatre performance I discovered, that I once more 
caused
some confusion by posting an incorrect statement.  That  again  came 
because I was in
a hurry. I tried out

 >>> def bitstrings(n):
        if n == 1: return ["0","1"]
        return [digit+bitstring for digit in bitstrings(1)
                                for bitstring in bitstrings(n-1)]

and this still satisfies me, although it doesn't work for n = 0. I 
transferred it into my
posting and a moment before pressing the send-button I thougt towards a 
solution
like Blakes, (which I really like; also his arguments concerning [""]).
Began to change my first idea, saw that I had no time left to try it out 
before the theatre
and quickly decided to go the "secure" way, my first idea. Changed it back,
except this bad zero:  :-(   Then, in a sudden emotion of impatience I 
pressed the send button
and I know I do this all to often.

What do I have to learn from this? To be more careful, and not to post  
if  in a hurry.

Anyway, thanks for your correction. I'm really glad that there are so 
many  people
on this list which can be considered as critical friends. (Hope this 
expression makes
sense in English).
 
Gregor

>
>Good luck!
>
>
>
>  
>


From hec.villafuerte at telgua.com.gt  Thu Oct 23 19:24:14 2003
From: hec.villafuerte at telgua.com.gt (=?ISO-8859-1?Q?=22H=E9ctor_Villafuerte_D=2E=22?=)
Date: Thu Oct 23 17:23:44 2003
Subject: [Tutor] Placeholder in string (MySQL instruction)
Message-ID: <3F98631E.6080206@telgua.com.gt>

Hi all,
I'm loading some files into MySQL tables. This function is working fine:

def load_data(proc):
    """Loads *.proc files into MySQL @ localhost."""
    cursor.execute("""LOAD DATA INFILE %s INTO TABLE traf_internat 
FIELDS TERMINATED BY ''""", (proc,))

BUT, I would like to pass the table name as an argument also... 
something like this:

load_data(os.getcwd()+'\\'+'ldia.proc', 'traf_internat')

def load_data(proc, table):
    """Loads *.proc files into MySQL @ localhost."""
    cursor.execute("""LOAD DATA INFILE %s INTO TABLE %s FIELDS 
TERMINATED BY ''""", (proc,table))

Unfortunately, this won't work:

Traceback (most recent call last):
  File "c:\Python23\progs\ttp\ttp_build.py", line 88, in ?
    ttp_mysql.load_data(os.getcwd()+'\\'+'ldia.proc', 'traf_internat')
  File "c:\Python23\progs\ttp\ttp_mysql.py", line 13, in load_data
    cursor.execute("""LOAD DATA INFILE %s INTO TABLE %s FIELDS 
TERMINATED BY ''""", (proc,table))
  File "C:\Python23\Lib\site-packages\MySQLdb\cursors.py", line 95, in 
execute
    return self._execute(query, args)
  File "C:\Python23\Lib\site-packages\MySQLdb\cursors.py", line 114, in 
_execute
    self.errorhandler(self, exc, value)
  File "C:\Python23\Lib\site-packages\MySQLdb\connections.py", line 33, 
in defaulterrorhandler
    raise errorclass, errorvalue
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your 
SQL syntax.  Check the manual that corresponds to
your MySQL server version for the right syntax to use near 
''traf_internat' FIELDS TERMINATED BY ''' at line 1")

Thanks in advance for your help,
Hector


From hec.villafuerte at telgua.com.gt  Thu Oct 23 19:38:03 2003
From: hec.villafuerte at telgua.com.gt (=?ISO-8859-1?Q?=22H=E9ctor_Villafuerte_D=2E=22?=)
Date: Thu Oct 23 17:37:28 2003
Subject: [Tutor] Placeholder in string (MySQL instruction)
In-Reply-To: <3F98631E.6080206@telgua.com.gt>
References: <3F98631E.6080206@telgua.com.gt>
Message-ID: <3F98665B.5030808@telgua.com.gt>

H?ctor Villafuerte D. wrote:

> Unfortunately, this won't work:
>
> Traceback (most recent call last):
>  File "c:\Python23\progs\ttp\ttp_build.py", line 88, in ?
>    ttp_mysql.load_data(os.getcwd()+'\\'+'ldia.proc', 'traf_internat')
>  File "c:\Python23\progs\ttp\ttp_mysql.py", line 13, in load_data
>    cursor.execute("""LOAD DATA INFILE %s INTO TABLE %s FIELDS 
> TERMINATED BY ''""", (proc,table))
>  File "C:\Python23\Lib\site-packages\MySQLdb\cursors.py", line 95, in 
> execute
>    return self._execute(query, args)
>  File "C:\Python23\Lib\site-packages\MySQLdb\cursors.py", line 114, in 
> _execute
>    self.errorhandler(self, exc, value)
>  File "C:\Python23\Lib\site-packages\MySQLdb\connections.py", line 33, 
> in defaulterrorhandler
>    raise errorclass, errorvalue
> _mysql_exceptions.ProgrammingError: (1064, "You have an error in your 
> SQL syntax.  Check the manual that corresponds to
> your MySQL server version for the right syntax to use near 
> ''traf_internat' FIELDS TERMINATED BY ''' at line 1")
>

I think that basically the problem is that I need to unquote the table 
name, i.e. remove this ' .
At least I'm getting closer :)


From bvg.pythontutor at freemail.hu  Thu Oct 23 17:48:44 2003
From: bvg.pythontutor at freemail.hu (Gabor Borgulya)
Date: Thu Oct 23 17:47:23 2003
Subject: [Tutor] sound/Morse on Linux
Message-ID: <1066945723.2127.59.camel@catv-d5de952e.bp04catv.broadband.hu>

Hi!

Could someone tell me how I can make sound from python on a Linux
system? I would like to write a simple program that reads a text loudly
with Morse sound symbols. If there was a function like Beep of the
winsound module, that would be very useful for me.
I found linuxaudiodev among the undocumented modules, but I couldn't
figure out how to make any sound with it.

G?bor

From pythontutor at venix.com  Thu Oct 23 17:49:33 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Thu Oct 23 17:49:40 2003
Subject: [Tutor] Placeholder in string (MySQL instruction)
In-Reply-To: <3F98631E.6080206@telgua.com.gt>
References: <3F98631E.6080206@telgua.com.gt>
Message-ID: <3F984CED.9030306@venix.com>

My guess is that table contains
	'traf_internat'
and not simply
	traf_internat

I think it is a good idea to have some mechanism in place to log/print
your sql statements so that you can better debug this kind of problem.
I'd recommend your own execute function which printed or logged the sql
statement before passing it on to cursor execute.

Otherwise, this could be a bug in MySQLdb.  The quick workaround is for
you to do the string interpolation yourself:

cursor.execute("""LOAD DATA INFILE '%s' INTO TABLE %s FIELDS TERMINATED BY ''""" % (proc,table))
(I think I got the quoting correct)

H?ctor Villafuerte D. wrote:

> Hi all,
> I'm loading some files into MySQL tables. This function is working fine:
> 
> def load_data(proc):
>    """Loads *.proc files into MySQL @ localhost."""
>    cursor.execute("""LOAD DATA INFILE %s INTO TABLE traf_internat FIELDS 
> TERMINATED BY ''""", (proc,))
> 
> BUT, I would like to pass the table name as an argument also... 
> something like this:
> 
> load_data(os.getcwd()+'\\'+'ldia.proc', 'traf_internat')
> 
> def load_data(proc, table):
>    """Loads *.proc files into MySQL @ localhost."""
>    cursor.execute("""LOAD DATA INFILE %s INTO TABLE %s FIELDS TERMINATED 
> BY ''""", (proc,table))
> 
> Unfortunately, this won't work:
> 
> Traceback (most recent call last):
>  File "c:\Python23\progs\ttp\ttp_build.py", line 88, in ?
>    ttp_mysql.load_data(os.getcwd()+'\\'+'ldia.proc', 'traf_internat')
>  File "c:\Python23\progs\ttp\ttp_mysql.py", line 13, in load_data
>    cursor.execute("""LOAD DATA INFILE %s INTO TABLE %s FIELDS TERMINATED 
> BY ''""", (proc,table))
>  File "C:\Python23\Lib\site-packages\MySQLdb\cursors.py", line 95, in 
> execute
>    return self._execute(query, args)
>  File "C:\Python23\Lib\site-packages\MySQLdb\cursors.py", line 114, in 
> _execute
>    self.errorhandler(self, exc, value)
>  File "C:\Python23\Lib\site-packages\MySQLdb\connections.py", line 33, 
> in defaulterrorhandler
>    raise errorclass, errorvalue
> _mysql_exceptions.ProgrammingError: (1064, "You have an error in your 
> SQL syntax.  Check the manual that corresponds to
> your MySQL server version for the right syntax to use near 
> ''traf_internat' FIELDS TERMINATED BY ''' at line 1")
> 
> Thanks in advance for your help,
> Hector
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582


From bvg.pythontutor at freemail.hu  Thu Oct 23 17:57:30 2003
From: bvg.pythontutor at freemail.hu (Gabor Borgulya)
Date: Thu Oct 23 17:55:57 2003
Subject: [Tutor] Re: adding type methods?
In-Reply-To: <E1ACZX3-0000Dj-00@hooloovoo>
References: <200310231731.47488.thomi@imail.net.nz>
	<E1ACZX3-0000Dj-00@hooloovoo>
Message-ID: <1066946249.2139.62.camel@catv-d5de952e.bp04catv.broadband.hu>

2003-10-23, cs keltez?ssel Abel Daniel ezt ?rta:
> Well, in newer pythons (it think after 2.3, with the introduction of
> new-style classes) you can subclass any built-in type

I tested your example in Python 2.2.2, and it did work!
G

From hec.villafuerte at telgua.com.gt  Thu Oct 23 20:08:45 2003
From: hec.villafuerte at telgua.com.gt (=?ISO-8859-1?Q?=22H=E9ctor_Villafuerte_D=2E=22?=)
Date: Thu Oct 23 18:08:15 2003
Subject: [Tutor] Placeholder in string (MySQL instruction)
In-Reply-To: <3F984CED.9030306@venix.com>
References: <3F98631E.6080206@telgua.com.gt> <3F984CED.9030306@venix.com>
Message-ID: <3F986D8D.6030007@telgua.com.gt>

Lloyd Kvam wrote:

> My guess is that table contains
>     'traf_internat'
> and not simply
>     traf_internat
>
> I think it is a good idea to have some mechanism in place to log/print
> your sql statements so that you can better debug this kind of problem.
> I'd recommend your own execute function which printed or logged the sql
> statement before passing it on to cursor execute.
>
> Otherwise, this could be a bug in MySQLdb.  The quick workaround is for
> you to do the string interpolation yourself:
>
> cursor.execute("""LOAD DATA INFILE '%s' INTO TABLE %s FIELDS 
> TERMINATED BY ''""" % (proc,table))
> (I think I got the quoting correct)


Thanks Lloyd!
I got it working like this...

The function call:
    load_data('ldia.proc', 'traf_internat')

The function definition:
    def load_data(proc, table):
        """Loads *.proc files into MySQL @ localhost."""
        tmp = string.replace(os.getcwd()+'\\'+proc, '\\', '\\\\')
        cursor.execute("""LOAD DATA INFILE '%s' INTO TABLE %s FIELDS 
TERMINATED BY ''""" % (tmp,table))



From arkamir at softhome.net  Thu Oct 23 18:47:07 2003
From: arkamir at softhome.net (Conrad Koziol)
Date: Thu Oct 23 18:47:20 2003
Subject: [Tutor] cannot concatenate str with tuple obj
Message-ID: <1066949226.5932.6.camel@quercus>

When I try to execute the code below i get a 'cant concanate str with
tuple object', and i dont know how to fix it. Though when i print out
postinfo contents it seems to me like they are a string object Any help
would be appreciated. :) 


import MySQLdb
import re
db = MySQLdb.connect(host='localhost', user='conrad', passwd='evil'\
db='cgi')

cursor = db.cursor()

def retrieveposts(forum, thread):
	giventemplate = 'posttemplate'
	inputtemplate = open(giventemplate, 'r')
	posttemplate = inputtemplate.read()
	cursor.execute('''select names, subjects, posts, positions\ from %s
where threads =\'%s\'''' % (forum, threads))
	postsinfo = cursor.fetchall()
	#sort postsinfo by column positions
	posts = ''
	for y in postsinfo:
		for x in range(0,4):
			posts = posts + re.subn(('<!--INSERT %s\ HERE-->' % y[x]), y[x],
posttemplate)
	return posts

p.s. i apologise for any indentation errors, my client sometimes does
weird stuff. Thanks

	konradkoziol

From project5 at redrival.net  Thu Oct 23 19:01:43 2003
From: project5 at redrival.net (Andrei)
Date: Thu Oct 23 19:03:58 2003
Subject: [Tutor] Re: cannot concatenate str with tuple obj
In-Reply-To: <1066949226.5932.6.camel@quercus>
References: <1066949226.5932.6.camel@quercus>
Message-ID: <bn9mon$uvp$1@sea.gmane.org>

Conrad Koziol wrote:

> When I try to execute the code below i get a 'cant concanate str with
> tuple object', and i dont know how to fix it. Though when i print out
> postinfo contents it seems to me like they are a string object Any help
> would be appreciated. :) 

You should have posted the traceback, not just the code (the traceback 
tells you a code line number as well). It's harder to guess where the error 
is without that traceback.

> 	posts = ''
> 	for y in postsinfo:
> 		for x in range(0,4):
> 			posts = posts + re.subn(('<!--INSERT %s\ HERE-->' % y[x]), y[x],
> posttemplate)
> 	return posts

This is where you get the error? Because the subn docs say this:

subn( pattern, repl, string[, count])
Perform the same operation as sub(), but return a tuple (new_string, 
number_of_subs_made).

Pay attention to what it returns. This means that you're trying to 
concatenate a string (posts) and a tuple (the results of subn).

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V 
ernq gur yvfg, fb gurer'f ab arrq gb PP.



From arkamir at softhome.net  Thu Oct 23 19:12:32 2003
From: arkamir at softhome.net (Conrad Koziol)
Date: Thu Oct 23 19:12:47 2003
Subject: [Tutor] Thanks a lot
Message-ID: <1066950751.5932.9.camel@quercus>

Thanks everyone for helping me understand sorting nested lists better.
:) Danny's and Alfred's were especially helpful.

	konradkoziol

From dyoo at hkn.eecs.berkeley.edu  Thu Oct 23 19:28:33 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Oct 23 19:28:41 2003
Subject: [Tutor] Bit Strings  [a recursive approach]
In-Reply-To: <3F984468.5070209@aon.at>
Message-ID: <Pine.LNX.4.44.0310231618480.18610-100000@hkn.eecs.berkeley.edu>

> What do I have to learn from this? To be more careful, and not to post
> if in a hurry.

Hi Gregor,

Don't worry: it happens to me all the time.  Programming is a human
endeavor.  I get all too impatient too at work, especially after a long
bugfixing day, and that's exactly when I start writing really buggy code.
*grin*


Best of wishes!


From dyoo at hkn.eecs.berkeley.edu  Thu Oct 23 19:32:22 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Oct 23 19:32:28 2003
Subject: [Tutor] sound/Morse on Linux
In-Reply-To: <1066945723.2127.59.camel@catv-d5de952e.bp04catv.broadband.hu>
Message-ID: <Pine.LNX.4.44.0310231630170.18610-100000@hkn.eecs.berkeley.edu>



On 23 Oct 2003, Gabor Borgulya wrote:

> Could someone tell me how I can make sound from python on a Linux
> system? I would like to write a simple program that reads a text loudly
> with Morse sound symbols. If there was a function like Beep of the
> winsound module, that would be very useful for me. I found linuxaudiodev
> among the undocumented modules, but I couldn't figure out how to make
> any sound with it.

Hi Gabor,

You might find the 'pygame' third-party module really useful here:

    http://pygame.org/

'pygame' has a nice sound module that you can use to simulate the morse
code beeps.  It also works on both Windows, Linux, and Mac OS X, so it's
also very portable.


Good luck!


From littledanehren at yahoo.com  Thu Oct 23 20:27:55 2003
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Thu Oct 23 20:27:59 2003
Subject: [Tutor] Re: handling string!!
In-Reply-To: <bn9f9b$qeg$1@sea.gmane.org>
Message-ID: <20031024002755.65410.qmail@web41804.mail.yahoo.com>


--- Andrei <project5@redrival.net> wrote:
> Daniel Ehrenberg wrote:
> 
> <snip>
> > I have a somewhat related question. I am trying to
> > write a program to parse the simple markup
> language
> > used at Wikipedia.org. For this specific question,
> the
> > markup is the same as in MoinMoin.
> 
> Kirk Bailey (who's around here too) has an open
> source Wiki at 
> tinylist.org, written in Python:
> 
> http://www.tinylist.org/cgi-bin/wikinehesaed2.py
> 
> It handles this kinda thing quite well, I just
> tested it at the bottom of 
>
http://www.tinylist.org/cgi-bin/wikinehesaed2.py/SandBox.
> Perhaps you 
> should look at its code.

It uses completely different markup. And anyway, it
didn't work.
> 
> > '''bold''' -> <strong>bold</strong>
> > ''italics'' -> <em>italics</em>
> > '''''bold and italics''''' -> <strong><em>bold and
> > italics</em></strong>
> > '''''b & i'' b''' -> <strong><em>b & i</em>
> b</strong>
> > '''''b & i''' i'' -> <em><strong>b & i</strong>
> i</em>
> 
> <snip>
> 
> You just have to keep track of what you have open
> and apply the first open, 
> last to close principle (use a list to which you
> append tags when you open 
> them and then delete them when you close them
> starting from the last). 
> In 
> your 5th example:
> 
>  > '''''b & i''' i'' -> <em><strong>b & i</strong>
> i</em>
> 
> your parser would e.g. first hit ''' (open <strong>
> and append it to the 
> OpenTags list), then the '' (open <em> and append it
> to the OpenTags list). 
> When it finds the closing ''', it tries to close the
> <strong>, but it 
> notices in the OpenTags list that there are tags
> before it. It closes those 
> first (in this case, the last tag in OpenTags is
> <em>, so it closes it 
> first, but places it in a different list, say
> RestoreTags), then it closes 
> the <strong> and reopens the ones in RestoreTags -
> obviously, these end up 
> being on the OpenTags list again. The generated code
> is then:
> 
> <strong><em>b & i</em></strong><em> i</em>
> 
> Which is not perfect, but it's valid XHTML :).
> Making it really intelligent 
> would be quite a bit harder, especially if you
> consider you might be 
> nesting more tags.

Well, then I'd have to write the code completely
differently than I wrote it on the previous letter.
How do you think I could go about writing the actual
code using that method?

> 
> I'm not sure this is the way Kirk's Wiki does it,
> but I know it would work 
> because I use this same principle in my regular
> expression tool to 
> highlight parentheses.
> 
Kirk's wiki uses different things for opening quotes
and closing quotes.

> I'm wondering how you'd handle '''''' though (can be
> two bolds or three 
> italics).
> 
> -- 
> Yours,
> 
> Andrei

Well, that would be an error on the writer's part, so
the resulting XHTML would probably also be eroneous :)
I don't want to spend too much time checking for
errors, as the original MediaWiki (Wikipedia's
PHP/mySQL implimentation) software doesn't either and
I only want compatability with it, not extra features
(except for an added GUI).
LDan


__________________________________
Do you Yahoo!?
The New Yahoo! Shopping - with improved product search
http://shopping.yahoo.com

From rclilly at cox.net  Fri Oct 24 04:00:09 2003
From: rclilly at cox.net (Robert Lilly)
Date: Fri Oct 24 04:00:41 2003
Subject: [Tutor] Introduction and ? re: searching the list's archives
In-Reply-To: <20031019191637.GA6578@ugcs.caltech.edu>
Message-ID: <AMEDJPACLBJGECKBDAOKAEIICCAA.rclilly@cox.net>

>
> how about mutt.  it should come with a full distribution
> of cygwin.  it will likely take a few minutes to load a
> very large mbox, but you get powerful searches like:
>
>   show me all posts with a subject containing
>   "dictionary", a body containing "hashable", that have
>   been replied to and are PGP signed from 10/1/01 to
>   11/1/01
>
>   ~s dictionary ~b hashable ~Q ~g ~d 1/10/01-1/11/01
>
> see here for a full description of mutt patterns:
>
>     http://mutt.org/doc/manual/manual-4.html#ss4.2
>
> to run it on your file, just type:
>
>   mutt -f <name of mbox>
>
> for messages it finds, you will see them in a nice
> threaded format.

Thanks, I'll check that out as I'm still experiment with ways to search the
archive.

> if you have multiple mboxes to search there is a nice
> program that can search gzipped, bzip2ed mboxes, maildirs
> by date and regexes within headers and/or body.  it also
> includes a wrapper for mutt or pine called grepmail:
>
>   http://grepmail.sourceforge.net/

Cool, I'll definitely check this out as I have Pine already installed and
operational.

> wow, i am replying almost a month too late.

No problem! The reply was still relevant. Thanks!


From project5 at redrival.net  Fri Oct 24 05:32:40 2003
From: project5 at redrival.net (Andrei)
Date: Fri Oct 24 05:34:54 2003
Subject: [Tutor] Re: handling string!!
In-Reply-To: <20031024002755.65410.qmail@web41804.mail.yahoo.com>
References: <bn9f9b$qeg$1@sea.gmane.org>
	<20031024002755.65410.qmail@web41804.mail.yahoo.com>
Message-ID: <bnarnp$p7a$1@sea.gmane.org>

Daniel Ehrenberg wrote:
<snip>

>>Perhaps you 
>>should look at its code.
> 
> 
> It uses completely different markup. And anyway, it
> didn't work.

I'm afraid I sent you the wrong links. Here's the correct one:

http://www.tinylist.org/cgi-bin/wikinehesa.py/SandBox

At the bottom, I've pasted this code:
`````b & i''' i''
`````b & i'' i'''

The HTML produced:

<b><i> b &amp; i</i></b><i> i </i>
<b><i> b &amp; i </i> i</b>

Looks correct to me. Perhaps it breaks in other cases though, I have no idea.

<snip>

> Well, then I'd have to write the code completely
> differently than I wrote it on the previous letter.
> How do you think I could go about writing the actual
> code using that method?

The code you mention in your previous letter would work with nested tags 
too, you just wouldn't get valid XHTML (you'd get <b><i></b></i>). You 
could fix it by running Tidy on it (I think there's a Python binding for it 
somewhere). But I think that if you want valid XHTML, string splitting 
won't get you that unless you use some kind of lookahead mechanism to find 
out which is closed first and hence must be opened last - not that fun IMO. 
Given the options, I'd rather take the simple finite state machine route 
with the list. It's not particularly hard to code.

> Kirk's wiki uses different things for opening quotes
> and closing quotes.

True, but I'm not sure how much of a difference that makes. He still has to 
close the right one at the right time. Anyway, I just looked at the code of 
the 1.2.0 tarball and I find it puzzling:

   line=string.replace(line,"```",'<b>')	# Start a BOLD block
   line=string.replace(line,"'''",'</b>')# end a BOLD block
   line=string.replace(line,"``",'<i> ')	# start an italic block
   line=string.replace(line,"''",' </i>')# end an italic block

I don't understand how this makes:

    `````b & i''' i''

into:

    <b><i> b &amp; i</i></b><i> i </i>

In an interactive session we'd get the expected invalid HTML with that code:

 >>> t = "`````b & i''' i''"
 >>> t = t.replace("```",'<b>')
 >>> t = t.replace("'''",'</b>')
 >>> t = t.replace("``",'<i> ')
 >>> t = t.replace("''",' </i>')
 >>> t
'<b><i> b & i</b> i </i>'


-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V 
ernq gur yvfg, fb gurer'f ab arrq gb PP.



From mhansen at cso.atmel.com  Fri Oct 24 10:28:30 2003
From: mhansen at cso.atmel.com (Mike Hansen)
Date: Fri Oct 24 10:26:21 2003
Subject: [Tutor] Multiple exits in a function...
In-Reply-To: <E1ACi3O-0005Al-MC@mail.python.org>
References: <E1ACi3O-0005Al-MC@mail.python.org>
Message-ID: <3F99370E.10309@cso.atmel.com>

I'm curious about this. A co-worker was ranting recently while debugging 
some C code that it had multiple exits. (BTW: It wasn't my C code. I 
have never written C code except in college.)

I trend to write my functions with multiple exits. Usually when some 
test fails, I spit a message(email, print it, or write it to a log file) 
and get out of dodge. The alternative is usually horrible nested If 
statements even if I flip the logic around. Which to me makes it hard to 
read and maintain.

Can you point me to some resources to help me wrap my mind around this? 
Code examples? ...

Thanks,

Mike

>
> Subject:
> Re: [Tutor] Re: Request for code critique ['break' vs control flag]
> From:
> "Alan Gauld" <alan.gauld@blueyonder.co.uk>
> Date:
> Thu, 23 Oct 2003 06:00:22 +0100
> To:
> "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu>
>
>
>>>whence into many other languages) which breaks the rules of
>>>      
>>>
>structured
>  
>
>>>programming and by so doing makes code more difficult to read
>>>      
>>>
>reliably.
>
>  
>
>>But I've also met a lot of respected programmers who insist on the
>>    
>>
>"one
>  
>
>>entry point, and one exit point" viewpoint. 'break' drives them
>>    
>>
>crazy.
>  
>
>>So, like many style guidelines, it's a controversial issue. *grin*
>>    
>>
>
>I think the issue is that this is NOT a style thing. It's
>one of the basic tenets of structured programming and based
>on actual hard data. Having multiple exit points makes code
>harder to comprehend and hence more prone to error.
>
>Sometimes people forget the reasons behind some of these
>early discoveries in Computer Science. In fact I just finished
>reviewing a book by Robert Glass: "Facts and Fallacies of
>Software Engineering" which is based entirely on the concept
>that the faddy world of SE regularly forgets (and subsequently
>rediscovers) some of the basic truths of our trade...
>
>It falls into the same category as indentation style for
>begin/end or {} block markers. People treat it as a personal
>choice but hard evidence exists which shows that some styles
>are significantly more comprehensible than others.
>
>Alan G.
>
>  
>
>


From VICKI.STANFIELD at ROCHE.COM  Fri Oct 24 10:50:24 2003
From: VICKI.STANFIELD at ROCHE.COM (Stanfield, Vicki {D167~Indianapolis})
Date: Fri Oct 24 10:51:43 2003
Subject: [Tutor] Multiple exits in a function...
Message-ID: <CA3458C84C976E45B6372A6C14724C9F9E5964@ridmsem02.nala.roche.com>

Is it considered wrong then to have Exit on the menubar and another exit in the code?

--vicki

-----Original Message-----
From: Mike Hansen [mailto:mhansen@cso.atmel.com]
Sent: Friday, October 24, 2003 9:29 AM
To: tutor@python.org
Subject: [Tutor] Multiple exits in a function...


I'm curious about this. A co-worker was ranting recently while debugging 
some C code that it had multiple exits. (BTW: It wasn't my C code. I 
have never written C code except in college.)

I trend to write my functions with multiple exits. Usually when some 
test fails, I spit a message(email, print it, or write it to a log file) 
and get out of dodge. The alternative is usually horrible nested If 
statements even if I flip the logic around. Which to me makes it hard to 
read and maintain.

Can you point me to some resources to help me wrap my mind around this? 
Code examples? ...

Thanks,

Mike

>
> Subject:
> Re: [Tutor] Re: Request for code critique ['break' vs control flag]
> From:
> "Alan Gauld" <alan.gauld@blueyonder.co.uk>
> Date:
> Thu, 23 Oct 2003 06:00:22 +0100
> To:
> "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu>
>
>
>>>whence into many other languages) which breaks the rules of
>>>      
>>>
>structured
>  
>
>>>programming and by so doing makes code more difficult to read
>>>      
>>>
>reliably.
>
>  
>
>>But I've also met a lot of respected programmers who insist on the
>>    
>>
>"one
>  
>
>>entry point, and one exit point" viewpoint. 'break' drives them
>>    
>>
>crazy.
>  
>
>>So, like many style guidelines, it's a controversial issue. *grin*
>>    
>>
>
>I think the issue is that this is NOT a style thing. It's
>one of the basic tenets of structured programming and based
>on actual hard data. Having multiple exit points makes code
>harder to comprehend and hence more prone to error.
>
>Sometimes people forget the reasons behind some of these
>early discoveries in Computer Science. In fact I just finished
>reviewing a book by Robert Glass: "Facts and Fallacies of
>Software Engineering" which is based entirely on the concept
>that the faddy world of SE regularly forgets (and subsequently
>rediscovers) some of the basic truths of our trade...
>
>It falls into the same category as indentation style for
>begin/end or {} block markers. People treat it as a personal
>choice but hard evidence exists which shows that some styles
>are significantly more comprehensible than others.
>
>Alan G.
>
>  
>
>


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

From ATrautman at perryjudds.com  Fri Oct 24 11:04:41 2003
From: ATrautman at perryjudds.com (Alan Trautman)
Date: Fri Oct 24 11:04:56 2003
Subject: [Tutor] Multiple exits in a function...
Message-ID: <06738462136C054B8F8872D69DA140DB01C08AEF@corp-exch-1.pjinet.com>


In this case they should call the same exit function. Especially if you do
any cleanup or logging. If they use different functions for each exit, do
you really want to maintain two exit functions? Or as happens more often you
forget one and that's the one your users will use causing a problem that
will be very hard to troubleshoot.


Any multiple exits is hard to follow any frequently leads to overly
complicated functions that should be simplified. As with everything there
are exceptions (menu handling functions) but generally this is fairly
accepted especially among people who have to maintain the code later. This
frequently can be handled by creating a decent flowchart of you program and
you'll quickly find how difficult these are to explain.

Mostly my opinion I know but it will be interesting to see what others say.

Alan



-----Original Message-----
From: Stanfield, Vicki {D167~Indianapolis}
[mailto:VICKI.STANFIELD@ROCHE.COM]
Sent: Friday, October 24, 2003 9:50 AM
To: tutor@python.org
Subject: RE: [Tutor] Multiple exits in a function...


Is it considered wrong then to have Exit on the menubar and another exit in
the code?

--vicki

-----Original Message-----
From: Mike Hansen [mailto:mhansen@cso.atmel.com]
Sent: Friday, October 24, 2003 9:29 AM
To: tutor@python.org
Subject: [Tutor] Multiple exits in a function...


I'm curious about this. A co-worker was ranting recently while debugging 
some C code that it had multiple exits. (BTW: It wasn't my C code. I 
have never written C code except in college.)

I trend to write my functions with multiple exits. Usually when some 
test fails, I spit a message(email, print it, or write it to a log file) 
and get out of dodge. The alternative is usually horrible nested If 
statements even if I flip the logic around. Which to me makes it hard to 
read and maintain.

Can you point me to some resources to help me wrap my mind around this? 
Code examples? ...

Thanks,

Mike

>
> Subject:
> Re: [Tutor] Re: Request for code critique ['break' vs control flag]
> From:
> "Alan Gauld" <alan.gauld@blueyonder.co.uk>
> Date:
> Thu, 23 Oct 2003 06:00:22 +0100
> To:
> "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu>
>
>
>>>whence into many other languages) which breaks the rules of
>>>      
>>>
>structured
>  
>
>>>programming and by so doing makes code more difficult to read
>>>      
>>>
>reliably.
>
>  
>
>>But I've also met a lot of respected programmers who insist on the
>>    
>>
>"one
>  
>
>>entry point, and one exit point" viewpoint. 'break' drives them
>>    
>>
>crazy.
>  
>
>>So, like many style guidelines, it's a controversial issue. *grin*
>>    
>>
>
>I think the issue is that this is NOT a style thing. It's
>one of the basic tenets of structured programming and based
>on actual hard data. Having multiple exit points makes code
>harder to comprehend and hence more prone to error.
>
>Sometimes people forget the reasons behind some of these
>early discoveries in Computer Science. In fact I just finished
>reviewing a book by Robert Glass: "Facts and Fallacies of
>Software Engineering" which is based entirely on the concept
>that the faddy world of SE regularly forgets (and subsequently
>rediscovers) some of the basic truths of our trade...
>
>It falls into the same category as indentation style for
>begin/end or {} block markers. People treat it as a personal
>choice but hard evidence exists which shows that some styles
>are significantly more comprehensible than others.
>
>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

From tpc at csua.berkeley.edu  Fri Oct 24 12:46:21 2003
From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu)
Date: Fri Oct 24 12:46:28 2003
Subject: [Tutor] python setup.py uninstall ?
Message-ID: <20031024094533.O66070-100000@localhost.name>


hi all, I am curious if there is a way to cleanly uninstall MySQLdb, if I
installed using:

python setup.py build
python setup.py install

I tried python setup.py --help-commands but they seem to be for building
and installing.  I want to remove my current MySQLdb (0.9.2) and try
0.9.3b2 for debugging purposes.



From alan.gauld at blueyonder.co.uk  Fri Oct 24 13:06:45 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Fri Oct 24 13:08:24 2003
Subject: [Tutor] Multiple exits in a function...
References: <E1ACi3O-0005Al-MC@mail.python.org> <3F99370E.10309@cso.atmel.com>
Message-ID: <005e01c39a51$34554da0$6401a8c0@xp>

> I trend to write my functions with multiple exits. Usually when some
> test fails, I spit a message(email, print it, or write it to a log
file)
> and get out of dodge. The alternative is usually horrible nested If
> statements even if I flip the logic around.

Yes that's the extreme case. I don't usually object to multiple
returns from a function, provided the returns are at a
consistent level - usually the top.

But the concept of multiple exits being bad is best understood in
the context of structured programming by thinking of the "shape"
of the code as black blocks. Each block should be logically
complete with a single entry point and single exit point.

Inside a block there will be code struictures each with their
own blocks but an any code block level there should be only
one entry/exit path.

The problem with break in particular is that it destroys the
semantic logic of the block.

while <condition> do
     <block>

meand that while the condition is true we continually repeat
the block. You don't need to look inside the block to
understand the enclosing  block. BUT if you use breaks
(and "continue" is only marginally better) inside
the block you can only understand the flow by reading the
inner block as well, because what is really part of the
exit condituon is now in a sepaate test inside the code.
This extra level of reading increases the complexity of
comprehension for the reader.

Of course there are vaid cases where break/continue
does actually simplify the code, but the current trend
in Python to avoid pre loop initialisation (an important
part of comprehending how the loop works!) is not a good
case.

For example:

test = obj.read()
while test < 100 and not eof(foo):
     block here

vv

while not eof(foo):
     test = obj.read()
     if test: break
     block here


In the second example the terminating condition is not
a single boolean expression but split. And now reading
the outer block I have to start reading the inner to
see that the loop actually can terminate due to two
possible scenarios wheras the first version makes it
all clear in the the while statement itself. It also
tells me what the loop initialiser is so that I get
some idea of the potential number of iterations. All
without reading any of the code inside the while.

> Can you point me to some resources to help me wrap
> my mind around this?

If you want a deeper explanation, I suspect you'll
need to look for some of the early books on Structured
Programming from the 1970's, or early 80's. Most modern
ones just mention in passing that single exit is
"a good thing" but give no reasons. (And some very new
ones ignore the research thats already been done and say
its OK!)

Alan G.


From dyoo at hkn.eecs.berkeley.edu  Fri Oct 24 13:51:02 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Oct 24 13:52:00 2003
Subject: [Tutor] Multiple exits in a function...
In-Reply-To: <06738462136C054B8F8872D69DA140DB01C08AEF@corp-exch-1.pjinet.com>
Message-ID: <Pine.LNX.4.44.0310241038530.23430-100000@hkn.eecs.berkeley.edu>



On Fri, 24 Oct 2003, Alan Trautman wrote:

> In this case they should call the same exit function. Especially if you
> do any cleanup or logging. If they use different functions for each
> exit, do you really want to maintain two exit functions? Or as happens
> more often you forget one and that's the one your users will use causing
> a problem that will be very hard to troubleshoot.

Hi Alan,


Wait, wait, I think we're talking about something else.

Let's say we're writing a function that searches a list for an even
number.  If it can find it, the function will return it.  Otherwise, it'll
return -1.

Here's one way to write it:

###
def findEven(L):
    """Returns an even number out of list L.  If no such number exists,
    returns -1."""
    for x in L:
        if x % 2 == 0:
            return x
    return -1
###

This is a function with multiple "exits" out of the function: we get out
either through the first "return", or the "second" return.


There's another way of writing this so that there's only one 'return' out
of the function:

###
def findEven(L):
    """Returns an even number out of list L.  If no such number exists,
    returns -1."""
    result = -1
    for x in L:
        if x % 2 == 0:
            result = x
    return result
###

(The behavior of both functions is not quite equivalent.  That's why the
docstring doesn't say anything about returning the 'first' even number it
encounters.)


Talk to you later!


From jeff at ccvcorp.com  Fri Oct 24 14:10:51 2003
From: jeff at ccvcorp.com (Jeff Shannon)
Date: Fri Oct 24 14:06:34 2003
Subject: [Tutor] Multiple exits in a function...
In-Reply-To: <005e01c39a51$34554da0$6401a8c0@xp>
References: <E1ACi3O-0005Al-MC@mail.python.org> <3F99370E.10309@cso.atmel.com>
	<005e01c39a51$34554da0$6401a8c0@xp>
Message-ID: <3F996B2B.5080408@ccvcorp.com>

I find this conversation interesting.  Some very respectable 
programmers on comp.lang.python espouse the very thing that Alan is 
recommending against, so this isn't necessarily a clear-cut issue.  I 
do agree with Alan's points, but there's complicating factors too.

Alan Gauld wrote:

> For example:
> 
> test = obj.read()
> while test < 100 and not eof(foo):
>      block here

However, if you expand this just a bit to show the loop 
re-initialization, it doesn't look quite so clean --

test = obj.read()
while test < 100 and not eof(foo):
     [block here]
     test = obj.read()

You have to set test in two different places, one of which is at the 
*end* of the loop.  This is counterintuitive and confusing in a 
different way.  And you've got the maintenance hassle of duplicated code.

> vv
> 
> while not eof(foo):
>      test = obj.read()
>      if test: break
>      block here

I (and, I believe, the c.l.p gurus who espouse this loop structure) 
would prefer to write this differently:

while 1:
     test = obj.read()
     if test >= 100 or eof(foo):
         break
     [block here]

By explicitly making this an infinite loop, it sends a clear signal to 
the reader that one must look elsewhere to find the loop exit.  It's 
true that the terminating condition is now hidden within the loop, 
which is unfortunate, but at least all possible terminating conditions 
are in the same place.  In fact, there *is* a single exit to this 
loop, as suggested by structured programming; it's just that the exit 
is within the body of the loop, rather than right at the top.

In fact, one could summarize the loop structure like this:

while 1:
     [iteration initialization]
     if [terminating condition(s)]:
         break
     [loop body]

To my mind, as long as this structure is closely followed, then one is 
staying fairly close to the spirit of structured programming, if not 
the letter.  One can look at this as a spelling variation of a 
do...while...repeat loop -- AFAIK (which admittedly isn't terribly 
reliable), that structure isn't specifically deprecated in structured 
programming.  And, at least to my mind, it seems cleaner than the 
structure Alan is recommending, which would be similarly summarized:

[iteration initialization]
while [terminating condition(s)]:
     [loop body]
     [iteration initialization]

I think that it's important to remember that everything involved in 
programming is a trade-off -- everything has a cost and a benefit.  In 
some cases the cost is negligible and the benefit large; this is 
usually the case for structured programming techniques.  In other 
cases the benefits are moderate and the cost is large; this is 
typically true of "goto" and similar structures (or should I say 
anti-structures?)  But there's always edge cases, where different 
beneficial techniques (blocks should have a single exit, code 
duplication should be avoided) end up conflicting, and sometimes it's 
best to find a compromise that follows the intent behind both 
techniques, even if it doesn't adhere to the specific recommendations.

Of course, all of this is just my opinion, and I've had considerably 
less education in this area than Alan has, so... standard disclaimers, 
YMMV, etc, etc  :)

Jeff Shannon
Technician/Programmer
Credit International



From simple_stuff at hotmail.com  Fri Oct 24 15:14:05 2003
From: simple_stuff at hotmail.com (Tom Semple)
Date: Fri Oct 24 15:17:06 2003
Subject: [Tutor] What is "pythonic"?
Message-ID: <Sea2-DAV60i3s1wsXZZ000091dd@hotmail.com>

I've seen frequent reference on this list and in other Python resources to the adjective 'pythonic'. For now I am translating "pythonic" as "takes good advantage of the expressive qualities of the Python language". However, as a newcomer to the language, I'm finding this translation doesn't always allow me to understand the point that is being made (especially when there is no attempt to elaborate beyond a bland assertion that some code is or is not 'pythonic'). Can anyone suggest some resources that have a number of code examples that illustrate 'pythonic' vs. 'non-pythonic' style?

On a related question, I'd like to know more about the philosophy and history of Python. For example, I came across a quote "we are all consenting adults here" I think in explaining why it is not necessary to have type declaration statements in Python, in contrast to other strongly-typed languages. I'm looking for more of that sort of material.

Thanks,
Tom
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20031024/18810e99/attachment.html
From littledanehren at yahoo.com  Fri Oct 24 15:28:45 2003
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Fri Oct 24 15:28:50 2003
Subject: [Tutor] Multiple exits in a function...
In-Reply-To: <Pine.LNX.4.44.0310241038530.23430-100000@hkn.eecs.berkeley.edu>
Message-ID: <20031024192845.45987.qmail@web41804.mail.yahoo.com>

> Hi Alan,
> 
> 
> Wait, wait, I think we're talking about something
> else.
> 
> Let's say we're writing a function that searches a
> list for an even
> number.  If it can find it, the function will return
> it.  Otherwise, it'll
> return -1.
> 
> Here's one way to write it:
> 
> ###
> def findEven(L):
>     """Returns an even number out of list L.  If no
> such number exists,
>     returns -1."""
>     for x in L:
>         if x % 2 == 0:
>             return x
>     return -1
> ###
> 
> This is a function with multiple "exits" out of the
> function: we get out
> either through the first "return", or the "second"
> return.
> 
> 
> There's another way of writing this so that there's
> only one 'return' out
> of the function:
> 
> ###
> def findEven(L):
>     """Returns an even number out of list L.  If no
> such number exists,
>     returns -1."""
>     result = -1
>     for x in L:
>         if x % 2 == 0:
>             result = x
>     return result
> ###
> 
> (The behavior of both functions is not quite
> equivalent.  That's why the
> docstring doesn't say anything about returning the
> 'first' even number it
> encounters.)
> 
> 
> Talk to you later!

I really don't see what's wrong with multiple returns,
especially in a simple function like this. To me, the
first one is more clear. For this function in
particular, wouldn't the first one terminate first
because it doesn't have to go through the entire list?
Daniel Ehrenberg

__________________________________
Do you Yahoo!?
The New Yahoo! Shopping - with improved product search
http://shopping.yahoo.com

From karl.fast at pobox.com  Fri Oct 24 15:32:17 2003
From: karl.fast at pobox.com (Karl Fast)
Date: Fri Oct 24 15:32:24 2003
Subject: [Tutor] What is "pythonic"?
In-Reply-To: <Sea2-DAV60i3s1wsXZZ000091dd@hotmail.com>;
	from simple_stuff@hotmail.com on Fri, Oct 24, 2003 at 12:14:05PM
	-0700
References: <Sea2-DAV60i3s1wsXZZ000091dd@hotmail.com>
Message-ID: <20031024133217.R5505@signal.lights.com>

> I came across a quote "we are all consenting adults here" I think in
> explaining why it is not necessary to have type declaration
> statements in Python, in contrast to other strongly-typed languages.

This expression is also used in the object-oriented python
literature to explain python's attitudes about private class
members, which python doesn't have. 

When you create an instance of some class there is nothing to
prevent you from poking around inside and using various internal,
private methods that are (a) necessary for the class to function,
BUT (b) not intended for direct use/access.

Nothing is really private in python. No class or class instance can
keep you away from all what's inside (this makes introspection
possible and powerful). Python trusts you. It says "hey, if you want
to go poking around in dark places, I'm gonna trust that you've got
a good reason and you're not making trouble."

After all, we're all consenting adults here.

C++ and Java don't have this philosophy (not to the same extent).
They allow you create private methods and static members. 

Perl culture is like python in this respect, but Perl expresses the
sentiment a bit differently. As the Camel book puts it,

  "a Perl module would prefer that you stayed out of its living room
  because you weren't invited, not because it has a shotgun."

But the sentiment is identical.
  
--karl

From project5 at redrival.net  Fri Oct 24 15:30:34 2003
From: project5 at redrival.net (Andrei)
Date: Fri Oct 24 15:32:55 2003
Subject: [Tutor] Re: What is "pythonic"?
In-Reply-To: <Sea2-DAV60i3s1wsXZZ000091dd@hotmail.com>
References: <Sea2-DAV60i3s1wsXZZ000091dd@hotmail.com>
Message-ID: <bnbuor$bsd$1@sea.gmane.org>

Tom Semple wrote:
> I've seen frequent reference on this list and in other Python resources 
> to the adjective 'pythonic'. For now I am translating "pythonic" as 
> "takes good advantage of the expressive qualities of the Python 
> language". However, as a newcomer to the language, I'm finding this 

Type "import this" in your Python interpreter :).

Also read this: 
http://mail.python.org/pipermail/python-list/2003-April/158825.html

> translation doesn't always allow me to understand the point that is 
> being made (especially when there is no attempt to elaborate beyond a 
> bland assertion that some code is or is not 'pythonic'). Can anyone 
> suggest some resources that have a number of code examples that 
> illustrate 'pythonic' vs. 'non-pythonic' style?

Unpythonic is doing lots of type checking, or trying really hard to make 
something private/protected. Or using an index to loop through a list 
rather than just doing "for item in mylist". Basically anything people do 
because that's how they do it in other languages, thinking it's as good as 
it gets. Code obsfucation (Perl) is unpythonic too. People you don't like 
fall in the same category. It's a very broad term ;).

> On a related question, I'd like to know more about the philosophy and 
> history of Python. For example, I came across a quote "we are all 
> consenting adults here" I think in explaining why it is not necessary to 
> have type declaration statements in Python, in contrast to other 
> strongly-typed languages. I'm looking for more of that sort of material.

That's the zen of python you get when you import this. You could also look 
at these:

http://www.python.org/doc/essays/

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V 
ernq gur yvfg, fb gurer'f ab arrq gb PP.



From elh at outreachnetworks.com  Fri Oct 24 15:34:32 2003
From: elh at outreachnetworks.com (Eric L. Howard)
Date: Fri Oct 24 15:34:39 2003
Subject: [Tutor] What is "pythonic"?
In-Reply-To: <Sea2-DAV60i3s1wsXZZ000091dd@hotmail.com>
References: <Sea2-DAV60i3s1wsXZZ000091dd@hotmail.com>
Message-ID: <20031024193431.GA1448@outreachnetworks.com>

At a certain time, now past [Oct.24.2003-12:14:05PM -0700], simple_stuff@hotmail.com spake thusly:
>    I've seen frequent reference on this list and in other Python
>    resources to the adjective 'pythonic'. For now I am translating
>    "pythonic" as "takes good advantage of the expressive qualities of the
>    Python language". However, as a newcomer to the language, I'm finding
>    this translation doesn't always allow me to understand the point that
>    is being made (especially when there is no attempt to elaborate beyond
>    a bland assertion that some code is or is not 'pythonic'). Can anyone
>    suggest some resources that have a number of code examples that
>    illustrate 'pythonic' vs. 'non-pythonic' style?

Python 2.2.3 (#1, Aug  1 2003, 12:54:19)
[GCC 3.2.3 20030422 (Gentoo Linux 1.4 3.2.3-r1, propolice)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
>>> 

       ~elh

-- 
Eric L. Howard           e l h @ o u t r e a c h n e t w o r k s . c o m
------------------------------------------------------------------------
www.OutreachNetworks.com                                    313.297.9900
------------------------------------------------------------------------
JabberID: elh@jabber.org                 Advocate of the Theocratic Rule

From ATrautman at perryjudds.com  Fri Oct 24 15:43:02 2003
From: ATrautman at perryjudds.com (Alan Trautman)
Date: Fri Oct 24 15:43:08 2003
Subject: [Tutor] Multiple exits in a function...
Message-ID: <06738462136C054B8F8872D69DA140DB01C08AF8@corp-exch-1.pjinet.com>

<snip a lot>
I really don't see what's wrong with multiple returns,
especially in a simple function like this. To me, the
first one is more clear. For this function in
particular, wouldn't the first one terminate first
because it doesn't have to go through the entire list?
Daniel Ehrenberg

Daniel,

You are correct in that you can optimize a function to go faster using
methodology. My perspective is that of maintaining and updating software. If
there are say, 4 exit points at various intervals, to determine what the
return location and value. This means I have to plow through every line of
every function to locate every possible action. If you program a single exit
I only need trap at one point in every function.

In a small one off I probably wouldn't care but I waste a lot of man hours
finding a little known (more than 3 months since it was written) exception
that is blocking a new feature. Insert preachy premature optimization plug
here too;)

There are times; menu systems and speed sensitive apps where this is not
appropriate but most apps on modern computers it is better to waste 50 clock
cycles all the time than to make it take 3 times as long to upgrade or
repair.

Ok this is all opinion and I wish I had my old text book now to give you
some other references but I'm supposed to be working:)

Peace,
Alan



From tpc at csua.berkeley.edu  Fri Oct 24 15:58:11 2003
From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu)
Date: Fri Oct 24 15:58:25 2003
Subject: [Tutor] What is "pythonic"?
In-Reply-To: <Sea2-DAV60i3s1wsXZZ000091dd@hotmail.com>
Message-ID: <20031024123010.F67132-100000@localhost.name>


at the last BayPIGgies meeting someone mentioned how Python is like
pseudocode that is executable.  Pseudocode as you may know allows one to
conceptualize the logic of a particular program before settling down to
the nitty gritty of implementation in a particular language.

For loop to iterate over the items in a datastructure in Java:

for (i = 0; i < 10; i++)
{
    System.out.println("hello world!")
}

and in Python to iterate:

myList = range(10)
for i in myList:
    print "hello world!"

Notice the lack of curly braces.  Python as you will find provides for
much cleaner, easier to read code.

On Fri, 24 Oct 2003, Tom Semple wrote:

> I've seen frequent reference on this list and in other Python resources to the adjective 'pythonic'. For now I am translating "pythonic" as "takes good advantage of the expressive qualities of the Python language". However, as a newcomer to the language, I'm finding this translation doesn't always allow me to understand the point that is being made (especially when there is no attempt to elaborate beyond a bland assertion that some code is or is not 'pythonic'). Can anyone suggest some resources that have a number of code examples that illustrate 'pythonic' vs. 'non-pythonic' style?
>
> On a related question, I'd like to know more about the philosophy and history of Python. For example, I came across a quote "we are all consenting adults here" I think in explaining why it is not necessary to have type declaration statements in Python, in contrast to other strongly-typed languages. I'm looking for more of that sort of material.
>
> Thanks,
> Tom
>


From alan.gauld at blueyonder.co.uk  Fri Oct 24 17:14:33 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Fri Oct 24 17:16:15 2003
Subject: [Tutor] Multiple exits in a function...
References: <E1ACi3O-0005Al-MC@mail.python.org>
	<3F99370E.10309@cso.atmel.com><005e01c39a51$34554da0$6401a8c0@xp>
	<3F996B2B.5080408@ccvcorp.com>
Message-ID: <001501c39a73$d2755fd0$6401a8c0@xp>


> I find this conversation interesting.  Some very respectable
> programmers on comp.lang.python espouse the very thing that Alan is
> recommending against, so this isn't necessarily a clear-cut issue.

No, its not because the current thinking is the opposite.
However I have not seen any hard data to suggest that
it is correct, whereas several studies in the 70s showed clear
differences in comprehension in the pure structured approach.
That's why Wirth and Dijkstra advocated it, it wasn't their
personal taste it was the result of detailed study of
programmer behaviour!

> test = obj.read()
> while test < 100 and not eof(foo):
>      [block here]
>      test = obj.read()
>
> You have to set test in two different places, one of which is at the
> *end* of the loop.  This is counterintuitive and confusing in a
> different way.  And you've got the maintenance hassle of duplicated
code.

The maintenance issue is the biggest one from my personal view
but...

> while 1:
>      test = obj.read()
>      if test >= 100 or eof(foo):
>          break
>      [block here]

This is actually the worst of all worlds. The while loop purports
to be an infinite loop when it clearly isn't and now to understand
how the loop terminates at all we have to read the internal block
(which for quick program comprehension we shouldn't need to do!)

What this style does is moves away from the idea of Python being
executable pseudo code because it hides the loigic of the code
inside an if test - a branch - which is embedded in a loop. But
the loop - which is logically what is happening, not a branch
- carries absolutely no semantic value whatsoever.

> By explicitly making this an infinite loop, it sends a clear signal
to
> the reader that one must look elsewhere to find the loop exit.

Yes inside a block of code ayt a lower level than the current
one - we have broken the structure of structured proigramming
which is all about the ability to read the code clearly at each
level of abstraction. We have now forced the reader to drop
a level of detail just to understand a higher level. Its very
close to introducing a GOTO - and Kernighan said as much when
he introduced it to C - but not quite...!

> true that the terminating condition is now hidden within the loop,
> which is unfortunate, but at least all possible terminating
conditions
> are in the same place.

That's true but you have to "go fishing" to find it.

> In fact, there *is* a single exit to this
> loop, as suggested by structured programming; it's just that the
exit
> is within the body of the loop, rather than right at the top.

There is a separate type of lop for this type of exit supported only
(so far as I know) by ADA. Code Complete describes it in detail
and shows how to emiulate it in various other languages. It looks
a lot like this.

BTW, I'm not as opposed to break/continue as I probably sound.
But someone asked why it ewas considered bad in principle.
I'm merely stating the pure structured programming view!
Like everything you have to apply some intelligence. However
its worth knowing that just because lots of folks do something,
it may not be the best thing! And until somewone carries out
some rigourous studies to show that the break approach works
as well as single exit I will continue to use breaks sparingly.

> while 1:
>      [iteration initialization]
>      if [terminating condition(s)]:
>          break
>      [loop body]


And thats almost exactly how the ADA loop construct looks.
But it formalises the if test. However it also has a unique
key word which avoids implying that its a while forever loop...

> the letter.  One can look at this as a spelling variation of a
> do...while...repeat loop -- AFAIK

Its a fudge because Python doesn't have such a structure.
The key point about a while loop is that it should be used
when we don't know whether we ever want the loop to execute
at all. The repeat loop by contrasat always executes *at least once*.
So there is a clear semantic difference between the two.
In Python if you need a loop that always executes at least
once you are forceed into these sorts of fudges.

> structure Alan is recommending, which would be similarly summarized:
>
> [iteration initialization]
> while [terminating condition(s)]:
>      [loop body]
>      [iteration initialization]

Thats correct, its the standard while loop behaviour.
The initialisation is logically part of the block since
of the block was not self modifying the loop would never
terminate and the explicit first initialisation is a vital
part of the readability of the structure.

> I think that it's important to remember that everything involved in
> programming is a trade-off -- everything has a cost and a benefit.
In
> some cases the cost is negligible and the benefit large; this is
> usually the case for structured programming techniques.

Absolutely, and we mneed to understand the trade-offs. In this
case the trade off is between rapid comprehension and double
maintenance.

> best to find a compromise that follows the intent behind both
> techniques, even if it doesn't adhere to the specific
recommendations.

Or make an informed choice to suit the actual situation.

> Of course, all of this is just my opinion, and I've had considerably
> less education in this area than Alan has,

Hmm, I've just read a lot of books... :-)

And as I said above i'm much less religious about this issue in
practice than I am in principle!

Alan G.


From alan.gauld at blueyonder.co.uk  Fri Oct 24 17:19:10 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Fri Oct 24 17:20:44 2003
Subject: [Tutor] Multiple exits in a function...
References: <20031024192845.45987.qmail@web41804.mail.yahoo.com>
Message-ID: <001a01c39a74$773a5020$6401a8c0@xp>

> I really don't see what's wrong with multiple returns,
> especially in a simple function like this. 

YOu have actually just hit on a very important point.
Where the functions are short and only have a few levels 
of nesting - as is usually the case in languages like 
Python - the whole issue of comprehension and levels 
of reading are much less important.

In more traditional 3rd generation languages like C 
or Pascal it was quite common for *functions* to 
be 50-100 lines long with up to 7 or more levels of 
indentation/nesting. In that type of environment 
the ability to stop reading after more than 2 levels 
of indent and still make sense of the code was 
very important.

When the whole *program* is only 100 lines then the 
issue is much less serious. But then again the whole 
need for structure is much less serious!

Alan G.

From jeff at ccvcorp.com  Fri Oct 24 17:39:37 2003
From: jeff at ccvcorp.com (Jeff Shannon)
Date: Fri Oct 24 17:35:48 2003
Subject: [Tutor] Multiple exits in a function...
In-Reply-To: <001501c39a73$d2755fd0$6401a8c0@xp>
References: <E1ACi3O-0005Al-MC@mail.python.org>	<3F99370E.10309@cso.atmel.com><005e01c39a51$34554da0$6401a8c0@xp>	<3F996B2B.5080408@ccvcorp.com>
	<001501c39a73$d2755fd0$6401a8c0@xp>
Message-ID: <3F999C19.8000307@ccvcorp.com>

Alan Gauld wrote:

>>I think that it's important to remember that everything involved in
>>programming is a trade-off -- everything has a cost and a benefit.
> 
> Absolutely, and we mneed to understand the trade-offs. In this
> case the trade off is between rapid comprehension and double
> maintenance.

I can agree with that.  :)  In this case I feel that the double 
maintenance is more onerous than the slower comprehension, but it's 
important to be aware of both sides of it.

>>Of course, all of this is just my opinion, and I've had considerably
>>less education in this area than Alan has,
> 
> Hmm, I've just read a lot of books... :-)

Well, you've probably read a lot more books than I have. ;)  I'm a 
relative newcomer to all of this, really...  But, through this thread, 
I've learned a bit more about the principles of structured 
programming, which is a good thing!

> And as I said above i'm much less religious about this issue in
> practice than I am in principle!

Heh.  "Practicality beats purity", and most of us wouldn't be using 
Python if we didn't agree with that to some fair degree.  :)  But it 
is important to understand the pure forms in order to know best how to 
cheat on them for practical purposes.

Jeff Shannon
Technician/Programmer
Credit International



From jerry at j3iss.com  Fri Oct 24 19:54:35 2003
From: jerry at j3iss.com (Jerry Jorgenson)
Date: Fri Oct 24 19:57:00 2003
Subject: [Tutor] Multiple exits in a function...
In-Reply-To: <001a01c39a74$773a5020$6401a8c0@xp>
References: <20031024192845.45987.qmail@web41804.mail.yahoo.com>
	<001a01c39a74$773a5020$6401a8c0@xp>
Message-ID: <20031024185435.5ea1a495.jerry@j3iss.com>

On Fri, 24 Oct 2003 22:19:10 +0100
"Alan Gauld" <alan.gauld@blueyonder.co.uk> wrote:

> When the whole *program* is only 100 lines then the 
> issue is much less serious. But then again the whole 
> need for structure is much less serious!
> 
> Alan G.

Except that the 100 line program of today often becomes the 1000..10000
line program of tomorrow. IMHO it's best to be rigorous--even in small
pieces of code, because you never know.

Jerry

-- 
Jerry Jorgenson
jerry@j3iss.com
http://www.j3iss.com/

From other at stopthesanity.org  Fri Oct 24 21:18:43 2003
From: other at stopthesanity.org (Chris Cioffi)
Date: Fri Oct 24 21:19:02 2003
Subject: [Tutor] Multiple exits in a function...
In-Reply-To: <3F99370E.10309@cso.atmel.com>
References: <E1ACi3O-0005Al-MC@mail.python.org> <3F99370E.10309@cso.atmel.com>
Message-ID: <3F99CF73.1000400@stopthesanity.org>

Um, when a test fails and you need to 'get out of dodge' there are these
things called exceptions.  Python's are rather nice. :)

OTOH, as long as the code is clear I don't think it's _necessarily_ bad
style to use multiple exit points.  My only advise in those cases: Be
Obvious(tm) .  Nothing is worse than wading through a bunch of code only
to find that it is never reached.

Chris

Mike Hansen wrote:

 > I'm curious about this. A co-worker was ranting recently while
 > debugging some C code that it had multiple exits. (BTW: It wasn't my
 > C code. I have never written C code except in college.)
 >
 > I trend to write my functions with multiple exits. Usually when some
 > test fails, I spit a message(email, print it, or write it to a log
 > file) and get out of dodge. The alternative is usually horrible
 > nested If statements even if I flip the logic around. Which to me
 > makes it hard to read and maintain.
 >
 > Can you point me to some resources to help me wrap my mind around
 > this? Code examples? ...
 >
 > Thanks,
 >
 > Mike
 >



From python at dhumketu.cjb.net  Fri Oct 24 15:57:18 2003
From: python at dhumketu.cjb.net (Shantanoo Mahajan)
Date: Sat Oct 25 03:26:16 2003
Subject: [Tutor] Blinking Characters
Message-ID: <20031024195718.GA477@dhumketu.homeunix.net>

Hi Everybody!
Is it possible to have blinking character in window's DOS prompt? In
C/C++ it is called as text attributes, and you can change the
foreground and background colors also along with the blinking
property of the character.

-- 
With Best Regards,
Shantanoo Mahajan

From p.sur at worldnet.att.net  Sat Oct 25 10:38:59 2003
From: p.sur at worldnet.att.net (Partha Sur)
Date: Sat Oct 25 10:34:03 2003
Subject: [Tutor] Blinking Characters
References: <20031024195718.GA477@dhumketu.homeunix.net>
Message-ID: <001401c39b05$bbd44ba0$2248590c@welcome>

Has this anything to do with Python ?

----- Original Message ----- 
From: "Shantanoo Mahajan" <python@dhumketu.cjb.net>
To: <tutor@python.org>
Sent: Friday, October 24, 2003 3:57 PM
Subject: [Tutor] Blinking Characters


> Hi Everybody!
> Is it possible to have blinking character in window's DOS prompt? In
> C/C++ it is called as text attributes, and you can change the
> foreground and background colors also along with the blinking
> property of the character.
> 
> -- 
> With Best Regards,
> Shantanoo Mahajan
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor


From missive at hotmail.com  Sat Oct 25 10:56:35 2003
From: missive at hotmail.com (Lee Harr)
Date: Sat Oct 25 10:56:41 2003
Subject: [Tutor] Re: Blinking Characters
Message-ID: <BAY2-F1194BvRnfvcyS000022b9@hotmail.com>

>Is it possible to have blinking character in window's DOS prompt? In
>C/C++ it is called as text attributes, and you can change the
>foreground and background colors also along with the blinking
>property of the character.


You may want to look at curses:
http://python.org/doc/current/lib/module-curses.html

_________________________________________________________________
Help STOP SPAM with the new MSN 8 and get 2 months FREE*  
http://join.msn.com/?page=features/junkmail


From erikprice at mac.com  Sat Oct 25 12:15:16 2003
From: erikprice at mac.com (Erik Price)
Date: Sat Oct 25 11:52:46 2003
Subject: [Tutor] What is "pythonic"?
In-Reply-To: <Sea2-DAV60i3s1wsXZZ000091dd@hotmail.com>
Message-ID: <6B8EBB1E-0706-11D8-993D-00039351FE6A@mac.com>


On Friday, October 24, 2003, at 03:14  PM, Tom Semple wrote:

> I've seen frequent reference on this list and in other Python 
> resources to the adjective 'pythonic'. For now I am translating 
> "pythonic" as "takes good advantage of the expressive qualities of the 
> Python language".


I noticed that Perl programmers often refer to idiomatic Perl concepts 
as being "canonical [Perl]".  I always thought that "Pythonic" was 
intended to mean the same thing.  Here's the Jargon file's take on the 
term "canonical" in the context of programming, perhaps someone should 
suggest adding "pythonic" to the catalog?

<http://www.catb.org/~esr/jargon/html/C/canonical.html>



Erik


From alan.gauld at blueyonder.co.uk  Sat Oct 25 12:21:59 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Sat Oct 25 12:23:21 2003
Subject: [Tutor] Blinking Characters
References: <20031024195718.GA477@dhumketu.homeunix.net>
Message-ID: <001f01c39b14$1dedf0d0$6401a8c0@xp>

> Is it possible to have blinking character in window's DOS prompt? In
> C/C++ it is called as text attributes, and you can change the
> foreground and background colors also along with the blinking
> property of the character.

Sure the DOS box is a standard ANSI terminal (once you load 
ANSI.SYS).

As a result it responds to all the ANSI comand sequences, 
thus just print the commands for blinking characters to 
stdout and it will respond, same goes for colours, 
character sizes etc.

Try searching the web for "ANSI terminal" and you should find 
what you need, you can test them in a DOS box using the 
DOS "ECHO" command. It used to be common practice pre windows 
to customise your DOS prompt using fancy ANSI sequences.

Alan G.

PS. I found this site:

http://www.termsys.demon.co.uk/vtansi.htm

From bgailer at alum.rpi.edu  Sat Oct 25 12:51:51 2003
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Sat Oct 25 12:54:24 2003
Subject: [Tutor] What is "pythonic"?
In-Reply-To: <6B8EBB1E-0706-11D8-993D-00039351FE6A@mac.com>
References: <Sea2-DAV60i3s1wsXZZ000091dd@hotmail.com>
	<6B8EBB1E-0706-11D8-993D-00039351FE6A@mac.com>
Message-ID: <6.0.0.22.0.20031025104844.028bcac8@66.28.54.253>

Skipped content of type multipart/alternative-------------- next part --------------

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.525 / Virus Database: 322 - Release Date: 10/9/2003
From carroll at tjc.com  Sat Oct 25 13:20:47 2003
From: carroll at tjc.com (Terry Carroll)
Date: Sat Oct 25 13:21:03 2003
Subject: [Tutor] Yet another question on Python and XML
In-Reply-To: <20031021080521.GA4947@sarathi.ncst.ernet.in>
Message-ID: <Pine.LNX.4.44.0310251012230.30863-100000@violet.rahul.net>

On Tue, 21 Oct 2003, Jayprasad J. Hegde wrote:

> You must have seen this question many times: Could you give me pointers
> to some *good* source for studying XML processing--DOM,
> especially--using Python? . . . Pointers to websites rather than books
> would be appreciated.

I don't have any web site pointers, but I highly recommend the book
"Python & XML," by Jones & Drake.  It's an O'Reilly publication.

I see your email address is from India, and I don't know the library 
situation there, but I was able to borrow this from a local library, 
because I was too cheap to purchase a copy (or, put another way, the value 
of this particular book was less to me than the best price I could find).


-- 
Terry Carroll
Santa Clara, CA
carroll@tjc.com 



From python at dhumketu.cjb.net  Sat Oct 25 15:47:05 2003
From: python at dhumketu.cjb.net (Shantanoo Mahajan)
Date: Sat Oct 25 15:47:16 2003
Subject: [Tutor] Re: Blinking Characters
In-Reply-To: <001401c39b05$bbd44ba0$2248590c@welcome>
References: <20031024195718.GA477@dhumketu.homeunix.net>
	<001401c39b05$bbd44ba0$2248590c@welcome>
Message-ID: <20031025194705.GB354@dhumketu.homeunix.net>

+-- Partha Sur [25-10-03 20:08 IST]:
| Has this anything to do with Python ?

	Yes. I want to display warnings/error in *bold* or *blinking*.
	I tried 'import curses' but that is not available on Windows
	:-(. 


| 
| ----- Original Message ----- 
| From: "Shantanoo Mahajan" <python@dhumketu.cjb.net>
| To: <tutor@python.org>
| Sent: Friday, October 24, 2003 3:57 PM
| Subject: [Tutor] Blinking Characters
| 
| 
| > Hi Everybody!
| > Is it possible to have blinking character in window's DOS prompt? In
| > C/C++ it is called as text attributes, and you can change the
| > foreground and background colors also along with the blinking
| > property of the character.
| > 

-- 
With Best Regards,
Shantanoo Mahajan

From python at dhumketu.cjb.net  Sat Oct 25 15:50:52 2003
From: python at dhumketu.cjb.net (Shantanoo Mahajan)
Date: Sat Oct 25 15:51:18 2003
Subject: [Tutor] Re: Blinking Characters
In-Reply-To: <001f01c39b14$1dedf0d0$6401a8c0@xp>
References: <20031024195718.GA477@dhumketu.homeunix.net>
	<001f01c39b14$1dedf0d0$6401a8c0@xp>
Message-ID: <20031025195052.GC354@dhumketu.homeunix.net>

  +-- Alan Gauld [25-10-03 21:51 IST]:
  | > Is it possible to have blinking character in window's DOS prompt? In
  | > C/C++ it is called as text attributes, and you can change the
  | > foreground and background colors also along with the blinking
  | > property of the character.
  | 
  | Sure the DOS box is a standard ANSI terminal (once you load 
  | ANSI.SYS).
  | 
  | As a result it responds to all the ANSI comand sequences, 
  | thus just print the commands for blinking characters to 
  | stdout and it will respond, same goes for colours, 
  | character sizes etc.
  | 
  | Try searching the web for "ANSI terminal" and you should find 
  | what you need, you can test them in a DOS box using the 
  | DOS "ECHO" command. It used to be common practice pre windows 
  | to customise your DOS prompt using fancy ANSI sequences.
  | 
  | Alan G.
  | 
  | PS. I found this site:
  | 
  | http://www.termsys.demon.co.uk/vtansi.htm

I want to have the blininkg/bold msgs. to be printed through python.
Errors/Warning in *blinking*. In FreeBSD, I tried, curses module and
it worked perfectly. But don't know anything on windows. :-( 

-- 
With Best Regards,
Shantanoo Mahajan

From littledanehren at yahoo.com  Sat Oct 25 15:59:09 2003
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Sat Oct 25 15:59:13 2003
Subject: [Tutor] Re: Blinking Characters
In-Reply-To: <20031025195052.GC354@dhumketu.homeunix.net>
Message-ID: <20031025195909.25821.qmail@web41807.mail.yahoo.com>


--- Shantanoo Mahajan <python@dhumketu.cjb.net> wrote:
>   +-- Alan Gauld [25-10-03 21:51 IST]:
>   | > Is it possible to have blinking character in
> window's DOS prompt? In
>   | > C/C++ it is called as text attributes, and you
> can change the
>   | > foreground and background colors also along
> with the blinking
>   | > property of the character.
>   | 
>   | Sure the DOS box is a standard ANSI terminal
> (once you load 
>   | ANSI.SYS).
>   | 
>   | As a result it responds to all the ANSI comand
> sequences, 
>   | thus just print the commands for blinking
> characters to 
>   | stdout and it will respond, same goes for
> colours, 
>   | character sizes etc.
>   | 
>   | Try searching the web for "ANSI terminal" and
> you should find 
>   | what you need, you can test them in a DOS box
> using the 
>   | DOS "ECHO" command. It used to be common
> practice pre windows 
>   | to customise your DOS prompt using fancy ANSI
> sequences.
>   | 
>   | Alan G.
>   | 
>   | PS. I found this site:
>   | 
>   | http://www.termsys.demon.co.uk/vtansi.htm
> 
> I want to have the blininkg/bold msgs. to be printed
> through python.
> Errors/Warning in *blinking*. In FreeBSD, I tried,
> curses module and
> it worked perfectly. But don't know anything on
> windows. :-( 
> 
> -- 
> With Best Regards,
> Shantanoo Mahajan

It looks like Windows doesn't have the curses module,
or atleast 2.3.2-1 doesn't.
Daniel Ehrenberg

__________________________________
Do you Yahoo!?
The New Yahoo! Shopping - with improved product search
http://shopping.yahoo.com

From littledanehren at yahoo.com  Sat Oct 25 16:10:24 2003
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Sat Oct 25 16:10:28 2003
Subject: [Tutor] Optimization
Message-ID: <20031025201024.17875.qmail@web41805.mail.yahoo.com>

I just read GvR's essay about optimization in Python
(at http://python.org/doc/essays/list2str.html), and I
came up with a somewhat efficient algorithm for it. It
was too easy to come up with it and it placed second
in efficiency compared to his other programs (he made
7 algorithms for it). The program converts a list of
numerical ASCII values into a string. The best two he
made (mine did better than one, worse than the other)
imported different modules, but mine didn't have to.
There's recently been some debate about programming
styles, so I'm wondering if I did somehting wrong with
that. Here's the best program, written by GvR:

>>> import array
>>> def f7(list):
...     return array.array('B', list).tostring()

and here's mine:

>>> f8 = lambda list: ''.join(map(chr, list))

On my computer, his was twice as fast as mine, and
mine was in turn twice as fast as the normally
programmed, most obvious one:

>>> def f1(list):
...     string = ""
...     for item in list:
...         string = string + chr(item)
...     return string

My function seemed fairly obvious to me, and it was
better than most of his, so I think there's something
wrong with it that made him not use it. There's
recently been a lot of discussion about which styles
of programming are good and which ones are bad, so is
this a bad style that I used?
Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Exclusive Video Premiere - Britney Spears
http://launch.yahoo.com/promos/britneyspears/

From erikprice at mac.com  Sat Oct 25 16:53:33 2003
From: erikprice at mac.com (Erik Price)
Date: Sat Oct 25 16:31:01 2003
Subject: [Tutor] Re: Request for code critique  ['break' vs control flag]
In-Reply-To: <016001c39922$90589c90$6401a8c0@xp>
Message-ID: <4BC97CEF-072D-11D8-993D-00039351FE6A@mac.com>


On Thursday, October 23, 2003, at 01:00  AM, Alan Gauld wrote:

> I think the issue is that this is NOT a style thing. It's
> one of the basic tenets of structured programming and based
> on actual hard data. Having multiple exit points makes code
> harder to comprehend and hence more prone to error.

Aren't exceptions a kind of exit?

Personally, I think multiple exits are great.  At work I'm responsible 
for maintaining some extremely ugly Java code (it looks more like C 
than Java, taking little advantage of OO), and one of the things I am 
doing is applying refactorings it to make it more readable.  A lot of 
it consists of gigantic methods, hundreds of lines long, which simply 
set various flag variables throughout the body of the method, and then 
analyze the flags at the end of the method to determine what value to 
return or behavior to perform.  Sometimes this is unavoidable, but I 
find it much more readable to use use "Extract Method" refactoring to 
put some large chunk of code into a purposefully-named utility method 
(read: "function"), and return values explicitly from the point in the 
code where the processing can stop -- otherwise the reader has to 
continue to read the code long past the point where the flag is finally 
set, and make sure that it's not being re-set at some point later in 
the code, before it's finally returned.



Erik


From project5 at redrival.net  Sat Oct 25 16:37:23 2003
From: project5 at redrival.net (Andrei)
Date: Sat Oct 25 16:39:39 2003
Subject: [Tutor] Re: Optimization
References: <20031025201024.17875.qmail@web41805.mail.yahoo.com>
Message-ID: <1qjq0qit0zgol.cyt4ws7dzt0e.dlg@40tude.net>

Daniel Ehrenberg wrote on Sat, 25 Oct 2003 13:10:24 -0700 (PDT):

> I just read GvR's essay about optimization in Python
> (at http://python.org/doc/essays/list2str.html), and I
> came up with a somewhat efficient algorithm for it. It
> was too easy to come up with it and it placed second
> in efficiency compared to his other programs (he made
> 7 algorithms for it). The program converts a list of
> numerical ASCII values into a string. The best two he
> made (mine did better than one, worse than the other)
> imported different modules, but mine didn't have to.

That page is pretty old I think. Not sure how old, but it's at least over 2
years, since a translation dated august 2001 is available at
http://home.hanmir.com/~johnsonj/etc/optimization%20anecdote.htm
Things change :). The oldtimers around here should be more capable than I
of judging whether the changes in Python made your solution viable compared
to GvR's.

> There's recently been some debate about programming
> styles, so I'm wondering if I did somehting wrong with
> that. Here's the best program, written by GvR:
> 
>>>> import array
>>>> def f7(list):
> ...     return array.array('B', list).tostring()
> 
> and here's mine:
> 
>>>> f8 = lambda list: ''.join(map(chr, list))

I wouldn't use list (or any other type or built-in) as variable name.

> On my computer, his was twice as fast as mine, and

I like your solution better actually. I don't know the workings of the
array module, but I understand map and lambda. If I had been confronted
with this problem, the array module wouldn't have occured to me.

> mine was in turn twice as fast as the normally
> programmed, most obvious one:
> 
>>>> def f1(list):
> ...     string = ""
> ...     for item in list:
> ...         string = string + chr(item)
> ...     return string

> My function seemed fairly obvious to me, and it was
> better than most of his, so I think there's something
> wrong with it that made him not use it. There's

Well, there are many ways to do it, and nobody can see all of them :). We
must not rule out the possibility that he took some artistic liberties when
he wrote that piece. Plus he doesn't like lambda and map, which are both
featured in the Python Regrets paper:

http://www.google.com/search?q=cache:2QztD1KncJgJ:www.python.org/doc/essays/ppt/regrets/PythonRegrets.ppt+python+regrets&hl=en&ie=UTF-8

> recently been a lot of discussion about which styles
> of programming are good and which ones are bad, so is
> this a bad style that I used?

Not bad IMO - even though I for one tend to choose list comprehensions
rather than map(). 


From sigurd at 12move.de  Sat Oct 25 16:53:19 2003
From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Sat Oct 25 16:56:59 2003
Subject: [Tutor] Optimization
In-Reply-To: <20031025201024.17875.qmail@web41805.mail.yahoo.com> (Daniel
	Ehrenberg's message of "Sat, 25 Oct 2003 13:10:24 -0700 (PDT)")
References: <20031025201024.17875.qmail@web41805.mail.yahoo.com>
Message-ID: <m3smlhqcem.fsf@hamster.pflaesterer.de>

On 25 Oct 2003, Daniel Ehrenberg <- littledanehren@yahoo.com wrote:

> I just read GvR's essay about optimization in Python
> (at http://python.org/doc/essays/list2str.html), and I

I read it after having read your e-mail. It was interesting.

> came up with a somewhat efficient algorithm for it. It

But GvR came up with nearly the same one.

> was too easy to come up with it and it placed second
> in efficiency compared to his other programs (he made
> 7 algorithms for it). The program converts a list of

Funktion 6 is the same as yours.
,----[ f6; Python Patterns - An Optimization Anecdote ]
|  import string
|     def f6(list):
|         return string.joinfields(map(chr, list), "")
`----

The only difference is he uses the strinfg module.  I think the time the
essay was written the `join' method of strings didn't exist.  The string
module was the only possibility.

> numerical ASCII values into a string. The best two he
> made (mine did better than one, worse than the other)
> imported different modules, but mine didn't have to.

The reason is written above.  The time the essay had been written you
also would have to import the string module.

> There's recently been some debate about programming
> styles, so I'm wondering if I did somehting wrong with
> that. Here's the best program, written by GvR:

>>>> import array
>>>> def f7(list):
> ...     return array.array('B', list).tostring()

> and here's mine:

>>>> f8 = lambda list: ''.join(map(chr, list))

As I wrote yours f8 is nearly the same as GvR's f6.  Furthermore you
cheat a bit; you don't give a name to you function but use just a
lambda.  That can be a bit faster.  f6 written with the join method of
strings instead of the function from the strings module should behave
like your function.

> On my computer, his was twice as fast as mine, and
> mine was in turn twice as fast as the normally
> programmed, most obvious one:

>>>> def f1(list):
> ...     string = ""
> ...     for item in list:
> ...         string = string + chr(item)
> ...     return string

I don't know for whom that would be the most obvious one; for me not.
The mapping solution seems more obvious if you know a bit functional
programming.

> My function seemed fairly obvious to me, and it was
> better than most of his, so I think there's something
> wrong with it that made him not use it. There's

No there isn't.  In fact he did use it as I showed you above.

Furthermore your solution uses lambda; it is well known that Guido is
not the gretaest friend on earth of lambda.

> of programming are good and which ones are bad, so is
> this a bad style that I used?

IMO not.

*But*: do not use *list* as a parameter.  It is a builtin.

If you prefer functional or imperative style or a mixture; that's up to
you.  Just use the same style in one programm and don't shadow builtins
unless you know why you do it.


   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


From littledanehren at yahoo.com  Sat Oct 25 17:14:23 2003
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Sat Oct 25 17:14:30 2003
Subject: [Tutor] Optimization
In-Reply-To: <m3smlhqcem.fsf@hamster.pflaesterer.de>
Message-ID: <20031025211423.59465.qmail@web41801.mail.yahoo.com>

--- Karl Pflästerer <sigurd @ 12move.de> wrote:
> *But*: do not use *list* as a parameter.  It is a
> builtin.
>    Karl

Where could I find a list of builtins?

__________________________________
Do you Yahoo!?
Exclusive Video Premiere - Britney Spears
http://launch.yahoo.com/promos/britneyspears/

From tbrauch at mindless.com  Sat Oct 25 17:23:55 2003
From: tbrauch at mindless.com (Timothy M. Brauch)
Date: Sat Oct 25 17:23:17 2003
Subject: [Tutor] Optimization
References: <20031025211423.59465.qmail@web41801.mail.yahoo.com>
Message-ID: <009b01c39b3e$4bb92b90$6600a8c0@winxp>

From: "Daniel Ehrenberg" <littledanehren@yahoo.com>
> --- Karl Pfl?sterer <sigurd @ 12move.de> wrote:
> > *But*: do not use *list* as a parameter.  It is a
> > builtin.
> >    Karl
>
> Where could I find a list of builtins?

Here are a couple of places to start looking

Built-In Functions (probably what you are most concerned with):
http://www.python.org/doc/current/lib/built-in-funcs.html

All Built-in Objects (nice to be away of):
http://www.python.org/doc/current/lib/builtin.html

And the default Built-In Modules:
http://www.python.org/doc/current/modindex.html

You can also use
>>dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError',
'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError',
'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'IOError',
'ImportError', 'IndentationError', 'IndexError', 'KeyError',
'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None',
'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError',
'OverflowWarning', 'PendingDeprecationWarning', 'ReferenceError',
'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration',
'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError',
'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError',
'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError',
'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError',
'_', '__debug__', '__doc__', '__import__', '__name__', 'abs', 'apply',
'basestring', 'bool', 'buffer', 'callable', 'chr', 'classmethod', 'cmp',
'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict',
'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter',
'float', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id',
'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len',
'license', 'list', 'locals', 'long', 'map', 'max', 'min', 'object', 'oct',
'open', 'ord', 'pow', 'property', 'quit', 'range', 'raw_input', 'reduce',
'reload', 'repr', 'round', 'setattr', 'slice', 'staticmethod', 'str', 'sum',
'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']

For those times you just want a quick list of what is built-in.  To find out
what something does, try something like
>>> print __builtins__.list.__doc__
list() -> new list
list(sequence) -> new list initialized from sequence's items
>>> print __builtins__.max.__doc__
max(sequence) -> value
max(a, b, c, ...) -> value

With a single sequence argument, return its largest item.
With two or more arguments, return the largest argument.

Just note, there are **two** underscores:
_ _ b u i l t i n s _ _
_ _ d o c _ _

dir() and __doc__ should be your friends.  And keep them in mind when
writing your own code.

 - Tim



---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.530 / Virus Database: 325 - Release Date: 10/23/2003


From project5 at redrival.net  Sat Oct 25 17:21:34 2003
From: project5 at redrival.net (Andrei)
Date: Sat Oct 25 17:23:48 2003
Subject: [Tutor] Re: Optimization
References: <m3smlhqcem.fsf@hamster.pflaesterer.de>
	<20031025211423.59465.qmail@web41801.mail.yahoo.com>
Message-ID: <1hur3bfg061me$.1jm24lsx3sx49.dlg@40tude.net>

Daniel Ehrenberg wrote on Sat, 25 Oct 2003 14:14:23 -0700 (PDT):

> --- Karl Pfl?sterer <sigurd @ 12move.de> wrote:
>> *But*: do not use *list* as a parameter.  It is a
>> builtin.
>>    Karl
> 
> Where could I find a list of builtins?
> 

dir(__builtins__)

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V
ernq gur yvfg, fb gurer'f ab arrq gb PP.


From alan.gauld at blueyonder.co.uk  Sat Oct 25 19:45:33 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Sat Oct 25 19:46:51 2003
Subject: [Tutor] Re: Request for code critique  ['break' vs control flag]
References: <4BC97CEF-072D-11D8-993D-00039351FE6A@mac.com>
Message-ID: <005701c39b52$14ba19b0$6401a8c0@xp>

> > on actual hard data. Having multiple exit points makes code
> > harder to comprehend and hence more prone to error.
>
> Aren't exceptions a kind of exit?

Yes, but by definition not part of the normal program flow.
The try/except mechanism is a way to remove multiple exits
from a block.

try
   [ code block with 'happy path']
except
   [ all the exceptions that would have broken up the block]

So in terms of legibility the core code block is made easier
to read because the exception handling has been moved outside.

The alternative is:

[ some code here]
if <exception>
   [handle it]
   [exit block]
[more happy path code]
if <another exception>
   [handle it]
   [exit block]
[more happy path]


I think most folks find the try/except style easier to comprehend,
precisely because it doesn't break up the main block of code.

One of the valid reasons for using break/continue (and the original
reason for them being in C) is to do exception processing within
loops, the only alternatives are maintaining multiple error flags
or using GOTO... In that case break is better. But it is, quite
literally, the exception and not the rule.

> Personally, I think multiple exits are great.  At work I'm
responsible
> for maintaining some extremely ugly Java code (it looks more like C
> than Java, taking little advantage of OO), and one of the things I
am
> doing is applying refactorings it to make it more readable.

> find it much more readable to use use "Extract Method" refactoring
to
> put some large chunk of code into a purposefully-named utility
method
> (read: "function"), and return values explicitly from the point in
the
> code where the processing can stop -- otherwise the reader has to
> continue to read the code long past the point where the flag is
finally
> set, and make sure that it's not being re-set at some point later in
> the code, before it's finally returned.

Refactoring is generally a good thing and has been recommended
long before it was called refactoring...

However even here some intelligence must be applied. For example
if a function is written to handle a long and complex data structure
it is tempting to break it into chunks, each chunk handling a
section of the structure. Often this works. But if the manipulation
of one part relies on values set in an earlier part then the values
have to be passed into the sub functions creating a dangerous
degree of coupling that may cause problems in the future.

For example, one of the biggest functions I ever saw was
about 300 lines long, but it made no sense to break it up
(refactorig it) because it was processing a data structure which
itself was over 100 lines long(this was in C). And because
there was no real repetition within the structure and there were
many internal dependencies in the values. To refactor it
would have led to a maintenance nightmare.

The usual rule applies: the structure of the data should determine
the structure of the code!

As I said in an earlier post, we live in an imperfect world
and purity must often be sacrificed for prgmatism. But the
compromises chosen should be based on a clear understanding
of the impacts, both positive and negative.

Alan G.


From littledanehren at yahoo.com  Sat Oct 25 23:48:56 2003
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Sat Oct 25 23:49:00 2003
Subject: [Tutor] Text processing with files
Message-ID: <20031026034856.21540.qmail@web41804.mail.yahoo.com>

I'm trying to make a program to convert any text
document into one with he native type of newline. I
wrote a script but all it did was blank the file. It
is posted below.

from os import linesep
filepath = raw_input("Convert which file? ")
fileread = file(filepath, "r")
filewrite = file(filepath, "w")
text = fileread.read()
fileread.close()
fixedtext = text.replace('\n', linesep)
filewrite.write(fixedtext)
filewrite.close()

What's wrong with it?
Daniel Ehrenberg

__________________________________
Do you Yahoo!?
The New Yahoo! Shopping - with improved product search
http://shopping.yahoo.com

From intatia at paradise.net.nz  Sun Oct 26 00:09:04 2003
From: intatia at paradise.net.nz (Intatia)
Date: Sun Oct 26 00:09:24 2003
Subject: [Tutor] Text processing with files
In-Reply-To: <20031026034856.21540.qmail@web41804.mail.yahoo.com>
References: <20031026034856.21540.qmail@web41804.mail.yahoo.com>
Message-ID: <3F9B48E0.2050004@paradise.net.nz>

Here's my pathetic attempt with what little I know...:)

from os import linesep
filepath = raw_input("Convert which file? ")
fileread = open(filepath, "r")
text = fileread.readlines()
fileread.close()
fixedtext = []
for line in text:
         fixedtext.append(line.replace('\n', linesep))
filewrite = open(filepath, "w")
filewrite.writelines(fixedtext)
filewrite.close()

Seems to work, or at least, the file keeps it's contents *g*

It's probably a matter of style, but I prefer to keep 
opening/(reading/writing)/closing a file all together where possible for easier 
reading.

Daniel Ehrenberg wrote:
> I'm trying to make a program to convert any text
> document into one with he native type of newline. I
> wrote a script but all it did was blank the file. It
> is posted below.
> 
> from os import linesep
> filepath = raw_input("Convert which file? ")
> fileread = file(filepath, "r")
> filewrite = file(filepath, "w")
> text = fileread.read()
> fileread.close()
> fixedtext = text.replace('\n', linesep)
> filewrite.write(fixedtext)
> filewrite.close()
> 
> What's wrong with it?
> Daniel Ehrenberg
> 
> __________________________________
> Do you Yahoo!?
> The New Yahoo! Shopping - with improved product search
> http://shopping.yahoo.com
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


From jjhegde at ncst.ernet.in  Sun Oct 26 03:27:08 2003
From: jjhegde at ncst.ernet.in (Jayprasad J. Hegde)
Date: Sun Oct 26 03:26:34 2003
Subject: [Tutor] Yet another question on Python and XML
In-Reply-To: <Pine.LNX.4.44.0310251012230.30863-100000@violet.rahul.net>
References: <20031021080521.GA4947@sarathi.ncst.ernet.in>
	<Pine.LNX.4.44.0310251012230.30863-100000@violet.rahul.net>
Message-ID: <20031026082708.GB1660@sarathi.ncst.ernet.in>

On Sat, Oct 25, 2003 at 10:20:47AM -0700, Terry Carroll wrote:
[ snip ] 

> I don't have any web site pointers, but I highly recommend the book
> "Python & XML," by Jones & Drake.  It's an O'Reilly publication.
> I see your email address is from India, and I don't know the library 
> situation there, but I was able to borrow this from a local library, 
> because I was too cheap to purchase a copy (or, put another way, the value 
> of this particular book was less to me than the best price I could find).

My company has a decent library of its own. Unfortunately, it does not
have many useful books on Python; "Python and XML" being one of them.

I came to know about this book only recently. 
I am currently going through it online using O'Reilly's "Safari". The
"preview" mode that it offers is no good, and in all likelihood, I
might end up subscribing and reading it online.

Thanks for the suggestion anyway. 

Regards, 
- JJH
-- 
[ Jayprasad J. Hegde, http://staff.ncst.ernet.in/1/1/jjhegde/ ]
Hartley's First Law:
	You can lead a horse to water, but if you can get him to float
	on his back, you've got something.

From alan.gauld at blueyonder.co.uk  Sun Oct 26 03:36:32 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Sun Oct 26 03:37:41 2003
Subject: [Tutor] Re: Blinking Characters
References: <20031024195718.GA477@dhumketu.homeunix.net>
	<001f01c39b14$1dedf0d0$6401a8c0@xp>
	<20031025195052.GC354@dhumketu.homeunix.net>
Message-ID: <006201c39b9c$4222b480$6401a8c0@xp>

Ok, I did a bit more digging...

>   | Sure the DOS box is a standard ANSI terminal (once you load 
>   | ANSI.SYS).

Apparently only works with a DOS 5.0 DOS box, the NT/XP CMD box 
doesn't do ANSI... :-(

Full details in MS Knowlege Base article KB100394

>   | Try searching the Windows Help for for "ANSI.SYS

And you get several KB articles including the supported codes.

However unless you have DOS 5 on board they won't help, sorry.

There is a version of curses for DOS but its not part of 
official python, and of course you get curses with cygwin
and its version of ppython.

Alan G.

From project5 at redrival.net  Sun Oct 26 05:45:59 2003
From: project5 at redrival.net (Andrei)
Date: Sun Oct 26 05:48:15 2003
Subject: [Tutor] Re: Text processing with files
References: <20031026034856.21540.qmail@web41804.mail.yahoo.com>
Message-ID: <16gvopux83fap.6pt0ps036q2w$.dlg@40tude.net>

Daniel Ehrenberg wrote on Sat, 25 Oct 2003 20:48:56 -0700 (PDT):

> I'm trying to make a program to convert any text
> document into one with he native type of newline. I
> wrote a script but all it did was blank the file. It
> is posted below.
> 
> from os import linesep

Note that this is the line separator on the current platform.

> filepath = raw_input("Convert which file? ")
> fileread = file(filepath, "r")
> filewrite = file(filepath, "w")

You're opening the same file both for reading and writing at the same time.
That can't be good :). First open, read and close, then open, write and
close. BTW, I think that it's enough to open the file with the flag "rU"
(starting with Python 2.3), which opens the file with universal newline
support, read it and then write it back. All line endings are during
reading automatically converted to "\n", which, when writing, is
automatically set to the platform's default if I'm not mistaken.


-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V
ernq gur yvfg, fb gurer'f ab arrq gb PP.


From erikprice at mac.com  Sun Oct 26 07:15:49 2003
From: erikprice at mac.com (Erik Price)
Date: Sun Oct 26 06:53:14 2003
Subject: [Tutor] Text processing with files
In-Reply-To: <20031026034856.21540.qmail@web41804.mail.yahoo.com>
Message-ID: <22940524-07AE-11D8-993D-00039351FE6A@mac.com>


On Saturday, October 25, 2003, at 11:48  PM, Daniel Ehrenberg wrote:

> I
> wrote a script but all it did was blank the file. It
> is posted below.
>
> from os import linesep
> filepath = raw_input("Convert which file? ")
> fileread = file(filepath, "r")
> filewrite = file(filepath, "w")
> text = fileread.read()
> fileread.close()
> fixedtext = text.replace('\n', linesep)
> filewrite.write(fixedtext)
> filewrite.close()
>
> What's wrong with it?

When you open a file for writing using file(filepathe, 'w'), Python 
wipes out the contents of the file.  You're doing this before you 
actually read through the file and store its contents into the "text" 
variable.  So, if you simply move your line "filewrite = file(filepath, 
'w')" line down below "fileread.close()" you should be fine.

In other words, close the file from reading before opening it for 
writing.


Erik


From david at graniteweb.com  Sun Oct 26 13:04:48 2003
From: david at graniteweb.com (David Rock)
Date: Sun Oct 26 13:04:52 2003
Subject: [Tutor] Text processing with files
In-Reply-To: <22940524-07AE-11D8-993D-00039351FE6A@mac.com>
References: <20031026034856.21540.qmail@web41804.mail.yahoo.com>
	<22940524-07AE-11D8-993D-00039351FE6A@mac.com>
Message-ID: <20031026180448.GB12603@wdfs.graniteweb.com>

* Erik Price <erikprice@mac.com> [2003-10-26 07:15]:
> 
> On Saturday, October 25, 2003, at 11:48  PM, Daniel Ehrenberg wrote:
> 
> >I
> >wrote a script but all it did was blank the file. It
> >is posted below.
> >
> >from os import linesep
> >filepath = raw_input("Convert which file? ")
> >fileread = file(filepath, "r")
> >filewrite = file(filepath, "w")
> >text = fileread.read()
> >fileread.close()
> >fixedtext = text.replace('\n', linesep)
> >filewrite.write(fixedtext)
> >filewrite.close()
> >
> >What's wrong with it?
> 
> When you open a file for writing using file(filepathe, 'w'), Python 
> wipes out the contents of the file.  You're doing this before you 
> actually read through the file and store its contents into the "text" 
> variable.  So, if you simply move your line "filewrite = file(filepath, 
> 'w')" line down below "fileread.close()" you should be fine.
> 
> In other words, close the file from reading before opening it for 
> writing.

You may also want to look into the Module fileinput. It is an iterator
for input streams (including files). One nice thing it has is the
ability to make changes inplace, similar to perl's -i option.

http://www.python.org/doc/current/lib/module-fileinput.html

-- 
David Rock
david@graniteweb.com
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20031026/a424f07f/attachment.bin
From littledanehren at yahoo.com  Sun Oct 26 13:48:10 2003
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Sun Oct 26 13:48:14 2003
Subject: [Tutor] Re: Text processing with files
In-Reply-To: <16gvopux83fap.6pt0ps036q2w$.dlg@40tude.net>
Message-ID: <20031026184810.18597.qmail@web41813.mail.yahoo.com>


--- Andrei <project5@redrival.net> wrote:
> Daniel Ehrenberg wrote on Sat, 25 Oct 2003 20:48:56
> -0700 (PDT):
> 
> > I'm trying to make a program to convert any text
> > document into one with he native type of newline.
> I
> > wrote a script but all it did was blank the file.
> It
> > is posted below.
> > 
> > from os import linesep
> 
> Note that this is the line separator on the current
> platform.
> 
> > filepath = raw_input("Convert which file? ")
> > fileread = file(filepath, "r")
> > filewrite = file(filepath, "w")
> 
> You're opening the same file both for reading and
> writing at the same time.
> That can't be good :). First open, read and close,
> then open, write and
> close. BTW, I think that it's enough to open the
> file with the flag "rU"
> (starting with Python 2.3), which opens the file
> with universal newline
> support, read it and then write it back. All line
> endings are during
> reading automatically converted to "\n", which, when
> writing, is
> automatically set to the platform's default if I'm
> not mistaken.
> 
> 
> -- 
> Yours,
> 
> Andrei

So would this be better?

filepath = raw_input("Convert which file? ")
filetext = file(filepath, "rU").read()
file(filepath, "w").write(filetext)

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Exclusive Video Premiere - Britney Spears
http://launch.yahoo.com/promos/britneyspears/

From Harm_Kirchhoff at mail.digital.co.jp  Sun Oct 26 19:46:27 2003
From: Harm_Kirchhoff at mail.digital.co.jp (Harm_Kirchhoff@mail.digital.co.jp)
Date: Sun Oct 26 20:15:22 2003
Subject: [Tutor] Basics of Classes
Message-ID: <OF82EF963F.BEDA9294-ON49256DCC.0001F69B-49256DCC.000422EE@jp.schneider-electric.com>

First of all, thanks for the feedback on my last question, the responses 
helped me to make good progress in understanding python.

Over the weekend I read through Mark Lutz & David Asher's Learning Python 
and started fumbling with classes. (I come from M/MUMPS which is an old 
language and does not know the concept of OOP or classes.)

I copied their example o p. 166 and ... got an error:

>>> class harm:
        def __getitem__(self, index):
                return index ** 2

 
>>> a3=harm
>>> print a3 [2]
Traceback (most recent call last):
  File "<pyshell#41>", line 1, in ?
    print a3 [2]
TypeError: unsubscriptable object
>>> 

I would like to write a class, that handles the in/output to my ZODB (I am 
not that far yet, but its the goal).
Ideally I would like to have an instance to which I can assign data as if 
it were a multidimensional db:

Sales [2003] ['Jan'] ['Cape Verde'] = (Quantity, Turnover)

All the rest (input validation, storage, ...) should be handled by the 
instance.

Any idea why my instance is 'unsubscriptable' ?

From amk at amk.ca  Sun Oct 26 20:57:03 2003
From: amk at amk.ca (amk@amk.ca)
Date: Sun Oct 26 20:57:30 2003
Subject: [Tutor] Basics of Classes
In-Reply-To: <OF82EF963F.BEDA9294-ON49256DCC.0001F69B-49256DCC.000422EE@jp.schneider-electric.com>
References: <OF82EF963F.BEDA9294-ON49256DCC.0001F69B-49256DCC.000422EE@jp.schneider-electric.com>
Message-ID: <20031027015703.GA26350@rogue.amk.ca>

On Mon, Oct 27, 2003 at 09:46:27AM +0900, Harm_Kirchhoff@mail.digital.co.jp wrote:
> >>> class harm:
>         def __getitem__(self, index):
>                 return index ** 2
> >>> a3=harm
> >>> print a3 [2]

You haven't created an instance, only bound the name 'a3' to a class object 
that's also bound to the name 'harm'.  Try 'a3=harm()' to make an instance
of the class.

Two useful tutorials on how to think about Python objects (not necessarily
just classes):
    http://starship.python.net/crew/mwh/hacks/objectthink.html
    http://effbot.org/guides/python-objects.htm

--amk

From klhjhm at hotmail.com  Sun Oct 26 23:31:14 2003
From: klhjhm at hotmail.com (kamariah lamim)
Date: Sun Oct 26 23:31:20 2003
Subject: [Tutor] (no subject)
Message-ID: <BAY1-F76vJZkPqkap7p0000213f@hotmail.com>

Hi ;
   i want to call and execute  other programs parallely from python.is that 
possible.?what tools do i need?

_________________________________________________________________
Download the latest MSN Messenger http://messenger.msn.com.my


From david at graniteweb.com  Mon Oct 27 00:20:48 2003
From: david at graniteweb.com (David Rock)
Date: Mon Oct 27 00:20:53 2003
Subject: [Tutor] (no subject)
In-Reply-To: <BAY1-F76vJZkPqkap7p0000213f@hotmail.com>
References: <BAY1-F76vJZkPqkap7p0000213f@hotmail.com>
Message-ID: <20031027052048.GA14473@wdfs.graniteweb.com>

* kamariah lamim <klhjhm@hotmail.com> [2003-10-27 12:31]:
> Hi ;
>   i want to call and execute  other programs parallely from python.is that 
> possible.?what tools do i need?

What type of programs and what do you mean by "Parallely"? You can use
os.fork or many of its variants to start child processes. What else are
you looking for?

-- 
David Rock
david@graniteweb.com
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20031026/415b44ee/attachment.bin
From klhjhm at hotmail.com  Mon Oct 27 00:41:22 2003
From: klhjhm at hotmail.com (kamariah lamim)
Date: Mon Oct 27 00:41:29 2003
Subject: [Tutor] running process in parallel
Message-ID: <BAY1-F12pqpEq8hZYNX00009e20@hotmail.com>

I want to run some script files in different directory all at a time that is 
running process in parallel .Is it possible?

* kamariah lamim <klhjhm@hotmail.com> [2003-10-27 12:31]:
>Hi ;
>   i want to call and execute  other programs parallely from python.is that 
>possible.?what tools do i need?

What type of programs and what do you mean by "Parallely"? You can use
os.fork or many of its variants to start child processes. What else are
you looking for?

--
David Rock
david@graniteweb.com

_________________________________________________________________
Are you in love? Find a date on MSN Personals http://match.msn.com.my/


From op73418 at mail.telepac.pt  Mon Oct 27 05:01:52 2003
From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=)
Date: Mon Oct 27 05:00:26 2003
Subject: [Tutor] Re: Text processing with files
In-Reply-To: <20031026184810.18597.qmail@web41813.mail.yahoo.com>
References: <16gvopux83fap.6pt0ps036q2w$.dlg@40tude.net>
	<20031026184810.18597.qmail@web41813.mail.yahoo.com>
Message-ID: <ijpppv81iab6tpv3r2tsnfgl1ko31v18av@4ax.com>

On Sun, 26 Oct 2003 10:48:10 -0800 (PST), Daniel Ehrenberg wrote:

>
>So would this be better?
>
>filepath = raw_input("Convert which file? ")
>filetext = file(filepath, "rU").read()
>file(filepath, "w").write(filetext)
>

Just a note: files are external resources, so it is a good programming
habit of disposing them explicitely.

A very common and pythonic pattern of dealing with external and
limited resources is

<open resource for use>
try:
    <use resource>
finally:
    <close resource>

In the case of files, this becomes

path = raw_input("Which file to open?")
#Open file.
f = file(path, "rU")
try:
    #Read file.
    text = f.read()
finally:
    #Close file.
    f.close()

The magic is the try/finally block. When Python encounters this, it
will execute the try block and then if no exceptions have been raised
the finally block is executed and everything goes on as normal. OTOH
if teh try block raises an exception, the finally block is executed
and only after is the exception raised. What this guarantees is that
the finally block is *always* executed - which is exactly what you
need when freeing resources (closing files, closing database
connections, releasing locks, etc.)

Now in your case, you only want to write to the file *if* the read
operation went fine, so a *robust* version goes like this:

path = raw_input("Which file to open?")
#Open file.
try:
    f = file(path, "rU")
    try:
        #Read file.
        text = f.read()
    finally:
        #Close file.
        f.close()
except:
    #Reraise exception => an error has ocurred.
    raise
else:
    #Open file for writing.
    f = file(path, "w")
    try:
        #Write to file.
        f.write(text)
    finally:
        #Close file.
        f.close()

Admittedly, the above is a little hairy, but it stays as a good
exercise in using exceptions and try/finally blocks to write robust
code.

A final note on your code:

>filetext = file(filepath, "rU").read()
>file(filepath, "w").write(filetext)

In going from the reading to the writing you are assuming that Python
closes the file in between. And you assum right, because Python makes
sure that when a file is garbage collected is closed. And that is what
happens above since by the time you get to the writing statement there
are no references to the file, so it is garbage collected, etc... BUT,
and this is a big but (only one t), this is an *implementation
detail*. It happens in the current CPython implementation but it is
not guaranteed to happen in future implementations. It is *not* true
in the Jython implementation, where the underlying Java VM takes care
of garbage collection. In Java, garbage collection can be defered
indefinitely (actually in CPython also, in the presence of cycles, but
that's another story) so it is *not* guaranteed that the file is
closed by the time you get to the write statement.

Any other question just holler, best regards,
G. Rodrigues

From mhansen at cso.atmel.com  Mon Oct 27 10:19:56 2003
From: mhansen at cso.atmel.com (Mike Hansen)
Date: Mon Oct 27 10:17:15 2003
Subject: [Tutor] Yet another question on Python and XML
In-Reply-To: <E1ADVTU-0005Wv-WD@mail.python.org>
References: <E1ADVTU-0005Wv-WD@mail.python.org>
Message-ID: <3F9D379C.1080007@cso.atmel.com>


> Subject:
> Re: [Tutor] Yet another question on Python and XML
> From:
> Terry Carroll <carroll@tjc.com>
> Date:
> Sat, 25 Oct 2003 10:20:47 -0700 (PDT)
> To:
> tutor@python.org
>
>
>On Tue, 21 Oct 2003, Jayprasad J. Hegde wrote:
>
>  
>
>>You must have seen this question many times: Could you give me pointers
>>to some *good* source for studying XML processing--DOM,
>>especially--using Python? . . . Pointers to websites rather than books
>>would be appreciated.
>>    
>>
>
>I don't have any web site pointers, but I highly recommend the book
>"Python & XML," by Jones & Drake.  It's an O'Reilly publication.
>
>I see your email address is from India, and I don't know the library 
>situation there, but I was able to borrow this from a local library, 
>because I was too cheap to purchase a copy (or, put another way, the value 
>of this particular book was less to me than the best price I could find).
>
>  
>
>  
>
Amazing! My local library's computer/tech/programming books are 
pathetic. 99% of the books are 5+ years old. VB3, Turbo Pascal, Windows 
95, Perl 4... you get the picture.

The XML how to is a good starting point...

http://pyxml.sourceforge.net/topics/howto/xml-howto.html

I just stumbled on to this site...

http://uche.ogbuji.net/tech/akara/nodes/2003-01-01/pyxml-akara

A XML Tutorial that was used in a presentation at Europython 2002

http://www.logilab.org/static/XMLTutorial/

I actually had better luck using SAX than DOM, but it depends on the 
complexity of the XML document and what you are trying to do with it. 
The XML docs that I was parsing with SAX were simple i.e. not too deep 
in the nesting.

Mike


From mhansen at cso.atmel.com  Mon Oct 27 10:38:28 2003
From: mhansen at cso.atmel.com (Mike Hansen)
Date: Mon Oct 27 10:38:55 2003
Subject: [Tutor] Re: Tutor Digest, Vol 3, Issue 51
In-Reply-To: <E1ADoKS-0002Ae-FW@mail.python.org>
References: <E1ADoKS-0002Ae-FW@mail.python.org>
Message-ID: <3F9D3BF4.4020008@cso.atmel.com>


>
> Subject:
> Re: [Tutor] Yet another question on Python and XML
> From:
> "Jayprasad J. Hegde" <jjhegde@ncst.ernet.in>
> Date:
> Sun, 26 Oct 2003 13:57:08 +0530
> To:
> tutor@python.org
>
>
>On Sat, Oct 25, 2003 at 10:20:47AM -0700, Terry Carroll wrote:
>[ snip ] 
>
>  
>
>>I don't have any web site pointers, but I highly recommend the book
>>"Python & XML," by Jones & Drake.  It's an O'Reilly publication.
>>I see your email address is from India, and I don't know the library 
>>situation there, but I was able to borrow this from a local library, 
>>because I was too cheap to purchase a copy (or, put another way, the value 
>>of this particular book was less to me than the best price I could find).
>>    
>>
>
>My company has a decent library of its own. Unfortunately, it does not
>have many useful books on Python; "Python and XML" being one of them.
>
>I came to know about this book only recently. 
>I am currently going through it online using O'Reilly's "Safari". The
>"preview" mode that it offers is no good, and in all likelihood, I
>might end up subscribing and reading it online.
>
>Thanks for the suggestion anyway. 
>
>Regards, 
>- JJH
>  
>
>
I'll 2nd the recommendation for "Python & XML". It gives enough 
information to get the ball rolling.

I signed up for Safari early this year. I've read several books and huge 
chunks of many others. It's saved me a bundle on tech books.

Mike


From VICKI.STANFIELD at ROCHE.COM  Mon Oct 27 10:34:27 2003
From: VICKI.STANFIELD at ROCHE.COM (Stanfield, Vicki {D167~Indianapolis})
Date: Mon Oct 27 11:18:54 2003
Subject: [Tutor] reiterative programming
Message-ID: <CA3458C84C976E45B6372A6C14724C9F355E90@ridmsem02.nala.roche.com>

I am trying to replace several calls to the same function with a loop, and for some reason I am not getting it right. The calls all read from a serial port and convert the received value like this:

	output=port.read()
            returnedval= hex(ord(output))

I want to loop through doing this until the returned value is a hex 4. I am using this:

	while returnedval != '\0x4':
                output=port.read()
                returnedval= hex(ord(output))

For some reason that I don't understand, when the returnedval is '0x4', it does the loop again and spits out an error for trying to convert a string of length 0 using the ord function. 

Do you see what I am doing wrong?

--vicki 

Best Regards,
--vicki stanfield


From nas-pytut at python.ca  Mon Oct 27 13:05:57 2003
From: nas-pytut at python.ca (Neil Schemenauer)
Date: Mon Oct 27 13:05:25 2003
Subject: [Tutor] reiterative programming
In-Reply-To: <CA3458C84C976E45B6372A6C14724C9F355E90@ridmsem02.nala.roche.com>
References: <CA3458C84C976E45B6372A6C14724C9F355E90@ridmsem02.nala.roche.com>
Message-ID: <20031027180557.GB21046@mems-exchange.org>

On Mon, Oct 27, 2003 at 10:34:27AM -0500, Stanfield, Vicki wrote:
> I want to loop through doing this until the returned value is a
> hex 4. I am using this:
> 
> 	while returnedval != '\0x4':
>                 output=port.read()
>                 returnedval= hex(ord(output))


You want '0x4', not '\0x4'.  The former is a string consisting of
the characters '0', 'x', and '4'.  The later is a string of the
characters NUL, 'x', '4'.  Personally, I would write the loop like
this:

    while 1:
        c = port.read(1)
        if c == '\x04':
            break

(although I'm guessing at what you are trying to do).

  Neil

From alan.gauld at blueyonder.co.uk  Mon Oct 27 13:35:59 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Mon Oct 27 13:44:57 2003
Subject: [Tutor] running process in parallel
References: <BAY1-F12pqpEq8hZYNX00009e20@hotmail.com>
Message-ID: <004d01c39cb9$2ae4b3e0$6401a8c0@xp>


> I want to run some script files in different directory all at a time
that is
> running process in parallel .Is it possible?

Assuming these are all Python scripts(?) and that they have
an API that you can call then you could use threads to
execute the different functions. OTOH if they are plain
python programs that you want to run in parallel (each in
its own Python interpreter) then you need to use a combination
of threads and os.system(or os.popen). The same applies if
they are written is some other language, but you will need
to form up the command string to include the interpreter
and script file name before passing it to os.system.

If thats not what you mean then you will ned to give us a
more explicit example.

Alan G.


From alan.gauld at blueyonder.co.uk  Mon Oct 27 13:51:49 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Mon Oct 27 13:52:45 2003
Subject: [Tutor] reiterative programming
References: <CA3458C84C976E45B6372A6C14724C9F355E90@ridmsem02.nala.roche.com>
Message-ID: <005401c39cbb$6125a3e0$6401a8c0@xp>

I'm not sure I understand the logic of the conversion.

hex(ord(c))

takes the character c, converts it to a number equal
to its ASCII value and then turns that number into a
hex representation. (Try it in the interpreter:

>>> print ord('4')
52
>>> print hex(ord(4))
0x34

Are you sure you don't want the hex representation of
the number the character represents

>>> print hex(int('4'))
0x4

Or even

>>> print int('4',16)
4

> I want to loop through doing this until the returned value is a hex
4.
>
> while returnedval != '\0x4':

This checks for the string '\0x4' which treats the \ as an escape
and yields:.

>>> print '\0x4'
 x4

You could use a raw string:

>>> print r'\0x4'
\0x4

> For some reason that I don't understand, when the returnedval
> is '0x4', it does the loop again

Because '0x4' is not the same as '\0x4'!

You need to be very clear about what you actually want to compare
with what, and then check the actual format you are using.
The >>> prompt is your friend.

Alan G.



From VICKI.STANFIELD at ROCHE.COM  Mon Oct 27 13:59:51 2003
From: VICKI.STANFIELD at ROCHE.COM (Stanfield, Vicki {D167~Indianapolis})
Date: Mon Oct 27 14:06:49 2003
Subject: [Tutor] reiterative programming
Message-ID: <CA3458C84C976E45B6372A6C14724C9F9E596D@ridmsem02.nala.roche.com>

No, I want the hex version of the ASCII representation. It is what the item on the other end wants. I don't know why they do it that way, but if I want to talk to their device, I have to do it that way. At least you give me hope that the awkwardness I perceive is not simply my perception.

--vicki

-----Original Message-----
From: Alan Gauld [mailto:alan.gauld@blueyonder.co.uk]
Sent: Monday, October 27, 2003 1:52 PM
To: Stanfield, Vicki {D167~Indianapolis}; tutor@python.org
Subject: Re: [Tutor] reiterative programming


I'm not sure I understand the logic of the conversion.

hex(ord(c))

takes the character c, converts it to a number equal
to its ASCII value and then turns that number into a
hex representation. (Try it in the interpreter:

>>> print ord('4')
52
>>> print hex(ord(4))
0x34

Are you sure you don't want the hex representation of
the number the character represents

>>> print hex(int('4'))
0x4

Or even

>>> print int('4',16)
4

> I want to loop through doing this until the returned value is a hex
4.
>
> while returnedval != '\0x4':

This checks for the string '\0x4' which treats the \ as an escape
and yields:.

>>> print '\0x4'
 x4

You could use a raw string:

>>> print r'\0x4'
\0x4

> For some reason that I don't understand, when the returnedval
> is '0x4', it does the loop again

Because '0x4' is not the same as '\0x4'!

You need to be very clear about what you actually want to compare
with what, and then check the actual format you are using.
The >>> prompt is your friend.

Alan G.



From tpc at csua.berkeley.edu  Mon Oct 27 14:20:10 2003
From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu)
Date: Mon Oct 27 14:20:41 2003
Subject: [Tutor] invalid literal for float int or long solved !
Message-ID: <20031027111252.H91970-100000@localhost.name>


fingers crossed, here's hoping the bug doesn't rear its creepy head again,
can't really say wherefore the bug but I found a workaround, I changed the
basic MySQL statement below:

SELECT url, title FROM URLs, URLs_WITH_MATCHES WHERE URLs.id =
URLs_WITH_MATCHES.url_id;

to:

SELECT title, url from URLs INNER JOIN URLs_WITH_MATCHES ON URLs.id =
URLs_WITH_MATCHES.url_id;

and voila !  I am a complete idiot.


From oyvind.sporck at eniro.no  Mon Oct 27 14:42:46 2003
From: oyvind.sporck at eniro.no (=?iso-8859-1?Q?=D8yvind_Dale_Sp=F8rck?=)
Date: Mon Oct 27 14:44:15 2003
Subject: [Tutor] Re trouble
Message-ID: <E1A71873A9F96A42B1B9A5DBE308DCB701A9AEFA@hermes.a.sol.no>

Hello,

   I am using the Re module to filter out some webadresses out of html
documents, but cannot seem to get it right. What should go in the paranteses
of the re.search?

Here is an example from the html:

<a
href="../../../../../../get.liste.kvakk.no/fs/http_3A/www.db.no/smurf/defaul
t.htm"><b>Dagbladet AS</b></a> &#91;<a
href="../../../../../../get.liste.kvakk.no/is/http_3A/testside.no/smurf/defa
ult.htm"><font color="#CC3300"><b>Vis side</b></font></a>

In other words, I would like to get a list of these adresses:
www.db.no/smurf/default.htm
testside.no/smurf/default.htm

These adresses can be anything. I guess the common nominator is that they
start after http_3A/ and ends before the first ". 

How would I write that so that re picks out the right stuff?

Thanks in advance,
?yvind

From pythontutor at venix.com  Mon Oct 27 14:45:09 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Mon Oct 27 14:45:53 2003
Subject: [Tutor] reiterative programming
In-Reply-To: <CA3458C84C976E45B6372A6C14724C9F9E596D@ridmsem02.nala.roche.com>
References: <CA3458C84C976E45B6372A6C14724C9F9E596D@ridmsem02.nala.roche.com>
Message-ID: <3F9D75C5.5060706@venix.com>

You might find it easier to code against the integer that ord(c)
returns and delay converting to hex until you actually need to use
the hex value.

returnedval = None
while returnedval != 4:
	output=port.read(1)	# using 1 was suggested by someone else
	returnedval= ord(output)

In those places where you need the hex value, you would specify:
	hex(returnedval)

This avoids "fussy" string comparisons. (e.g. '0x4', '0X4', '0x04')

Stanfield, Vicki {D167~Indianapolis} wrote:

> No, I want the hex version of the ASCII representation. It is what the item on the other end wants. I don't know why they do it that way, but if I want to talk to their device, I have to do it that way. At least you give me hope that the awkwardness I perceive is not simply my perception.
> 
> --vicki
> 
> -----Original Message-----
> From: Alan Gauld [mailto:alan.gauld@blueyonder.co.uk]
> Sent: Monday, October 27, 2003 1:52 PM
> To: Stanfield, Vicki {D167~Indianapolis}; tutor@python.org
> Subject: Re: [Tutor] reiterative programming
> 
> 
> I'm not sure I understand the logic of the conversion.
> 
> hex(ord(c))
> 
> takes the character c, converts it to a number equal
> to its ASCII value and then turns that number into a
> hex representation. (Try it in the interpreter:
> 
> 
>>>>print ord('4')
> 
> 52
> 
>>>>print hex(ord(4))
> 
> 0x34
> 
> Are you sure you don't want the hex representation of
> the number the character represents
> 
> 
>>>>print hex(int('4'))
> 
> 0x4
> 
> Or even
> 
> 
>>>>print int('4',16)
> 
> 4
> 
> 
>>I want to loop through doing this until the returned value is a hex
> 
> 4.
> 
>>while returnedval != '\0x4':
> 
> 
> This checks for the string '\0x4' which treats the \ as an escape
> and yields:.
> 
> 
>>>>print '\0x4'
> 
>  x4
> 
> You could use a raw string:
> 
> 
>>>>print r'\0x4'
> 
> \0x4
> 
> 
>>For some reason that I don't understand, when the returnedval
>>is '0x4', it does the loop again
> 
> 
> Because '0x4' is not the same as '\0x4'!
> 
> You need to be very clear about what you actually want to compare
> with what, and then check the actual format you are using.
> The >>> prompt is your friend.
> 
> Alan G.
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582


From tpc at csua.berkeley.edu  Mon Oct 27 15:33:27 2003
From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu)
Date: Mon Oct 27 15:33:35 2003
Subject: [Tutor] Re trouble
In-Reply-To: <E1A71873A9F96A42B1B9A5DBE308DCB701A9AEFA@hermes.a.sol.no>
Message-ID: <20031027122740.K92516-100000@localhost.name>


regarding extracting URLs from HTML documents via Python regular
expressions, this question has been asked many times and the consensus is
that you want to use HTMLParser, as re doesn't keep state and is not the
right tool for this task.

You can search the python archives here:

http://mail.python.org/pipermail/tutor/

On Mon, 27 Oct 2003, [iso-8859-1] =D8yvind Dale Sp=F8rck wrote:

> Hello,
>
>    I am using the Re module to filter out some webadresses out of html
> documents, but cannot seem to get it right. What should go in the parante=
ses
> of the re.search?
>
> Here is an example from the html:
>
> <a
> href=3D"../../../../../../get.liste.kvakk.no/fs/http_3A/www.db.no/smurf/d=
efaul
> t.htm"><b>Dagbladet AS</b></a> &#91;<a
> href=3D"../../../../../../get.liste.kvakk.no/is/http_3A/testside.no/smurf=
/defa
> ult.htm"><font color=3D"#CC3300"><b>Vis side</b></font></a>
>
> In other words, I would like to get a list of these adresses:
> www.db.no/smurf/default.htm
> testside.no/smurf/default.htm
>
> These adresses can be anything. I guess the common nominator is that they
> start after http_3A/ and ends before the first ".
>
> How would I write that so that re picks out the right stuff?
>
> Thanks in advance,
> =D8yvind
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>



From tpc at csua.berkeley.edu  Mon Oct 27 15:53:45 2003
From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu)
Date: Mon Oct 27 15:53:52 2003
Subject: [Tutor] Re: [mod_python] invalid literal for float int or long
	solved !
In-Reply-To: <20031027144335.Q39378@onyx.ispol.com>
Message-ID: <20031027124550.E92775-100000@localhost.name>


ok I take that back.  I just switched it again as per your suggestion and
I now see that "url, title" gives me invalid literal errors whereas
"title, url" does not, even for the old SELECT statement.  This perplexes
me, as I know at least once I saw:

ValueError: invalid literal for float(): <insert any mp3 URL here>

However, I now make sure to <shift> RELOAD to make sure memory cache is
cleared, so you may be on to something.


On Mon, 27 Oct 2003, Gregory (Grisha) Trubetskoy wrote:

>
> The first one is "url, title", the second is "title, url" - was that the
> problem, or was it the WHERE instead of INNER JOIN (which are same thing
> IIRC).
>
> Grisha
>
>
> On Mon, 27 Oct 2003 tpc@csua.berkeley.edu wrote:
>
> >
> > fingers crossed, here's hoping the bug doesn't rear its creepy head again,
> > can't really say wherefore the bug but I found a workaround, I changed the
> > basic MySQL statement below:
> >
> > SELECT url, title FROM URLs, URLs_WITH_MATCHES WHERE URLs.id =
> > URLs_WITH_MATCHES.url_id;
> >
> > to:
> >
> > SELECT title, url from URLs INNER JOIN URLs_WITH_MATCHES ON URLs.id =
> > URLs_WITH_MATCHES.url_id;
> >
> > and voila !  I am a complete idiot.
> >
> > _______________________________________________
> > Mod_python mailing list
> > Mod_python@modpython.org
> > http://mailman.modpython.org/mailman/listinfo/mod_python
> >
>


From project5 at redrival.net  Mon Oct 27 17:15:29 2003
From: project5 at redrival.net (Andrei)
Date: Mon Oct 27 17:17:45 2003
Subject: [Tutor] Re: Re trouble
References: <E1A71873A9F96A42B1B9A5DBE308DCB701A9AEFA@hermes.a.sol.no>
Message-ID: <4gfj8aashwrs.12d29wvtuzj75.dlg@40tude.net>

?yvind Dale Sp?rck wrote on Mon, 27 Oct 2003 20:42:46 +0100:

> Hello,
> 
>    I am using the Re module to filter out some webadresses out of html
> documents, but cannot seem to get it right. What should go in the paranteses
> of the re.search?
> 
> Here is an example from the html:
> 
> <a
> href="../../../../../../get.liste.kvakk.no/fs/http_3A/www.db.no/smurf/defaul
> t.htm"><b>Dagbladet AS</b></a> &#91;<a
> href="../../../../../../get.liste.kvakk.no/is/http_3A/testside.no/smurf/defa
> ult.htm"><font color="#CC3300"><b>Vis side</b></font></a>
> 
> In other words, I would like to get a list of these adresses:
> www.db.no/smurf/default.htm
> testside.no/smurf/default.htm
> 
> These adresses can be anything. I guess the common nominator is that they
> start after http_3A/ and ends before the first ". 

Here's a regex that can do that (pick the group with index 1 returned by
RE, it contains the address):

  http_3A/(.*)"

Won't get you very far if your requirements change, even slightly.

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V
ernq gur yvfg, fb gurer'f ab arrq gb PP.


From alan.gauld at blueyonder.co.uk  Mon Oct 27 17:46:48 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Mon Oct 27 17:47:43 2003
Subject: [Tutor] reiterative programming
References: <CA3458C84C976E45B6372A6C14724C9F9E596D@ridmsem02.nala.roche.com>
Message-ID: <005c01c39cdc$34c8d120$6401a8c0@xp>

> No, I want the hex version of the ASCII representation. 

Oh, OK.

However the other points about the string representation
should still apply:

> > For some reason that I don't understand, when the returnedval
> > is '0x4', it does the loop again
>
> Because '0x4' is not the same as '\0x4'!
>
> You need to be very clear about what you actually want to compare
> with what, and then check the actual format you are using.
> The >>> prompt is your friend.


Alan G.




From Harm_Kirchhoff at mail.digital.co.jp  Mon Oct 27 19:21:27 2003
From: Harm_Kirchhoff at mail.digital.co.jp (Harm_Kirchhoff@mail.digital.co.jp)
Date: Mon Oct 27 19:23:56 2003
Subject: [Tutor] Basics of Classes
Message-ID: <OF8E437B1C.C4B42172-ON49256DCD.0000C98A-49256DCD.0001D892@jp.schneider-electric.com>

  amk, thank you VERY much. A simple question, but if you are new it can 
take you hours to find out. I really appreciate the help I am getting 
here, and hope to return it one day.

harm

From p.sur at worldnet.att.net  Mon Oct 27 21:12:44 2003
From: p.sur at worldnet.att.net (Partha Sur)
Date: Mon Oct 27 21:10:56 2003
Subject: [Tutor] "idle" problem
Message-ID: <003001c39cf8$fa950b00$3cac590c@welcome>

Hello,

I am unable to use "idle" development environment for Python.

When I invoke idle from the Linux prompt I get the following error message:

Memory fault.

I get back the Linux prompt.
(I am using ksh)

My hardware / software configuration is as follows:

Hardware:  Dell Dimension XPS T500
OS:  Red Hat Linux 9  (Kernel 2.4.20-6)
python-2.2.2-26
tkinter-2.2.22-26
tcl-8.3.5-88
tk-8.3.5-88
tclx-8.3-88
tcllib-1.3-88

I added the following to my .profile
PATH=$PATH:/usr/lib/python2.2/site-packages/idle:.
to invoke idle directly from my home Linux prompt.

When I first invoked idle from my Linux prompt I got the following error
message:
"Import Error: No module named idlelib"

So I then modified the idle script in the
/usr/lib/python2.2/site-packages/idle
directory thus:

#! /usr/bin/env python

# import modified by Partha Sur 9/22/2003
# to suppress "ImportError : No module named idlelib"
# import IdleConf and PyShell directly - there is no idlelib on this system

import os
import sys
#from idlelib import IdleConf  <=  I commented this out
import IdleConf

idle_dir = os.path.dirname(IdleConf.__file__)
IdleConf.load(idle_dir)
# defer importing Pyshell until IdleConf is loaded
#from idlelib import PyShell   <=  I commented this out
import PysShell
PyShell.main()

Now I do not get the "ImportError: ..." error message but idle fails to run
with the "Memory fault" error message.

If anyone can help me resolve my problem I shall be very thankful.
Until then I am forced to work with the >>> prompt.

Thanks.

Partha Sur



From ptwaugh at earthlink.net  Mon Oct 27 21:32:07 2003
From: ptwaugh at earthlink.net (P.T. Waugh MA)
Date: Mon Oct 27 21:34:30 2003
Subject: [Tutor] Question on Reading a Directory
Message-ID: <5.2.1.1.2.20031027182840.00aaead0@pop.earthlink.net>

Hi all,

I'm a very new Python programmer, and I want to get all the filenames 
(Windows) into a list.  I have been unable to figure out how to do this and 
don't see any functions in the library to do it.

Your help is appreciated.

Also, just out of curiousity.... this is how I copy a file:

splash = select_splash()
win32file.CopyFile(splash, '..\\dlgsplash.bmp',0)

and I was just wondering, if I need to do it this way (as it seems 
un-portable).

Cheers,

Patrick




From littledanehren at yahoo.com  Mon Oct 27 21:35:55 2003
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Mon Oct 27 21:36:00 2003
Subject: [Tutor] running process in parallel
In-Reply-To: <BAY1-F12pqpEq8hZYNX00009e20@hotmail.com>
Message-ID: <20031028023555.51863.qmail@web41812.mail.yahoo.com>

> I want to run some script files in different
> directory all at a time that is 
> running process in parallel .Is it possible?
> 
> * kamariah lamim [2003-10-27
> 12:31]:
> >Hi ;
> >   i want to call and execute  other programs
> parallely from python.is that 
> >possible.?what tools do i need?
> 
> What type of programs and what do you mean by
> "Parallely"? You can use
> os.fork or many of its variants to start child
> processes. What else are
> you looking for?
> 
> --
> David Rock
> david @ graniteweb.com

Funny, the version of Python I'm using (2.3.2-1)
doesn't have os.fork. Here's the input and output in
case I interpreted something incorrectly:

>>> import os
>>> os.fork
Traceback (most recent call last):
  File "<input>", line 1, in ?
AttributeError: 'module' object has no attribute
'fork'

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Exclusive Video Premiere - Britney Spears
http://launch.yahoo.com/promos/britneyspears/

From jeff at ccvcorp.com  Mon Oct 27 21:49:59 2003
From: jeff at ccvcorp.com (Jeff Shannon)
Date: Mon Oct 27 21:45:46 2003
Subject: [Tutor] running process in parallel
In-Reply-To: <20031028023555.51863.qmail@web41812.mail.yahoo.com>
References: <20031028023555.51863.qmail@web41812.mail.yahoo.com>
Message-ID: <3F9DD957.4090702@ccvcorp.com>

Daniel Ehrenberg wrote:

>>>  i want to call and execute  other programs
>>>parallely from python.is that 
>>>possible.?what tools do i need?
>>
>>What type of programs and what do you mean by
>>"Parallely"? You can use
>>os.fork or many of its variants to start child
>>processes. 
> 
> Funny, the version of Python I'm using (2.3.2-1)
> doesn't have os.fork. 

os.fork() is a *nix-only function.  On Windows, something similar can 
be done with the os.exec* family of functions.

It's also possible, on Windows, to use os.system("start file.ext") to 
have the OS take the action that's associated with the given ext 
(usually running a program and loading the named document).  Unlike 
fork() and exec*(), "start" will cause the program to run in a new 
process, leaving the original process free to do other tasks.  (I 
believe that there's a comparable *nix command, but I'm not certain 
what it is offhand...)

Jeff Shannon
Technician/Programmer
Credit International



From jeff at ccvcorp.com  Mon Oct 27 21:52:20 2003
From: jeff at ccvcorp.com (Jeff Shannon)
Date: Mon Oct 27 21:48:17 2003
Subject: [Tutor] Question on Reading a Directory
In-Reply-To: <5.2.1.1.2.20031027182840.00aaead0@pop.earthlink.net>
References: <5.2.1.1.2.20031027182840.00aaead0@pop.earthlink.net>
Message-ID: <3F9DD9E4.7060909@ccvcorp.com>

P.T. Waugh MA wrote:

> Hi all,
> 
> I'm a very new Python programmer, and I want to get all the filenames 
> (Windows) into a list.  I have been unable to figure out how to do this 
> and don't see any functions in the library to do it.
> 
> Your help is appreciated.
> 
> Also, just out of curiousity.... this is how I copy a file:
> 
> splash = select_splash()
> win32file.CopyFile(splash, '..\\dlgsplash.bmp',0)
> 
> and I was just wondering, if I need to do it this way (as it seems 
> un-portable).

You want the os.listdir() function (to list the entire contents of a 
directory), or glob.glob() (to list filenames matching a filespec with 
wildcards).

For portable equivalents to most of the win32file functions, look in 
the os module and the shutil module.

Jeff Shannon
Technician/Programmer
Credit International



From littledanehren at yahoo.com  Mon Oct 27 21:56:42 2003
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Mon Oct 27 21:56:47 2003
Subject: [Tutor] Question on Reading a Directory
In-Reply-To: <5.2.1.1.2.20031027182840.00aaead0@pop.earthlink.net>
Message-ID: <20031028025642.54855.qmail@web41812.mail.yahoo.com>

> Hi all,
> 
> I'm a very new Python programmer, and I want to get
> all the filenames 
> (Windows) into a list.  I have been unable to figure
> out how to do this and 
> don't see any functions in the library to do it.

What do you mean all of the filenames? All of the
filenames in a folder? All of they python files on
your computer? All of the files on your computer?
> 
> Your help is appreciated.
> 
> Also, just out of curiousity.... this is how I copy
> a file:
> 
> splash = select_splash()
> win32file.CopyFile(splash, '..\\dlgsplash.bmp',0)
> 
> and I was just wondering, if I need to do it this
> way (as it seems 
> un-portable).
> 
> Cheers,
> 
> Patrick

Yes, it is unportable. I just didn't download the
win32all extentions so that I wouldn't accidentally
write such unportable code. (If you need an IDE that's
better than Python but not the Win32 IDE, use the one
that comes with wxPython.) I would probably write the
code like this (but it wouldn't garbage collect
properly on Jython):

>>> infilepath = raw_input("input ")
>>> outfilepath = raw_input("output ")
>>> print >> file(outfilepath, 'w'),
file(infilepath).read()

There is probably a more efficient way to write it,
but I can't think of it. On my computer, it works
virtually instantaniously, so I don't really care if
it's as fast as with win32all.

Note: for most other cross-platform operations (that
would normally be platform-dependent), you would
usually use the os or sys modules.
Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Exclusive Video Premiere - Britney Spears
http://launch.yahoo.com/promos/britneyspears/

From project5 at redrival.net  Mon Oct 27 22:06:43 2003
From: project5 at redrival.net (Andrei)
Date: Mon Oct 27 22:08:58 2003
Subject: [Tutor] Re: Question on Reading a Directory
References: <5.2.1.1.2.20031027182840.00aaead0@pop.earthlink.net>
	<20031028025642.54855.qmail@web41812.mail.yahoo.com>
Message-ID: <fm6c0ob0ikcc$.qzcvwm8yovja.dlg@40tude.net>

Daniel Ehrenberg wrote on Mon, 27 Oct 2003 18:56:42 -0800 (PST):

<snip>
>> splash = select_splash()
>> win32file.CopyFile(splash, '..\\dlgsplash.bmp',0)
>> 
>> and I was just wondering, if I need to do it this
>> way (as it seems 
>> un-portable).
> 
> Yes, it is unportable. I just didn't download the
> win32all extentions so that I wouldn't accidentally
> write such unportable code. (If you need an IDE that's

Never write "win32" in your code if you want it to be portable, that's a
good rule :).

> better than Python but not the Win32 IDE, use the one
> that comes with wxPython.) I would probably write the

wxPython doesn't really include an IDE, does it? A simple editor perhaps.
Spe is the only wxPython-based IDE I know (pretty good too).

> code like this (but it wouldn't garbage collect
> properly on Jython):
> 
>>>> infilepath = raw_input("input ")
>>>> outfilepath = raw_input("output ")
>>>> print >> file(outfilepath, 'w'),
> file(infilepath).read()
> There is probably a more efficient way to write it,
> but I can't think of it. On my computer, it works

The shutil module contains lots of file operations, including copy, move
and delete trees. It's cross-platform.

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V
ernq gur yvfg, fb gurer'f ab arrq gb PP.


From karl.fast at pobox.com  Mon Oct 27 23:36:51 2003
From: karl.fast at pobox.com (Karl Fast)
Date: Mon Oct 27 23:36:59 2003
Subject: [Tutor] generating instance names from a list
Message-ID: <20031027223651.F2605@signal.lights.com>


I've got a list and want to create an instance for each item in the
list based on the list value. In other words, I want to create a set
of objects based on some list values.


I'm trying to do something like this (which doesn't work):

class SomeClass:
  names = ['alpha', 'beta']

  def somefunc(self):
      for item in self.names:
          self.item = OtherClass()

class OtherClass:
   ....


Obviously that's not going to work. It creates self.item and keeps
reassigning it until the list is exhausted. 

I've had to resort to this, which seems silly.

  def somefunc(self):
      self.alpha = OtherClass()
      self.beta  = OtherClass()


I'm missing something real obvious and it's late and maybe someone
will answer this by the time I wake up tomorrow!


--karl


From thomi at imail.net.nz  Mon Oct 27 23:43:10 2003
From: thomi at imail.net.nz (Thomi Richards)
Date: Mon Oct 27 23:46:22 2003
Subject: [Tutor] generating instance names from a list
In-Reply-To: <20031027223651.F2605@signal.lights.com>
References: <20031027223651.F2605@signal.lights.com>
Message-ID: <200310281743.14272.thomi@imail.net.nz>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

>
> I'm trying to do something like this (which doesn't work):
>
> class SomeClass:
>   names = ['alpha', 'beta']
>
>   def somefunc(self):
>       for item in self.names:
>           self.item = OtherClass()
>
> class OtherClass:
>    ....
>

Hi!

I tried this a wee while ago, so I may as well share my results with you.

The only way you can do this (AFAIK) is like so:

names = ['alpha','beta']

for name in names:
	exec('%s = someClass()' % (name))

However, I found out very quickly that this really isn't a good idea... you 
might want to try doing something like:

1.- storing your class instance in a list?:

names = ['alpha','beta']
objects = []

for name in names:
	objects.append(someClass(name))

inside the someClass class it could assign the value passed to it to an 
internal attribute....

2.- another (better?) way is to store your class instances in a dictionary, 
like so:

names = ['alpha','beta']
objects = {}

for name in objects:
	objects[name] = someClass()

now, you can use this dictionary like so:

objects['alpha'].somemethod()

all the above is untested code, but here's a short snippet to illustrate what 
I'm getting at:

>>> def foo():
...     print "hi"
... 
>>> d['foo'] = foo
>>> d['foo']
<function foo at 0x40210f0c>
>>> d['foo']()
hi


simple eh?

HTH!


- -- 
Thomi Richards,
http://once.sourceforge.net/


-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.3 (GNU/Linux)

iD8DBQE/nfPh2tSuYV7JfuERAo19AJ4+sBShWDWpnU4fi0dC54+GSg4ciwCdGCsx
q8/Ko9vNFxq1MDfQSo2hyqA=
=VAdb
-----END PGP SIGNATURE-----


From alan.gauld at blueyonder.co.uk  Tue Oct 28 02:28:17 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Tue Oct 28 02:29:03 2003
Subject: [Tutor] Re trouble
References: <20031027122740.K92516-100000@localhost.name>
Message-ID: <008101c39d25$0e819530$6401a8c0@xp>

> regarding extracting URLs from HTML documents via Python regular
> expressions, this question has been asked many times and the 
> consensus is that you want to use HTMLParser, as re doesn't 
> keep state and is not the right tool for this task.

That's true for parsing html for tag values but if you are looking 
for urls then regex should work just fine. There is no chance of 
a regex containing another regex within it!

So provided you aren't trying to extract the url by looking for
<A></A> pairs or somesuch it should be OK.

Alan G.


From python.tutorial at jarava.org  Tue Oct 28 04:31:01 2003
From: python.tutorial at jarava.org (Javier JJ)
Date: Tue Oct 28 04:31:17 2003
Subject: [Tutor] Python + ioctl + Windows HOWTO?
Message-ID: <3F9E3755.1070608@jarava.org>

Hi all!!

I'm trying to use Python to help in testing software for the Windows 
Platform.

The sw we develop at the company I work for sets up quite a number of 
"new" device drives in Windows, and as part of the testing process I'd 
need to be able to "query" them about their state and suchlike. The 
"interface" for doing so involves opening "device files" (of the form  
\\.\Device\CDCrypto) and sending them ioctls to query their state.

I've been searching / googling for ioctl, and the only mentions I've 
seen are to UNIX-specific modules such as fcntl. My question is, is it 
possible to use similar functions / modules in windows? If so, how?

Thanks a lot

    Javier

PS: Also, is there any "pre-built" "sw-testing" framework developed in 
Python. I'm not refering to "unit testing" for Python code, but a way of 
"plugging-on" tests and specifying dependencies so that I'd only have to 
worry about what tests to write / how to test things.

    Thank,s


       JJJ


From python.tutorial at jarava.org  Tue Oct 28 04:31:26 2003
From: python.tutorial at jarava.org (Javier JJ)
Date: Tue Oct 28 04:31:36 2003
Subject: [Tutor] Python + ioctl + Windows HOWTO?
Message-ID: <3F9E376E.4060303@jarava.org>

Hi all!!

I'm trying to use Python to help in testing software for the Windows 
Platform.

The sw we develop at the company I work for sets up quite a number of 
"new" device drives in Windows, and as part of the testing process I'd 
need to be able to "query" them about their state and suchlike. The 
"interface" for doing so involves opening "device files" (of the form  
\\.\Device\CDCrypto) and sending them ioctls to query their state.

I've been searching / googling for ioctl, and the only mentions I've 
seen are to UNIX-specific modules such as fcntl. My question is, is it 
possible to use similar functions / modules in windows? If so, how?

Thanks a lot

    Javier

PS: Also, is there any "pre-built" "sw-testing" framework developed in 
Python. I'm not refering to "unit testing" for Python code, but a way of 
"plugging-on" tests and specifying dependencies so that I'd only have to 
worry about what tests to write / how to test things.

    Thank,s


       JJJ


From karl.fast at pobox.com  Tue Oct 28 11:30:55 2003
From: karl.fast at pobox.com (Karl Fast)
Date: Tue Oct 28 11:31:01 2003
Subject: [Tutor] generating instance names from a list
In-Reply-To: <200310281743.14272.thomi@imail.net.nz>;
	from thomi@imail.net.nz on Tue, Oct 28, 2003 at 05:43:10PM +1300
References: <20031027223651.F2605@signal.lights.com>
	<200310281743.14272.thomi@imail.net.nz>
Message-ID: <20031028103055.O2605@signal.lights.com>


I understand, thanks. 

> 1.- storing your class instance in a list?:
> 
> names = ['alpha','beta']
> objects = []
> 
> for name in names:
> 	objects.append(someClass(name))
> 
> inside the someClass class it could assign the value passed to it to
> an internal attribute....


From pythontutor at venix.com  Tue Oct 28 11:56:34 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Tue Oct 28 11:56:52 2003
Subject: [Tutor] generating instance names from a list
In-Reply-To: <20031027223651.F2605@signal.lights.com>
References: <20031027223651.F2605@signal.lights.com>
Message-ID: <3F9E9FC2.9020901@venix.com>

When the name of an attribute is in a variable, you can use the
builtin functions:
	getattr(obj, name[,default])
	hasattr(obj, name)
	setattr(obj, name, value)
to work with the attribue and its object.

def somefunc(self):
     for item in self.names:
         setattr(self, item, OtherClass())

should do what you intended.

Karl Fast wrote:

> I've got a list and want to create an instance for each item in the
> list based on the list value. In other words, I want to create a set
> of objects based on some list values.
> 
> 
> I'm trying to do something like this (which doesn't work):
> 
> class SomeClass:
>   names = ['alpha', 'beta']
> 
>   def somefunc(self):
>       for item in self.names:
>           self.item = OtherClass()
> 
> class OtherClass:
>    ....
> 
> 
> Obviously that's not going to work. It creates self.item and keeps
> reassigning it until the list is exhausted. 
> 

> 
> --karl
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582


From karl.fast at pobox.com  Tue Oct 28 12:25:58 2003
From: karl.fast at pobox.com (Karl Fast)
Date: Tue Oct 28 12:27:05 2003
Subject: [Tutor] generating instance names from a list
In-Reply-To: <3F9E9FC2.9020901@venix.com>;
	from pythontutor@venix.com on Tue, Oct 28, 2003 at 11:56:34AM
	-0500
References: <20031027223651.F2605@signal.lights.com>
	<3F9E9FC2.9020901@venix.com>
Message-ID: <20031028112558.P2605@signal.lights.com>


This works. This is the solution I was looking for. Much thanks.

I've summarized the problem and the solution below, for anyone who
cares and doesn't want to piece together the thread.


> When the name of an attribute is in a variable, you can use the
> builtin functions:
> 	getattr(obj, name[,default])
> 	hasattr(obj, name)
> 	setattr(obj, name, value)
> to work with the attribue and its object.


THE PROBLEM:

You've got a list of names and want to create an instance for each
item in the list.  

THE SOLUTION:

class SomeClass:
 
   def somefunc(self):
       names = ['alpha', 'beta']
       
       for item in names:
           setattr(self, item, OtherClass())

class OtherClass:
   ....


So if you do this:

  >>> a = SomeClass()
  >>> a.somefunc()

You will now have a.alpha and a.beta, both instances of OtherClass.



--karl

From karl.fast at pobox.com  Tue Oct 28 13:01:34 2003
From: karl.fast at pobox.com (Karl Fast)
Date: Tue Oct 28 13:01:43 2003
Subject: [Tutor] instantiating subclass by parameter
Message-ID: <20031028120134.Q2605@signal.lights.com>


I've got a class with two subclasses. I need to create an instance
of a particular subclass, inheriting from the superclass, but I want
to do it by passing a parameter to the super class. 

I'm probably not describing this very well. Some sample code might
help.

This doesn't work, but I think it illusrates what I'm going for...

class WebSearch:
    def __init__(self, engine):
        self.name = engine    
        if engine == 'altavista':
            self = Altavista.__init__()
        elif engine == 'alltheweb':
            self = AlltheWeb.__init__()

    def foo(self):
       print "inherited foo"

    def bar(self):
       print "inherited bar"
       
class Altavista(WebSearch):
    def __init__(self):
        pass

    def foo(self):
       print "altavista foo"    

class AlltheWeb(WebSearch):
    def __init__(self):
        pass
  
    def bar(self):
        print "alltheweb bar"


The idea is that if I create instances, like so, then I'll get these
results:

  >>>  a = WebSearch('altavista')
  >>>  b = WebSearch('alltheweb')
  >>>  a.name
  altavista
  >>>  b.name
  alltheweb  
  >>>  a.foo()
  altavista foo
  >>>  b.bar()
  alltheweb bar  
  >>>  a.bar()
  inherited bar
  >>>  b.foo()  
  inherited foo

Does that make sense?


--karl

From gipson1 at indiatimes.com  Tue Oct 28 13:03:27 2003
From: gipson1 at indiatimes.com (gipson1)
Date: Tue Oct 28 13:11:24 2003
Subject: [Tutor] berkeley db
Message-ID: <200310281740.XAA03558@WS0005.indiatimes.com>

I have python 2.2 installed on my redhat machine
i want to access berkeley database version  4.1 from python 


with some sample programs kindly help me to access berkeley db


with regards,
bye
 Click onthe image to chat with me
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20031028/1236fe8d/attachment.html
From dyoo at hkn.eecs.berkeley.edu  Tue Oct 28 13:29:18 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Oct 28 13:29:28 2003
Subject: [Tutor] Python + ioctl + Windows HOWTO?
In-Reply-To: <3F9E376E.4060303@jarava.org>
Message-ID: <Pine.LNX.4.44.0310281022090.4287-100000@hkn.eecs.berkeley.edu>



On Tue, 28 Oct 2003, Javier JJ wrote:

> The sw we develop at the company I work for sets up quite a number of
> "new" device drives in Windows, and as part of the testing process I'd
> need to be able to "query" them about their state and suchlike. The
> "interface" for doing so involves opening "device files" (of the form
> \\.\Device\CDCrypto) and sending them ioctls to query their state.
>
> I've been searching / googling for ioctl, and the only mentions I've
> seen are to UNIX-specific modules such as fcntl. My question is, is it
> possible to use similar functions / modules in windows? If so, how?

Hi Javier,

According to the documentation at:

    http://www.python.org/doc/current/lib/module-fcntl.html

the ioctl() call in there is a Unix call, so it probably won't work on
Windows.


> PS: Also, is there any "pre-built" "sw-testing" framework developed in
> Python. I'm not refering to "unit testing" for Python code, but a way of
> "plugging-on" tests and specifying dependencies so that I'd only have to
> worry about what tests to write / how to test things.


I have to profess complete ignorance on these topics.  You may want to ask
your question on the main Python newsgroup, comp.lang.python.  That
newsgroup enjoys a wide readership, and the folks there should be better
able to point you toward a good answer.


My apologies!


From dyoo at hkn.eecs.berkeley.edu  Tue Oct 28 13:34:19 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Oct 28 13:34:39 2003
Subject: [Tutor] berkeley db
In-Reply-To: <200310281740.XAA03558@WS0005.indiatimes.com>
Message-ID: <Pine.LNX.4.44.0310281031070.4287-100000@hkn.eecs.berkeley.edu>



On Tue, 28 Oct 2003, gipson1 wrote:

> I have python 2.2 installed on my redhat machine i want to access
> berkeley database version 4.1 from python
>
> with some sample programs kindly help me to access berkeley db

Hi gipson1,

The standard bsddb library at:

    http://www.python.org/doc/lib/module-bsddb.html

should work if you're using Python 2.3.


But if you have to use Python 2.2, then you can grab pybsddb:

    http://pybsddb.sourceforge.net/

which should have support for the 4.1 database format that you're using.


Good luck!


From pythontutor at venix.com  Tue Oct 28 14:06:19 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Tue Oct 28 14:06:36 2003
Subject: [Tutor] instantiating subclass by parameter
In-Reply-To: <20031028120134.Q2605@signal.lights.com>
References: <20031028120134.Q2605@signal.lights.com>
Message-ID: <3F9EBE2B.5090402@venix.com>

class Altavista(WebSearch):
     def __init__(self):
         WebSearch.__init__(self, 'altavista')

The child class __init__ needs to call its parent __init__.

So now you would have:
     a = Altavista()
to create an Altavista based instance.

You can have a "factory" function that calls the proper class


Recent Python improvements involve "new style" classes.  amk publishes the
what's new in python notes.

http://www.python.org/doc/2.2.3/whatsnew/whatsnew22.html
What's New in Python 2.2

There are benefits to making object your base class.  You would
change WebSearch to inherit from object.  Then the __init__ method
would be coded:
class WebSearch(object):
     ...
class Altavista(WebSearch):
     def __init__(self):
         super(Altavista, self).__init__(self, 'altavista')


Also, classes have a special attribute: __name__ which is (surprise)
the name of the class.  The WebSearch __init__ could use
self.__class__.__name__ rather than a parameter.

Hope this helps.

Karl Fast wrote:

> I've got a class with two subclasses. I need to create an instance
> of a particular subclass, inheriting from the superclass, but I want
> to do it by passing a parameter to the super class. 
> 
> I'm probably not describing this very well. Some sample code might
> help.
> 
> This doesn't work, but I think it illusrates what I'm going for...
> 
> class WebSearch:
>     def __init__(self, engine):
>         self.name = engine    
>         if engine == 'altavista':
>             self = Altavista.__init__()
>         elif engine == 'alltheweb':
>             self = AlltheWeb.__init__()
> 
>     def foo(self):
>        print "inherited foo"
> 
>     def bar(self):
>        print "inherited bar"
>        
> class Altavista(WebSearch):
>     def __init__(self):
>         pass
> 
>     def foo(self):
>        print "altavista foo"    
> 
> class AlltheWeb(WebSearch):
>     def __init__(self):
>         pass
>   
>     def bar(self):
>         print "alltheweb bar"
> 
> 
> The idea is that if I create instances, like so, then I'll get these
> results:
> 
>   >>>  a = WebSearch('altavista')
>   >>>  b = WebSearch('alltheweb')
>   >>>  a.name
>   altavista
>   >>>  b.name
>   alltheweb  
>   >>>  a.foo()
>   altavista foo
>   >>>  b.bar()
>   alltheweb bar  
>   >>>  a.bar()
>   inherited bar
>   >>>  b.foo()  
>   inherited foo
> 
> Does that make sense?
> 
> 
> --karl
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582


From karl.fast at pobox.com  Tue Oct 28 15:58:14 2003
From: karl.fast at pobox.com (Karl Fast)
Date: Tue Oct 28 15:58:47 2003
Subject: [Tutor] instantiating subclass by parameter
In-Reply-To: <3F9EBE2B.5090402@venix.com>;
	from pythontutor@venix.com on Tue, Oct 28, 2003 at 02:06:19PM
	-0500
References: <20031028120134.Q2605@signal.lights.com>
	<3F9EBE2B.5090402@venix.com>
Message-ID: <20031028145814.B1129@signal.lights.com>

> You can have a "factory" function that calls the proper class

Ahh, a factory function is what I need. Being new to python and
somewhat new to OOP I wasn't aware of the factory thing. Was trying
to replicate a CPAN perl module that works like I described.

It works. Here's a cookbook style writeup.

However, I still have one small question (at the very end).


PROBLEM:

You've got a class with various subclasses and you want some generic
code that will instantiate the proper subclass based on a variable
instead of a classname.

A SOLUTION:

You need a factory function. The following code has a master class
(WebSearch) with two subclasses (Altavista, AlltheWeb). 

You can create new objects by calling these classes directly. But
the point is to call the factory function instead which returns an
an object instance based on the keyword you supply.


class WebSearch:
   def __init__(self, engine):
       self.name = engine
         
   def foo(self):
       return "inherited foo"
         
   def bar(self):
       return "inherited bar"
         
class Altavista(WebSearch):
   def __init__(self):
       WebSearch.__init__(self, 'altavista')
         
   def foo(self):
       return "altavista foo"
         
class AlltheWeb(WebSearch):
   def __init__(self):
       WebSearch.__init__(self, 'alltheweb')
         
   def bar(self):
       return "alltheweb bar"

def factory (engine):
   if engine == 'altavista':
       return apply(Altavista)
   elif engine == 'alltheweb':
       return apply(AlltheWeb)

if __name__ == '__main__':
   alpha = factory('altavista')
   beta  = factory('alltheweb')
   print "alpha.name  = %s" % alpha.name
   print "alpha.foo() = %s" % alpha.foo()
   print "alpha.bar() = %s" % alpha.bar()  
   print "beta.name   = %s" % beta.name
   print "beta.foo()  = %s" % beta.foo()
   print "beta.foo()  = %s" % beta.bar()  

If you run this you'll get the following, which is what you want:
   
   alpha.name  = altavista
   alpha.foo() = altavista foo
   alpha.bar() = inherited bar
   beta.name   = alltheweb
   beta.foo()  = inherited foo
   beta.foo()  = alltheweb bar


QUESTION, if anyone read this far....   

Instead of doing this:

   alpha = factory('altavista')
   beta  = factory('alltheweb')

I'd rather have a dict with the desired object names and use that to
call the factory function. Kinda like this (which doesn't work).

     create = {'alpha': 'altavista', 'beta': 'alltheweb'}
     for key in create:
         key = factory(create[key])

The assignment clearly fails. The idea is to wind up with objects
called alpha and beta, which you can do things like alpha.foo() and
beta.name.
         
My current solution is to build a dict of objects created by the
factory, where the keynames are the desired object names.

     create = {'alpha': 'altavista', 'beta': 'alltheweb'}
     obj = {}
     for key in create:
         obj[key] = factory(create[key])
     for key in obj:
         print obj[key]
         print obj[key].name
         print obj[key].foo()
         print obj[key].bar()
                                               
Again, I suspect there is an easy answer, I'm just lacking enough
knowledge of python.

--karl

From pythontutor at venix.com  Tue Oct 28 16:54:10 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Tue Oct 28 16:54:18 2003
Subject: [Tutor] instantiating subclass by parameter
In-Reply-To: <20031028145814.B1129@signal.lights.com>
References: <20031028120134.Q2605@signal.lights.com>	<3F9EBE2B.5090402@venix.com>
	<20031028145814.B1129@signal.lights.com>
Message-ID: <3F9EE582.7080906@venix.com>

def factory (engine):
    if engine == 'altavista':
        return apply(Altavista)
    elif engine == 'alltheweb':
        return apply(AlltheWeb)

This doesn't need to use apply.  Simply:
	return Altavista()	# the () calls the class to get an instance
or
	return AlltheWeb()


Here you need something to hold the objects that you are creating.
      create = {'alpha': 'altavista', 'beta': 'alltheweb'}
      for key in create:
          key = factory(create[key])
The name key is bound to each object in turn and winds up bound to the
last one.  The alpha/altavista object is created and lost because it
is not bound (tied to) any name.

The folowing code where you use a dictionary named obj to hold the objects
with the specified key names (alpha, beta) looks like it should work.

What's going wrong?


Karl Fast wrote:

>>You can have a "factory" function that calls the proper class
> 
> 
> Ahh, a factory function is what I need. Being new to python and
> somewhat new to OOP I wasn't aware of the factory thing. Was trying
> to replicate a CPAN perl module that works like I described.
> 
> It works. Here's a cookbook style writeup.
> 
> However, I still have one small question (at the very end).
> 
> 
> PROBLEM:
> 
> You've got a class with various subclasses and you want some generic
> code that will instantiate the proper subclass based on a variable
> instead of a classname.
> 
> A SOLUTION:
> 
> You need a factory function. The following code has a master class
> (WebSearch) with two subclasses (Altavista, AlltheWeb). 
> 
> You can create new objects by calling these classes directly. But
> the point is to call the factory function instead which returns an
> an object instance based on the keyword you supply.
> 
> 
> class WebSearch:
>    def __init__(self, engine):
>        self.name = engine
>          
>    def foo(self):
>        return "inherited foo"
>          
>    def bar(self):
>        return "inherited bar"
>          
> class Altavista(WebSearch):
>    def __init__(self):
>        WebSearch.__init__(self, 'altavista')
>          
>    def foo(self):
>        return "altavista foo"
>          
> class AlltheWeb(WebSearch):
>    def __init__(self):
>        WebSearch.__init__(self, 'alltheweb')
>          
>    def bar(self):
>        return "alltheweb bar"
> 
> def factory (engine):
>    if engine == 'altavista':
>        return apply(Altavista)
>    elif engine == 'alltheweb':
>        return apply(AlltheWeb)
> 
> if __name__ == '__main__':
>    alpha = factory('altavista')
>    beta  = factory('alltheweb')
>    print "alpha.name  = %s" % alpha.name
>    print "alpha.foo() = %s" % alpha.foo()
>    print "alpha.bar() = %s" % alpha.bar()  
>    print "beta.name   = %s" % beta.name
>    print "beta.foo()  = %s" % beta.foo()
>    print "beta.foo()  = %s" % beta.bar()  
> 
> If you run this you'll get the following, which is what you want:
>    
>    alpha.name  = altavista
>    alpha.foo() = altavista foo
>    alpha.bar() = inherited bar
>    beta.name   = alltheweb
>    beta.foo()  = inherited foo
>    beta.foo()  = alltheweb bar
> 
> 
> QUESTION, if anyone read this far....   
> 
> Instead of doing this:
> 
>    alpha = factory('altavista')
>    beta  = factory('alltheweb')
> 
> I'd rather have a dict with the desired object names and use that to
> call the factory function. Kinda like this (which doesn't work).
> 
>      create = {'alpha': 'altavista', 'beta': 'alltheweb'}
>      for key in create:
>          key = factory(create[key])
> 
> The assignment clearly fails. The idea is to wind up with objects
> called alpha and beta, which you can do things like alpha.foo() and
> beta.name.
>          
> My current solution is to build a dict of objects created by the
> factory, where the keynames are the desired object names.
> 
>      create = {'alpha': 'altavista', 'beta': 'alltheweb'}
>      obj = {}
>      for key in create:
>          obj[key] = factory(create[key])
>      for key in obj:
>          print obj[key]
>          print obj[key].name
>          print obj[key].foo()
>          print obj[key].bar()
>                                                
> Again, I suspect there is an easy answer, I'm just lacking enough
> knowledge of python.
> 
> --karl
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582


From karl.fast at pobox.com  Tue Oct 28 17:10:01 2003
From: karl.fast at pobox.com (Karl Fast)
Date: Tue Oct 28 17:11:03 2003
Subject: [Tutor] instantiating subclass by parameter
In-Reply-To: <3F9EE582.7080906@venix.com>;
	from pythontutor@venix.com on Tue, Oct 28, 2003 at 04:54:10PM
	-0500
References: <20031028120134.Q2605@signal.lights.com>
	<3F9EBE2B.5090402@venix.com>
	<20031028145814.B1129@signal.lights.com>
	<3F9EE582.7080906@venix.com>
Message-ID: <20031028161001.D1129@signal.lights.com>

> Here you need something to hold the objects that you are creating.
>       create = {'alpha': 'altavista', 'beta': 'alltheweb'}
>       for key in create:
>           key = factory(create[key])

I understand what's going wrong here. I knew it wasn't working and I
knew why, but thanks for your explanation which confirms it.


> The folowing code where you use a dictionary named obj to hold the
> objects with the specified key names (alpha, beta) looks like it
> should work.

Yes, it does work (tested it before posting).

I'm just wondering if there is another way of doing this that would
give me objects based on the name in the dict, instead of a dict
holding the objects where the objects are accessible by key.

That is, instead of accessing the results like this:

   obj['alpha'].foo() 
   obj['beta'].name

I could access them like this:

   alpha.foo()
   beta.name()

The dict solution works. As an exercise in learning python I'm 
wondering if is another solution that would give me the second
result.

In other words, is there a way to change the line that calls factory
so that it creates the objects alpha and beta.

   create = {'alpha': 'altavista', 'beta': 'alltheweb'}
   for key in create:
        key = factory(create[key])

   alpha.foo()

   
--karl        

From alan.gauld at blueyonder.co.uk  Tue Oct 28 18:15:31 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Tue Oct 28 18:16:07 2003
Subject: [Tutor] generating instance names from a list
References: <20031027223651.F2605@signal.lights.com>
Message-ID: <003a01c39da9$621011c0$6401a8c0@xp>


> I'm trying to do something like this (which doesn't work):
> 
> class SomeClass:
>   names = ['alpha', 'beta']

If you make that list a dictionary:
    names = {'alpha':None,'beta':None}

>   def somefunc(self):
>       for item in self.names:
>           self.item = OtherClass()

Then you can do this:
            self.names[item] = OtherClass()

> I've had to resort to this, which seems silly.
> 
>   def somefunc(self):
>       self.alpha = OtherClass()
>       self.beta  = OtherClass()

Why is that silly? If you have a fixed set of names this 
is both clear and unambiguous! (If you must do it from a 
loop you can probably do some tricks with setattr and 
getattr too, but personally I'd just list the attributes 
explicitly!)

Using a list of names is better if you have a dynamic list 
- ie new names can be added during the lifetime of an object,
or if you have lots of methods that apply to all attributes.
But for most things explicit naming is better IMHO

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

From karl.fast at pobox.com  Tue Oct 28 18:38:51 2003
From: karl.fast at pobox.com (Karl Fast)
Date: Tue Oct 28 18:38:56 2003
Subject: [Tutor] generating instance names from a list
In-Reply-To: <003a01c39da9$621011c0$6401a8c0@xp>;
	from alan.gauld@blueyonder.co.uk on Tue, Oct 28, 2003 at
	11:15:31PM -0000
References: <20031027223651.F2605@signal.lights.com>
	<003a01c39da9$621011c0$6401a8c0@xp>
Message-ID: <20031028173851.G1129@signal.lights.com>

> > I've had to resort to this, which seems silly.
> > 
> >   def somefunc(self):
> >       self.alpha = OtherClass()
> >       self.beta  = OtherClass()
> 
> Why is that silly? If you have a fixed set of names this is both
> clear and unambiguous!

AAhh, but you see I don't have a fixed set of names. The program
reads data from a config file and generates objects based on that.
The idea is that I can add a new bit to the config file and viola!,
without editing the code. 

Someone else pointed out how to use setattr, which did the trick.

Thanks.


--karl

From pythontutor at venix.com  Tue Oct 28 19:28:40 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Tue Oct 28 19:28:44 2003
Subject: [Tutor] instantiating subclass by parameter
In-Reply-To: <20031028161001.D1129@signal.lights.com>
References: <20031028120134.Q2605@signal.lights.com>	<3F9EBE2B.5090402@venix.com>	<20031028145814.B1129@signal.lights.com>	<3F9EE582.7080906@venix.com>
	<20031028161001.D1129@signal.lights.com>
Message-ID: <3F9F09B8.9020500@venix.com>

Well, normally you would have your code organized so that there
was an object - other than the module namespace - to hold the names.

There is a function, globals() which provides the dictionary used
for managing the names in the module namespace.  I believe that it
is usually possible to assign values into that dictionary.  However,
the need to do that is an indication that you are using Python to
code some other language.

In other words, if you want to be able to write
	alpha.foo()
then why are you relunctant to write
	alpha = factory('altavista')

If you need to setup some other class to be able to use alpha as a
variable name, then you can use the setattr function on that object
to create the variable alpha initalized to the proper instance of
WebSearch.

I think if you simply do direct assignments for now, as your code evolves,
you'll find a resonable object or container to hold the WebSearch
instances.

I hope that helps.


Karl Fast wrote:

>>Here you need something to hold the objects that you are creating.
>>      create = {'alpha': 'altavista', 'beta': 'alltheweb'}
>>      for key in create:
>>          key = factory(create[key])
> 
> 
> I understand what's going wrong here. I knew it wasn't working and I
> knew why, but thanks for your explanation which confirms it.
> 
> 
> 
>>The folowing code where you use a dictionary named obj to hold the
>>objects with the specified key names (alpha, beta) looks like it
>>should work.
> 
> 
> Yes, it does work (tested it before posting).
> 
> I'm just wondering if there is another way of doing this that would
> give me objects based on the name in the dict, instead of a dict
> holding the objects where the objects are accessible by key.
> 
> That is, instead of accessing the results like this:
> 
>    obj['alpha'].foo() 
>    obj['beta'].name
> 
> I could access them like this:
> 
>    alpha.foo()
>    beta.name()
> 
> The dict solution works. As an exercise in learning python I'm 
> wondering if is another solution that would give me the second
> result.
> 
> In other words, is there a way to change the line that calls factory
> so that it creates the objects alpha and beta.
> 
>    create = {'alpha': 'altavista', 'beta': 'alltheweb'}
>    for key in create:
>         key = factory(create[key])
> 
>    alpha.foo()
> 
>    
> --karl        
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582


From alan.gauld at blueyonder.co.uk  Tue Oct 28 23:52:32 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Tue Oct 28 23:53:03 2003
Subject: [Tutor] instantiating subclass by parameter
References: <20031028120134.Q2605@signal.lights.com><3F9EBE2B.5090402@venix.com>
	<20031028145814.B1129@signal.lights.com>
Message-ID: <006001c39dd8$769419a0$6401a8c0@xp>

> I'd rather have a dict with the desired object names and use that to
> call the factory function. Kinda like this (which doesn't work).
> 
>      create = {'alpha': 'altavista', 'beta': 'alltheweb'}
>      for key in create:
>          key = factory(create[key])


So why not bypass the factory and just do:

classes = {'AltaVista':AltaVista,'WebSearch':WebSearch,...}

a = classes['AltaVista']()
b = classes['WebSearch']()

after all classes are objects too...

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

From karl.fast at pobox.com  Wed Oct 29 00:22:10 2003
From: karl.fast at pobox.com (Karl Fast)
Date: Wed Oct 29 00:22:17 2003
Subject: [Tutor] instantiating subclass by parameter
In-Reply-To: <3F9F09B8.9020500@venix.com>;
	from pythontutor@venix.com on Tue, Oct 28, 2003 at 07:28:40PM
	-0500
References: <20031028120134.Q2605@signal.lights.com>
	<3F9EBE2B.5090402@venix.com>
	<20031028145814.B1129@signal.lights.com>
	<3F9EE582.7080906@venix.com>
	<20031028161001.D1129@signal.lights.com>
	<3F9F09B8.9020500@venix.com>
Message-ID: <20031028232210.I1129@signal.lights.com>

> I think if you simply do direct assignments for now, as your code
> evolves, you'll find a resonable object or container to hold the
> WebSearch instances.

This is the situation. I've got another container which holds
instances of WebSearch. I've used both the dict option and the
setattr technique. Both work nicely. In writing the example I posted
I began to wonder about the other question.

Thanks for all your help.

I was going in the right direction, and now I have a better idea of
the pythonic way of solving things.

Again, thanks.

--karl

From karl.fast at pobox.com  Wed Oct 29 00:27:04 2003
From: karl.fast at pobox.com (Karl Fast)
Date: Wed Oct 29 00:27:08 2003
Subject: [Tutor] instantiating subclass by parameter
In-Reply-To: <006001c39dd8$769419a0$6401a8c0@xp>;
	from alan.gauld@blueyonder.co.uk on Wed, Oct 29, 2003 at
	04:52:32AM -0000
References: <20031028120134.Q2605@signal.lights.com><3F9EBE2B.5090402@venix.com>
	<20031028145814.B1129@signal.lights.com>
	<006001c39dd8$769419a0$6401a8c0@xp>
Message-ID: <20031028232704.J1129@signal.lights.com>

> So why not bypass the factory and just do:
> 
> classes = {'AltaVista':AltaVista,'WebSearch':WebSearch,...}
> 
> a = classes['AltaVista']()
> b = classes['WebSearch']()

Yup, I've done that too.  I've done both solutions, the factory and
a dict style one, like above.

As I learn python some of my perl habits keep coming back. The
there-is-more-than-one-way-to-do-it philosophy is deeply ingrained.

I was just curious to find out if there was another way. 

The answers today have been most helpful. Thanks.


--karl

From jim_938 at hotmail.com  Wed Oct 29 09:13:55 2003
From: jim_938 at hotmail.com (Jimmy verma)
Date: Wed Oct 29 09:13:59 2003
Subject: [Tutor] list permutation!!!
Message-ID: <Sea1-F24OQDygco166v0003620b@hotmail.com>

Hello,

I need some suggestions regarding my problem.

I have n lists and i want to make the possible arrangements out of the 
elements of the lists.

For example:

If i have 3 lists

A = ['1','2']
B = ['3', '4']
C = ['5','6']

Then the combinations are:

'1''3''5'
'1''3''6'
'1''4''5'
'1''4''6'

'2''3''5'
'2''3''6'
'2''4''5'
'2''4''6'

I will wait for the suggestions.


Thanks in advance.

Regards,

J+

_________________________________________________________________
Making your life easy! That is Citibank Suvidha. 
http://server1.msn.co.in/msnleads/citi_cards_sept03/CitiSuvidha.asp Get your 
account now!


From dyoo at hkn.eecs.berkeley.edu  Wed Oct 29 11:43:52 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Oct 29 11:43:57 2003
Subject: [Tutor] List selection
In-Reply-To: <Sea1-F24OQDygco166v0003620b@hotmail.com>
Message-ID: <Pine.LNX.4.44.0310290831580.16648-100000@hkn.eecs.berkeley.edu>



On Wed, 29 Oct 2003, Jimmy verma wrote:

> I need some suggestions regarding my problem.
>
> I have n lists and i want to make the possible arrangements out of the
> elements of the lists.


Hi Jimmy,

Let's call a function that does this 'arrangements()' so we have something
solid to talk about.  *grin*

What does it mean to do a possible arrangement() of 1 list?  What does:

    arrangements([ [1, 2, 3] ])

give us?

And if we have just two lists (n=2), how would we make all possible
arrangements of those two lists?


Try the "simple" cases first and show us what you get --- they may help
make it easier to tackle the more general 'n lists' problem.


From dyoo at hkn.eecs.berkeley.edu  Wed Oct 29 11:56:01 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Oct 29 11:56:25 2003
Subject: [Tutor] "idle" problem
In-Reply-To: <003001c39cf8$fa950b00$3cac590c@welcome>
Message-ID: <Pine.LNX.4.44.0310290847130.16648-100000@hkn.eecs.berkeley.edu>



On Mon, 27 Oct 2003, Partha Sur wrote:

> I am unable to use "idle" development environment for Python.
>
> When I invoke idle from the Linux prompt I get the following error
> message:

Hi Partha,

Sorry for the long delay in replying!  It looks like none of us have run
into this problem before, so I think that's why you're not getting good
answers from us.


> I added the following to my .profile
> PATH=$PATH:/usr/lib/python2.2/site-packages/idle:.
> to invoke idle directly from my home Linux prompt.

Are you sure you need to do this?  What happens if you execute IDLE using
an explicit absolute path?



> When I first invoked idle from my Linux prompt I got the following error
> message: "Import Error: No module named idlelib"
>
> So I then modified the idle script in the
> /usr/lib/python2.2/site-packages/idle

> # import modified by Partha Sur 9/22/2003
> # to suppress "ImportError : No module named idlelib"
> # import IdleConf and PyShell directly - there is no idlelib on this system
>
> import os
> import sys
> #from idlelib import IdleConf  <=  I commented this out
> import IdleConf

Yikes.  I'm not sure if this is valid to do.  If there's no idlelib on
your system, that's an indication that you have a broken version of IDLE
on your system.  Just modifying a file to make the ImportError go away is
probably not enough.

Let's see if a new version of IDLE will fix the problem.  Have you tried
using IDLEFork?

    http://sourceforge.net/project/showfiles.php?group_id=9579

It's the improved version of IDLE that Python 2.3 is using now.  I believe
it should work in 2.2, so you may want to see if it works for you.

Also, I'd recommend first seeing if it works by using the absolute
pathname.  Get it working first, and then you can concentrate on adding it
to your PATH.


Good luck to you!


From dyoo at hkn.eecs.berkeley.edu  Wed Oct 29 12:08:24 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Oct 29 12:08:31 2003
Subject: [Tutor] instantiating subclass by parameter
In-Reply-To: <20031028232704.J1129@signal.lights.com>
Message-ID: <Pine.LNX.4.44.0310290857020.16648-100000@hkn.eecs.berkeley.edu>



> > So why not bypass the factory and just do:
> >
> > classes = {'AltaVista':AltaVista,'WebSearch':WebSearch,...}
> >
> > a = classes['AltaVista']()
> > b = classes['WebSearch']()
>
> Yup, I've done that too.  I've done both solutions, the factory and
> a dict style one, like above.

Hi Karl,

By the way, we can see a concrete example of this 'plugin' style system in
the Standard Library.


The 'codecs' library works by keeping a module-level dictionary of all the
encodings that it knowns about, and whenever we do something like:

    'foobar'.encode('utf-8')

it envokes the codecs system, which looks up an instance of a UTF-8
encoder from that internal dictionary.  Their system is a bit more
sophisticated, but its essence is similar to what you're doing.

    http://www.python.org/doc/lib/module-codecs.html


Another example of a plugin-style system is in xml.sax() --- its
make_parser() function is a "factory" that returns XMLReader objects.

    http://www.python.org/doc/lib/module-xml.sax.html



> As I learn python some of my perl habits keep coming back. The
> there-is-more-than-one-way-to-do-it philosophy is deeply ingrained.

Not necessarily a bad thing.  *grin*


Good luck to you!


From midgley at linuxmail.org  Wed Oct 29 15:01:12 2003
From: midgley at linuxmail.org (paul midgley)
Date: Wed Oct 29 15:01:19 2003
Subject: [Tutor] Tutor summary
Message-ID: <20031029200112.3222.qmail@linuxmail.org>

Hello

Is there a FAQ from the tutor email group and where can I go to download it.

Regards

Paul
-- 
______________________________________________
Check out the latest SMS services @ http://www.linuxmail.org 
This allows you to send and receive SMS through your mailbox.


Powered by Outblaze

From project5 at redrival.net  Wed Oct 29 16:02:51 2003
From: project5 at redrival.net (Andrei)
Date: Wed Oct 29 16:08:47 2003
Subject: [Tutor] Re: Tutor summary
References: <20031029200112.3222.qmail@linuxmail.org>
Message-ID: <1pa0qttjhjb4.1fgsssil6vrzu$.dlg@40tude.net>

paul midgley wrote on Wed, 29 Oct 2003 20:01:12 +0000:

Hi,

> Is there a FAQ from the tutor email group and where can I go to download it.

I don't know of any specific python-tutor list, but the official Python
faqs contain a lot of questions which are popular here too:

http://python.org/doc/faq/

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V
ernq gur yvfg, fb gurer'f ab arrq gb PP.


From mlong at datalong.com  Wed Oct 29 16:14:06 2003
From: mlong at datalong.com (mlong@datalong.com)
Date: Wed Oct 29 16:14:17 2003
Subject: [Tutor] Split string and convert to int
In-Reply-To: <Pine.LNX.4.44.0310290857020.16648-100000@hkn.eecs.berkeley.edu>
References: <20031028232704.J1129@signal.lights.com> 
	<Pine.LNX.4.44.0310290857020.16648-100000@hkn.eecs.berkeley.edu>
Message-ID: <.68.160.0.89.1067462046.squirrel@datalong.com>

Hi,

I have a string variable that represents a date. I want to pull out the
individual parts as integers. Is there a more efficient way to do this?

fooDate='10/3/2003'

month, day, year = fooDate.split('/')
month=int(month)
day=int(day)
year=int(year)


Thanks,
Mike

From pythontutor at venix.com  Wed Oct 29 16:51:11 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Wed Oct 29 16:51:19 2003
Subject: [Tutor] Split string and convert to int
In-Reply-To: <.68.160.0.89.1067462046.squirrel@datalong.com>
References: <20031028232704.J1129@signal.lights.com>
	<Pine.LNX.4.44.0310290857020.16648-100000@hkn.eecs.berkeley.edu>
	<.68.160.0.89.1067462046.squirrel@datalong.com>
Message-ID: <3FA0364F.8050206@venix.com>

month, day, year = [int(x) for x in fooDate.split('/')]

is more compact and pretty clear.  another alternative is:

month, day, year = map(int, fooDate.split('/'))

Most of the time I think the first approach using list comprehensions
is your best bet.

mlong@datalong.com wrote:

> Hi,
> 
> I have a string variable that represents a date. I want to pull out the
> individual parts as integers. Is there a more efficient way to do this?
> 
> fooDate='10/3/2003'
> 
> month, day, year = fooDate.split('/')
> month=int(month)
> day=int(day)
> year=int(year)
> 
> 
> Thanks,
> Mike
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582


From sigurd at 12move.de  Wed Oct 29 16:53:13 2003
From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=)
Date: Wed Oct 29 16:56:13 2003
Subject: [Tutor] Split string and convert to int
In-Reply-To: <.68.160.0.89.1067462046.squirrel@datalong.com>
	(mlong@datalong.com's
	message of "Wed, 29 Oct 2003 16:14:06 -0500 (EST)")
References: <20031028232704.J1129@signal.lights.com>
	<Pine.LNX.4.44.0310290857020.16648-100000@hkn.eecs.berkeley.edu>
	<.68.160.0.89.1067462046.squirrel@datalong.com>
Message-ID: <m3brrzyapc.fsf@hamster.pflaesterer.de>

An unnamed person wrote:

> I have a string variable that represents a date. I want to pull out the
> individual parts as integers. Is there a more efficient way to do this?

> fooDate='10/3/2003'

> month, day, year = fooDate.split('/')
> month=int(month)
> day=int(day)
> year=int(year)

In [9]: fooDate='10/3/2003'

In [10]: [month, day, year] = map(int, fooDate.split('/'))

In [11]: #or

In [12]: [month, day, year] = [int(x) for x in fooDate.split('/')]


But in that case I would prefer map.

   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


From littledanehren at yahoo.com  Wed Oct 29 17:25:21 2003
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Wed Oct 29 17:28:21 2003
Subject: [Tutor] Python vs. Ruby
Message-ID: <20031029222521.7732.qmail@web41810.mail.yahoo.com>

What are the advantages of Python over Ruby? They both
look pretty good sytactically. Python seems slightly
more readable, but that's probably just because I know
Python. Ruby does have annoying end keywords, but in
Python, you have to write "self." before every
variable within a class, whereas in Ruby you just
prefix it with "$". Ruby typically writes shorter
code, and I think that's pretty important (it's
partially why I chose Python).
Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Exclusive Video Premiere - Britney Spears
http://launch.yahoo.com/promos/britneyspears/

From glingl at aon.at  Wed Oct 29 18:03:43 2003
From: glingl at aon.at (Gregor Lingl)
Date: Wed Oct 29 18:05:47 2003
Subject: [Tutor] Python vs. Ruby
In-Reply-To: <20031029222521.7732.qmail@web41810.mail.yahoo.com>
References: <20031029222521.7732.qmail@web41810.mail.yahoo.com>
Message-ID: <3FA0474F.9040404@aon.at>

Daniel Ehrenberg schrieb:

>What are the advantages of Python over Ruby? 
>
Hi Daniel!

About two month ago Alex Martelli posted some very
informative thoughts on this theme (or vice versa?)
at comp.lang.python:

 http://groups.google.com/groups?selm=bhqr78021hp%40enews1.newsguy.com

 From there you can follow the whole thread of 248(!) contributions ... ;-)

Regards,
Gregor

>They both
>look pretty good sytactically. Python seems slightly
>more readable, but that's probably just because I know
>Python. Ruby does have annoying end keywords, but in
>Python, you have to write "self." before every
>variable within a class, whereas in Ruby you just
>prefix it with "$". Ruby typically writes shorter
>code, and I think that's pretty important (it's
>partially why I chose Python).
>Daniel Ehrenberg
>
>__________________________________
>Do you Yahoo!?
>Exclusive Video Premiere - Britney Spears
>http://launch.yahoo.com/promos/britneyspears/
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>
>  
>


From zak at harlekin-maus.com  Wed Oct 29 18:12:46 2003
From: zak at harlekin-maus.com (Zak Arntson)
Date: Wed Oct 29 18:12:53 2003
Subject: [Tutor] Module Packages
Message-ID: <3539.192.207.104.221.1067469166.squirrel@webmail.harlekin-maus.com>

I'm writing a Python roguelike (in Pygame, whee!), and have started
splitting my initial file up into multiple files. So I figured this would
be a good time to learn about packages.

In the one-file format, I have the following classes (well, I have more,
but these are the relevant ones):

class Entity
class Player(Entity)
class Zombie(Entity)
class Game

Now, game makes use of both the Player and the Zombie classes, by creating
instances of both. Ideally, I'd like to separate things into subitems:

/Pyrl
    /Entity
        Entity.py
        Player.py
        /Monster
            Zombie.py
    Game.py

First question, then, is this a properly done package structure? I'd like
to be able to do the following:
    plr = Entity.Player()
    zom1 = Entity.Monster.Zombie()
    zom2 = Entity.Monster.Zombie()

But it looks like I'll have to:
    plr = Entity.Player.Player()
    zom1 = Entity.Monster.Zombie.Zombie()
    zom2 = Entity.Monster.Zombie.Zombie()

Is there anyway to avoid the "double-referencing"? Or am I going about my
package organization all wrong?

---
Zak Arntson
www.harlekin-maus.com - Games - Lots of 'em

From project5 at redrival.net  Wed Oct 29 19:07:31 2003
From: project5 at redrival.net (Andrei)
Date: Wed Oct 29 19:09:48 2003
Subject: [Tutor] Re: Python vs. Ruby
References: <20031029222521.7732.qmail@web41810.mail.yahoo.com>
Message-ID: <63m5ymum4am1.n5hzjz3ncyet$.dlg@40tude.net>

Daniel Ehrenberg wrote on Wed, 29 Oct 2003 14:25:21 -0800 (PST):

> What are the advantages of Python over Ruby? They both
> look pretty good sytactically. Python seems slightly
> more readable, but that's probably just because I know
> Python. Ruby does have annoying end keywords, but in
> Python, you have to write "self." before every
> variable within a class, whereas in Ruby you just

Not if you don't want that variable to stick around for very long :).

> prefix it with "$". 

I too have looked at Ruby (and I still look at it :)), not very long after
I started Python, so my view of it is not that of an expert, nor that of
someone who already knew Python before trying Ruby. Python won, despite the
two languages being quite similar for most practical purposes as far as I
can tell.

It's true that you don't have to do that self. stuff (though in python you
can use e.g. s. if self. is too long for you), but I don't think the use of
@, @@ and $ is an improvement at all. In fact, being a touch typist, I
think I can type "self." just as fast as or faster than "@" and I'm sure I
can type "s." faster than "@". Plus those annoying ends in Ruby that you
already mentioned. What I really liked in Ruby was that you can change the
built-in types, so that e.g. adding two integers would return their average
(or whatever). Obviously this is very cool, but not particularly useful I'd
think.

Ruby however has some large disadvantages on the tutorials/tools field as
far as I can tell. The Python standard library and additional modules/tools
are simply amazing. Not that Ruby doesn't have anything, but Python has so
much more. Zope, wxPython, PyQt, PyGame, lots of tutorials for all levels,
lots of good editors/tools (Spe, Boa, wxGlade, PyCrust - hm... that all
kinda depends on wxWindows :), PythonWin). 
For ruby I found one Windows-only solution called RDE which is pretty good,
but is programmed by someone who apparently doesn't know a lot about
interface design and one called FreeRide which looks nice, but is rather
buggy and a bit lacking in the recent releases department. 

Python docs are a lot better too, especially the ones in the ActiveState
distro; the there isn't even a "docs" entry in my Ruby program group!
Another advantage is that the whole of Python is quite English-oriented,
while a lot of Ruby stuff is still in Japanese only (at least I presume
it's Japanese), or really broken English. 

You'll also find Python in more places than Ruby. From the Jython
interpreter embedded in e.g. Jedit to Jasc software that uses Python for
scripting. So Python knowledge has the potential to help you in more places
than Ruby knowledge.

Another diff seems to be that Python is faster than Ruby. Not that it
really matters in scripting languages, but thought I should mention it :).
Saw that on some language shootout page.

> Ruby typically writes shorter
> code, and I think that's pretty important (it's
> partially why I chose Python).

If you like that, you should see Perl. I've been told it can solve the
mystery of Life, The Universe and Everything in just one byte of code :).

Nevertheless, Ruby does seem like a nice language and if Python wasn't
around, I'd probably hang around on the ruby-tutor list now (oh, wait, that
doesn't exist :)).

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V
ernq gur yvfg, fb gurer'f ab arrq gb PP.


From dyoo at hkn.eecs.berkeley.edu  Wed Oct 29 19:28:52 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Oct 29 19:28:58 2003
Subject: [Tutor] Re: Python vs. Ruby  [where to find more about Ruby]
In-Reply-To: <63m5ymum4am1.n5hzjz3ncyet$.dlg@40tude.net>
Message-ID: <Pine.LNX.4.44.0310291615030.20823-100000@hkn.eecs.berkeley.edu>



> Python docs are a lot better too, especially the ones in the ActiveState
> distro; the there isn't even a "docs" entry in my Ruby program group!
> Another advantage is that the whole of Python is quite English-oriented,
> while a lot of Ruby stuff is still in Japanese only (at least I presume
> it's Japanese), or really broken English.

Hi Andrei,

There are some good Ruby books out there.  In fact, the folks who wrote
"The Pragmatic Programmer" have released their own Ruby book online:

    http://www.rubycentral.com/book/index.html

Hmmm... but I'd better balance my karma by providing a link to a nice
online Python book too.  *grin*

    http://diveintopython.org/


> Nevertheless, Ruby does seem like a nice language and if Python wasn't
> around, I'd probably hang around on the ruby-tutor list now (oh, wait,
> that doesn't exist :)).

I haven't been able to find an explicit Ruby-tutor mailing list, but I'm
sure that the ruby-talk mailing list at:

    http://www.ruby-lang.org/en/20020104.html

is well suited for asking general Ruby learning questions.


Good luck to you!


From tbstep at tampabay.rr.com  Wed Oct 29 19:59:03 2003
From: tbstep at tampabay.rr.com (Todd Stephens)
Date: Wed Oct 29 19:59:58 2003
Subject: [Tutor] Re: Python vs. Ruby
In-Reply-To: <63m5ymum4am1.n5hzjz3ncyet$.dlg@40tude.net>
References: <20031029222521.7732.qmail@web41810.mail.yahoo.com>
	<63m5ymum4am1.n5hzjz3ncyet$.dlg@40tude.net>
Message-ID: <200310291959.03556.tbstep@tampabay.rr.com>

On Wednesday 29 October 2003 07:07 pm, Andrei wrote:
>  Nevertheless, Ruby does seem like a nice language and if Python
> wasn't around, I'd probably hang around on the ruby-tutor list now
> (oh, wait, that doesn't exist :)).

Without a doubt, Python has the strongest community of any language I 
have seen.  Sure, others like Lisp have ardent supporters, but even 
that community is fractured (and not nearly as supportive of 
beginners).  

While community is obviously no reason to choose a programming language 
to use for a particular project, I think it is a big factor in bringing 
in new people to the language (and subsequently increasing usage of the 
language all over the world).

-- 
Todd Stephens
"Good people do not need laws to tell them to act responsibly, 
while bad people will find a way around the laws." - Plato


From littledanehren at yahoo.com  Wed Oct 29 20:09:57 2003
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Wed Oct 29 20:10:01 2003
Subject: [Tutor] Re: Question on Reading a Directory
In-Reply-To: <fm6c0ob0ikcc$.qzcvwm8yovja.dlg@40tude.net>
Message-ID: <20031030010957.44812.qmail@web41810.mail.yahoo.com>

> wxPython doesn't really include an IDE, does it? A
> simple editor perhaps.
> Spe is the only wxPython-based IDE I know (pretty
> good too).

I don't like Spe. Very complicated, but the features
aren't useful. I prefer PyShell and PyAlaCarte, which
I *thought* were IDEs and come with wxPython.
Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Exclusive Video Premiere - Britney Spears
http://launch.yahoo.com/promos/britneyspears/

From project5 at redrival.net  Wed Oct 29 20:14:22 2003
From: project5 at redrival.net (Andrei)
Date: Wed Oct 29 20:16:40 2003
Subject: [Tutor] Re: Re: Python vs. Ruby  [where to find more about Ruby]
References: <63m5ymum4am1.n5hzjz3ncyet$.dlg@40tude.net>
	<Pine.LNX.4.44.0310291615030.20823-100000@hkn.eecs.berkeley.edu>
Message-ID: <x31bvaepk7uh$.19ud307iy4cws$.dlg@40tude.net>

Danny Yoo wrote on Wed, 29 Oct 2003 16:28:52 -0800 (PST):

>> Python docs are a lot better too, especially the ones in the ActiveState
>> distro; the there isn't even a "docs" entry in my Ruby program group!
>> Another advantage is that the whole of Python is quite English-oriented,
>> while a lot of Ruby stuff is still in Japanese only (at least I presume
>> it's Japanese), or really broken English.
> 
> Hi Andrei,
> 
> There are some good Ruby books out there.  In fact, the folks who wrote
> "The Pragmatic Programmer" have released their own Ruby book online:
> 
>     http://www.rubycentral.com/book/index.html

Yep, I know that one - it's the one I used/use to look into ruby (I can't
help being fascinated by the language, despite a definite feeling that I'll
never actually use it). It comes with the Windows distro too. But it's not
a ruby documentation. Ok, let's be fair, there is a docs dir, but that only
contains a limited number of subdirs which in turn contain a mix of text,
html and rb files, of varying quality and layout. No centralized index, no
library index, nothing that I can see.

The book also doesn't quite fit my style of learning (trying to be too
academically correct I think, while I'm more a fan of a pragmatic approach,
learning to walk before you learn to run and all that). This is in stark
contrast with the numerous excellent Python tutorials (you mentioned Dive
into Python, but How to think like a Comp. Sci. and Alan Gauld's and the
default Python tutorial are all quite good), not to mention the Instant
Hacking on hetland.org and the Python Quick Reference (which is not quite a
tutorial, but is still quite useful).

> I haven't been able to find an explicit Ruby-tutor mailing list, but I'm
> sure that the ruby-talk mailing list at:
> 
>     http://www.ruby-lang.org/en/20020104.html
> 
> is well suited for asking general Ruby learning questions.

I know that one too. But it has the disadvantage of being quite
high-volume, meaning there's a lot of "noise" which is not that interesting
to beginners. The python-tutor list is much quieter. I suspect that in
time, as ruby gets more popular, the 'issues' I mentioned will disappear.
But by that time Python will be faster than C or will be able to read your
thoughts and produce programs accordingly or something, and switching to
Ruby still won't be tempting :).

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V
ernq gur yvfg, fb gurer'f ab arrq gb PP.


From project5 at redrival.net  Wed Oct 29 20:25:39 2003
From: project5 at redrival.net (Andrei)
Date: Wed Oct 29 20:27:57 2003
Subject: [Tutor] Re: Re: Question on Reading a Directory
References: <fm6c0ob0ikcc$.qzcvwm8yovja.dlg@40tude.net>
	<20031030010957.44812.qmail@web41810.mail.yahoo.com>
Message-ID: <e1hu6cdor8tk$.16s5401okddqv.dlg@40tude.net>

Daniel Ehrenberg wrote on Wed, 29 Oct 2003 17:09:57 -0800 (PST):

>> wxPython doesn't really include an IDE, does it? A
>> simple editor perhaps.
>> Spe is the only wxPython-based IDE I know (pretty
>> good too).
> 
> I don't like Spe. Very complicated, but the features
> aren't useful. I prefer PyShell and PyAlaCarte, which

Matter of taste I suppose. I use SciTE for small things, but for larger
stuff I really want a class browser, and my folds to stay folded when I
switch to a different file - that would be Spe then. I use PyCrust as
shell.

> I *thought* were IDEs and come with wxPython.

PyAlaCarte is a quite simple editor. It lacks even basic features that I
really want when editing Python code, like auto-indenting after ":" and
code folding or block commenting; I wouldn't call it an IDE. SciTE has the
same light feel to it as PyAlaCarte, but a lot more power in case you need
it. But of course, to each his own :).

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V
ernq gur yvfg, fb gurer'f ab arrq gb PP.


From mlong at datalong.com  Wed Oct 29 21:25:19 2003
From: mlong at datalong.com (mlong@datalong.com)
Date: Wed Oct 29 21:28:17 2003
Subject: [Tutor] Split string and convert to int
In-Reply-To: <m3brrzyapc.fsf@hamster.pflaesterer.de>
References: <20031028232704.J1129@signal.lights.com><Pine.LNX.4.44.0310290857020.1
	6648-100000@hkn.eecs.berkeley.edu><.68.160.0.89.1067462046.squirrel@da
	talong.com> <m3brrzyapc.fsf@hamster.pflaesterer.de>
Message-ID: <.151.199.43.9.1067480719.squirrel@datalong.com>

Thanks for the responses. Having the example using map has helped me to
finally understand what it does. I had read about the map function in the
docs but did not fully get it until now. I would like a little more
clarification however. Lloyd prefers using list comprehension and Karl
prefers the map function. Is this difference due to personal preference,
or are there some other technical reasons for using one over the other.

Thanks,
Mike

> An unnamed person wrote:
>
>> I have a string variable that represents a date. I want to pull out the
>> individual parts as integers. Is there a more efficient way to do this?
>
>> fooDate='10/3/2003'
>
>> month, day, year = fooDate.split('/')
>> month=int(month)
>> day=int(day)
>> year=int(year)
>
> In [9]: fooDate='10/3/2003'
>
> In [10]: [month, day, year] = map(int, fooDate.split('/'))
>
> In [11]: #or
>
> In [12]: [month, day, year] = [int(x) for x in fooDate.split('/')]
>
>
> But in that case I would prefer map.
>
>    Karl
> --
> Please do *not* send copies of replies to me.
> I read the list
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>


From carroll at tjc.com  Wed Oct 29 21:35:43 2003
From: carroll at tjc.com (Terry Carroll)
Date: Wed Oct 29 21:35:47 2003
Subject: [Tutor] Activestate Python 2.3
Message-ID: <Pine.LNX.4.44.0310291831560.15552-100000@violet.rahul.net>

I know some members, like me, have been waiting for Activestate to move to 
Python 2.3.  Just a heads-up, they've done it.  You can now download 2.3.2
from the Activestate web site.

http://www.activestate.com/Products/ActivePython/

I haven't downloaded or installed it yet, because I have too much going on
this week; just passing on the info from the ActivePython mailing list.

-- 
Terry Carroll
Santa Clara, CA
carroll@tjc.com 


From project5 at redrival.net  Wed Oct 29 21:47:27 2003
From: project5 at redrival.net (Andrei)
Date: Wed Oct 29 21:49:46 2003
Subject: [Tutor] Re: Split string and convert to int
References: <20031028232704.J1129@signal.lights.com><Pine.LNX.4.44.0310290857020.1
	6648-100000@hkn.eecs.berkeley.edu><.68.160.0.89.1067462046.squirrel@da
	talong.com> <m3brrzyapc.fsf@hamster.pflaesterer.de>
	<1719.93020126155$1067480806@news.gmane.org>
Message-ID: <1e0edwxjou653$.2cr6ozfutbmu$.dlg@40tude.net>

mlong@datalong.com wrote on Wed, 29 Oct 2003 21:25:19 -0500 (EST):

> Thanks for the responses. Having the example using map has helped me to
> finally understand what it does. I had read about the map function in the
> docs but did not fully get it until now. I would like a little more
> clarification however. Lloyd prefers using list comprehension and Karl
> prefers the map function. Is this difference due to personal preference,
> or are there some other technical reasons for using one over the other.

There are probably speed differences between the two, but nothing you'd
notice for such small amounts of numbers. I don't know which would be
fastest when used to convert many numbers. 
Another difference is that the map() solution requires less typing.
GvR (that's the guy who wrote/writes Python) prefers list comprehensions if
I'm not mistaken, so that makes them more pythonic :).

What it comes down to in this case is probably taste. I would take the
comprehension over the map because I like list comprehensions better than
map, but if this code needed good performance, I'd test the two solutions
and pick the fastest one.

Andrei

>> An unnamed person wrote:
>>
>>> I have a string variable that represents a date. I want to pull out the
>>> individual parts as integers. Is there a more efficient way to do this?
>>
>>> fooDate='10/3/2003'
>>
>>> month, day, year = fooDate.split('/')
>>> month=int(month)
>>> day=int(day)
>>> year=int(year)
>>
>> In [9]: fooDate='10/3/2003'
>>
>> In [10]: [month, day, year] = map(int, fooDate.split('/'))
>>
>> In [11]: #or
>>
>> In [12]: [month, day, year] = [int(x) for x in fooDate.split('/')]
>>
>>
>> But in that case I would prefer map.
>>
>>    Karl
>> --
>> Please do *not* send copies of replies to me.
>> I read the list


From pythontutor at venix.com  Wed Oct 29 22:11:44 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Wed Oct 29 22:11:49 2003
Subject: [Tutor] Split string and convert to int
In-Reply-To: <.151.199.43.9.1067480719.squirrel@datalong.com>
References: <20031028232704.J1129@signal.lights.com><Pine.LNX.4.44.0310290857020.1	6648-100000@hkn.eecs.berkeley.edu><.68.160.0.89.1067462046.squirrel@da	talong.com>
	<m3brrzyapc.fsf@hamster.pflaesterer.de>
	<.151.199.43.9.1067480719.squirrel@datalong.com>
Message-ID: <3FA08170.7020502@venix.com>

I started a reply saying it didn't really matter, but changed my mind.  I should
have sent it.

My main code reviewer doesn't care for map/filter, but does like the
list comprehensions.  I find it easy to see the implied loops of list
comprehensions when scanning through programs.  map is easier to overlook.

Keep your code somewhat consistent and find what works for you.

David Mertz has a lot of useful recommendations in his book:
http://gnosis.cx/TPiP/
Text Processing in Python (a book)

Chapter one covers aspects of functional programming and uses map and filter
quite extensively.  Also read some of David Mertz's Charming Python columns.

mlong@datalong.com wrote:
> Thanks for the responses. Having the example using map has helped me to
> finally understand what it does. I had read about the map function in the
> docs but did not fully get it until now. I would like a little more
> clarification however. Lloyd prefers using list comprehension and Karl
> prefers the map function. Is this difference due to personal preference,
> or are there some other technical reasons for using one over the other.
> 
> Thanks,
> Mike
> 
> 
>>An unnamed person wrote:
>>
>>
>>>I have a string variable that represents a date. I want to pull out the
>>>individual parts as integers. Is there a more efficient way to do this?
>>
>>>fooDate='10/3/2003'
>>
>>>month, day, year = fooDate.split('/')
>>>month=int(month)
>>>day=int(day)
>>>year=int(year)
>>
>>In [9]: fooDate='10/3/2003'
>>
>>In [10]: [month, day, year] = map(int, fooDate.split('/'))
>>
>>In [11]: #or
>>
>>In [12]: [month, day, year] = [int(x) for x in fooDate.split('/')]
>>
>>
>>But in that case I would prefer map.
>>
>>   Karl
>>--
>>Please do *not* send copies of replies to me.
>>I read the list
>>
>>
>>_______________________________________________
>>Tutor maillist  -  Tutor@python.org
>>http://mail.python.org/mailman/listinfo/tutor
>>
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582


From mlong at datalong.com  Wed Oct 29 23:24:14 2003
From: mlong at datalong.com (mlong@datalong.com)
Date: Wed Oct 29 23:24:25 2003
Subject: [Tutor] Split string and convert to int
In-Reply-To: <3FA08170.7020502@venix.com>
References: <20031028232704.J1129@signal.lights.com><Pine.LNX.4.44.0310290857020.1
	6648-100000@hkn.eecs.berkeley.edu><.68.160.0.89.1067462046.squirrel@d
	a	talong.com><m3brrzyapc.fsf@hamster.pflaesterer.de><.151.199.43.9.106
	7480719.squirrel@datalong.com> <3FA08170.7020502@venix.com>
Message-ID: <.151.199.43.9.1067487854.squirrel@datalong.com>

> I started a reply saying it didn't really matter, but changed my mind.  I
> should
> have sent it.

Excellent...my curiosity has been satisfied :)

From alan.gauld at blueyonder.co.uk  Thu Oct 30 03:43:36 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Thu Oct 30 03:43:34 2003
Subject: [Tutor] Split string and convert to int
References: <20031028232704.J1129@signal.lights.com>
	<Pine.LNX.4.44.0310290857020.16648-100000@hkn.eecs.berkeley.edu>
	<.68.160.0.89.1067462046.squirrel@datalong.com>
Message-ID: <00a701c39ec1$e8b63d80$6401a8c0@xp>

> fooDate='10/3/2003'
> 
> month, day, year = fooDate.split('/')
> month=int(month)
> day=int(day)
> year=int(year)

month,day,year = map(int,fooDate.split('/'))

But your method isn't that bad IMHO.

Alan G.

From alan.gauld at blueyonder.co.uk  Thu Oct 30 03:54:21 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Thu Oct 30 03:54:18 2003
Subject: [Tutor] Module Packages
References: <3539.192.207.104.221.1067469166.squirrel@webmail.harlekin-maus.com>
Message-ID: <00b401c39ec3$694a8a90$6401a8c0@xp>

> In the one-file format, I have the following classes

If you mean by one-file format that you have one
class per file, can I ask why? If the classes are
related its usually better to keep them together IMHO.

> Now, game makes use of both the Player and the Zombie classes, by
creating
> instances of both. Ideally, I'd like to separate things into
subitems:
>
> /Pyrl
>     /Entity
>         Entity.py
>         Player.py
>         /Monster
>             Zombie.py
>     Game.py

Why separate Monsters from other Entities? And why
separate Entities at all, why not just two modules, one
for the Entities and another for the Game itself.

Presumably you might reuse the Entity module but less
likely to reuse the game?

> First question, then, is this a properly done package structure? I'd
like
> to be able to do the following:
>     plr = Entity.Player()
> But it looks like I'll have to:
>     plr = Entity.Player.Player()

Exactly, its easier to use the module to hold all the class
definitions. Fine grained file structures tend to be used
in things like C++ and Java as a mechanism for controlling
compilation times, but they add a lot of undue complexity
to a project in my experience.

> Is there anyway to avoid the "double-referencing"? Or am I going
about my
> package organization all wrong?

I think you should build your module structure based on
the groups of reuse in your code, not the individual classes.
If a bunch of classes are likely to be reused together put
it in a single module.

Alan G.


From alan.gauld at blueyonder.co.uk  Thu Oct 30 04:06:55 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Thu Oct 30 04:06:58 2003
Subject: [Tutor] Python vs. Ruby
References: <20031029222521.7732.qmail@web41810.mail.yahoo.com>
Message-ID: <00c101c39ec5$2aaa5de0$6401a8c0@xp>


> What are the advantages of Python over Ruby? They both
> look pretty good sytactically. 

The only real reasons I stuck to Python after learning 
Ruby were:

1) I hate languages that stick prefixes ($,@,@@ etc) in 
front of variables.

2) I hate languages that insist on everything being an object. 
I've used OO long enough to know there are times when it 
ain't the best answer...

3) The support in terms of number of books, newgroups/mailing 
lists, libraries, tools etc is much better. The communities 
are both very friendly and supportive but there is just so 
much more for python.

However Ruby does offer some nice features that Python lacks
(code blocks for example) but Python is catching up (it has 
added iterators and generators and new style classes since 
then...

> Ruby does have annoying end keywords, 

I can live with those. :-)

> Python, you have to write "self." before every
> variable within a class, whereas in Ruby you just
> prefix it with "$". 

Personally I find 'self' clearer. But then I do that 
in C++ and Java to - using 'this' of course!

> Ruby typically writes shorter code, and I think that's 
> pretty important 

Really? I hadn't noticed. It can't be very much shorter.
I'd think its a little like Java vv C++, it depends on the 
problem domain as much as the language. Java is usually 
cited as being shorter than C++ but in every significant 
program I've written using both  C++ is shorter! Ruby 
didn't *feel* shorter than Python to me - but I never 
thought to compare them directly.

Alan G.

From zak at harlekin-maus.com  Thu Oct 30 09:37:20 2003
From: zak at harlekin-maus.com (Zak Arntson)
Date: Thu Oct 30 09:37:28 2003
Subject: [Tutor] Module Packages
In-Reply-To: <00b401c39ec3$694a8a90$6401a8c0@xp>
References: <3539.192.207.104.221.1067469166.squirrel@webmail.harlekin-maus.com>
	<00b401c39ec3$694a8a90$6401a8c0@xp>
Message-ID: <3354.4.62.178.63.1067524640.squirrel@webmail.harlekin-maus.com>

>> In the one-file format, I have the following classes
>
> If you mean by one-file format that you have one
> class per file, can I ask why? If the classes are
> related its usually better to keep them together IMHO.

Sorry, I meant the entire program was in one file. It finally became
unmanageable and I wanted to break it up.

> Why separate Monsters from other Entities? And why
> separate Entities at all, why not just two modules, one
> for the Entities and another for the Game itself.

It's to ease the addition of new monsters. I'd like to be able to add
monsters very easily, so I'd like each one to be dealt with in its own
file. I'm planning on having about 52 different monsters (probably more),
so I don't want them all in the same file.

> Presumably you might reuse the Entity module but less
> likely to reuse the game?

Yes. I will reuse the Entity module a ton. It is the basis for monsters,
players, traps, special effects, anything that has a presence in the game.

> Exactly, its easier to use the module to hold all the class
> definitions. Fine grained file structures tend to be used
> in things like C++ and Java as a mechanism for controlling
> compilation times, but they add a lot of undue complexity
> to a project in my experience.

Right, but it's not to control compilation, it's to coding easier. Easier
to find a monster, and easier to add a new one.

> Alan G.

I hope I've made more sense of what I want to do. My eventual goal is to
make adding new features as easy as plopping in a .py file (say, for a
monster or a new level-building algorithm), and make it easier to find a
specific section of code. Going from just that, what would you recommend?

---
Zak Arntson
www.harlekin-maus.com - Games - Lots of 'em

From ATrautman at perryjudds.com  Thu Oct 30 10:34:20 2003
From: ATrautman at perryjudds.com (Alan Trautman)
Date: Thu Oct 30 10:34:30 2003
Subject: [Tutor] Module Packages
Message-ID: <06738462136C054B8F8872D69DA140DB01C08B20@corp-exch-1.pjinet.com>

Warning a hunk of theory here read on at your discretion.

Zak,

I too am working on a really similar type thing. I don't know if this will
help but it addresses some of the concerns about handling. I XML'ed it
partially for the experience and partially for the reasons you mention.

I decided there should be a master file of monsters. Each area would have
its own monsters. These would be kept in an XML file with directions to the
image map, name, info, damage etc... To add a general monster append it to
the xml file, to add a monster to a dungeon add it to the local monster
file. I use a folder for each adventure area. 

This way I only need on monster handler for the whole game. It just needs to
be pointed to the correct xml file to get the monster. More importantly it
means the user only has to create a profile to add a monster. Additionally
using xml format means that not every monster has a record for every
possible action: rats don't need have documentation about their magic
ability. The problem is being the programmer you have to provide an action
script with enough flexibility to allow neat new monsters to be created.

This is also the way I document the world and adventure areas.

The huge advantage/disadvantage to this method is of course speed unless you
preload a huge amount into memory. I will never program a thumb speed game
so I this this is an advantage because I can program rich environment vs.
speed.

Ok, wow that's a lot. I'm interested to see what people say.

Alan


>> In the one-file format, I have the following classes
>
> If you mean by one-file format that you have one
> class per file, can I ask why? If the classes are
> related its usually better to keep them together IMHO.

Sorry, I meant the entire program was in one file. It finally became
unmanageable and I wanted to break it up.

> Why separate Monsters from other Entities? And why
> separate Entities at all, why not just two modules, one
> for the Entities and another for the Game itself.

It's to ease the addition of new monsters. I'd like to be able to add
monsters very easily, so I'd like each one to be dealt with in its own
file. I'm planning on having about 52 different monsters (probably more),
so I don't want them all in the same file.

> Presumably you might reuse the Entity module but less
> likely to reuse the game?

Yes. I will reuse the Entity module a ton. It is the basis for monsters,
players, traps, special effects, anything that has a presence in the game.

> Exactly, its easier to use the module to hold all the class
> definitions. Fine grained file structures tend to be used
> in things like C++ and Java as a mechanism for controlling
> compilation times, but they add a lot of undue complexity
> to a project in my experience.

Right, but it's not to control compilation, it's to coding easier. Easier
to find a monster, and easier to add a new one.

> Alan G.

I hope I've made more sense of what I want to do. My eventual goal is to
make adding new features as easy as plopping in a .py file (say, for a
monster or a new level-building algorithm), and make it easier to find a
specific section of code. Going from just that, what would you recommend?

---
Zak Arntson
www.harlekin-maus.com - Games - Lots of 'em

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

From vicki at thepenguin.org  Thu Oct 30 13:19:20 2003
From: vicki at thepenguin.org (Vicki Stanfield)
Date: Thu Oct 30 13:21:49 2003
Subject: [Tutor] More confusion on conversion
Message-ID: <49834.206.53.226.235.1067537960.squirrel@www.thepenguin.org>

Okay, don't ask me why because the answer I got was "for historical
reasons", but I have to take the length of something (a decimal value) and
convert it to its hexadecimal equivalent and then convert that value to
its hexadecimal equivalent padded to 2 places. The result is something
like this:

length = 10
convert 10 to A
convert A to 0x41
padded version = 0x30 0x41

When I try to convert the decimal 10 using either binascii.hexlify, I am
told that it wants a single value instead of the two digit 10. How does
one convert a 10 (decimal value) to its hex equivalent? I don't want the
hex equivalent of 1 followed by the hex equivalent of 0. The example above
is exactly what I must achieve.

--vicki

From reggie at merfinllc.com  Thu Oct 30 13:35:10 2003
From: reggie at merfinllc.com (Reggie Dugard)
Date: Thu Oct 30 13:36:32 2003
Subject: [Tutor] More confusion on conversion
In-Reply-To: <49834.206.53.226.235.1067537960.squirrel@www.thepenguin.org>
References: <49834.206.53.226.235.1067537960.squirrel@www.thepenguin.org>
Message-ID: <1067538910.6379.4.camel@pika>

Ok I won't ask :-).  How about something like:

>>> length = 10
>>> [ hex(ord(x)) for x in '%02X' % length ]
['0x30', '0x41']
>>>

Reggie

On Thu, 2003-10-30 at 10:19, Vicki Stanfield wrote:
> Okay, don't ask me why because the answer I got was "for historical
> reasons", but I have to take the length of something (a decimal value) and
> convert it to its hexadecimal equivalent and then convert that value to
> its hexadecimal equivalent padded to 2 places. The result is something
> like this:
> 
> length = 10
> convert 10 to A
> convert A to 0x41
> padded version = 0x30 0x41
> 
> When I try to convert the decimal 10 using either binascii.hexlify, I am
> told that it wants a single value instead of the two digit 10. How does
> one convert a 10 (decimal value) to its hex equivalent? I don't want the
> hex equivalent of 1 followed by the hex equivalent of 0. The example above
> is exactly what I must achieve.
> 
> --vicki
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor



From zmerch at 30below.com  Thu Oct 30 13:37:21 2003
From: zmerch at 30below.com (Roger Merchberger)
Date: Thu Oct 30 13:44:41 2003
Subject: [Tutor] More confusion on conversion
In-Reply-To: <49834.206.53.226.235.1067537960.squirrel@www.thepenguin.or
 g>
Message-ID: <5.1.0.14.2.20031030132957.05406f18@mail.30below.com>

At 13:19 10/30/2003 -0500, Vicki Stanfield wrote:
>Okay, don't ask me why because the answer I got was "for historical
>reasons", but I have to take the length of something (a decimal value) and
>convert it to its hexadecimal equivalent and then convert that value to
>its hexadecimal equivalent padded to 2 places. The result is something
>like this:
>
>length = 10
>convert 10 to A
>convert A to 0x41
>padded version = 0x30 0x41
>
>When I try to convert the decimal 10 using either binascii.hexlify, I am
>told that it wants a single value instead of the two digit 10. How does
>one convert a 10 (decimal value) to its hex equivalent? I don't want the
>hex equivalent of 1 followed by the hex equivalent of 0. The example above
>is exactly what I must achieve.

I'm not *exactly* sure if this is what you want, but try this snippet & see 
if it's what you want to do:

length = 10                     # original length
hex_length = '%02x' % length    # length converted to 2place hex
individ_hexchar = []            # array to hold individual hex chars
for i in hex_length:            # loop thru hex_length...
   individ_hexchar.append(ord(i))  # Get the ordinal (ASCII) of each

print individ_hexchar           # See if this is what you want!


Anyway, I'm still a partial Python n00b... but I'm learning quick! (Working 
on a module that will yank ID3v1 & ID3v2 tags from .mp3 files... I have it 
working in theory, but it needs some cleanup...
;-)

Hope this helps,
Roger "Merch" Merchberger

--
Roger "Merch" Merchberger -- sysadmin, Iceberg Computers
zmerch@30below.com

What do you do when Life gives you lemons,
and you don't *like* lemonade?????????????


From amk at amk.ca  Thu Oct 30 14:48:07 2003
From: amk at amk.ca (amk@amk.ca)
Date: Thu Oct 30 14:48:56 2003
Subject: [Tutor] Module Packages
In-Reply-To: <3539.192.207.104.221.1067469166.squirrel@webmail.harlekin-maus.com>
References: <3539.192.207.104.221.1067469166.squirrel@webmail.harlekin-maus.com>
Message-ID: <20031030194807.GB13352@rogue.amk.ca>

On Wed, Oct 29, 2003 at 11:12:46PM -0000, Zak Arntson wrote:
> But it looks like I'll have to:
>     plr = Entity.Player.Player()
>     zom1 = Entity.Monster.Zombie.Zombie()
>     zom2 = Entity.Monster.Zombie.Zombie()

Use 'from ... import':

from Pyrl.Entity.Player import Player
from Pyrl.Entity.Monster.Zombie import Zombie

'from ... import *' is considered poor practice, because it imports a whole
bunch of names from the module, but most people have nothing against
importing a few specified names.  

Alan Gauld is correct that it's often clearer to have multiple classes in a
file; for example, "from Pyrl.Entity.Monster import Zombie, Vampire" would
be tidier.  That depends on the length of each class; if the Zombie class is
500 lines long, you're probably going to want to put it in a file of its
own, but if it's 3 lines or 20 lines or maybe 100 lines, you can put
multiple monster classes in a file without things becoming too ungainly.

--amk

From reggie at merfinllc.com  Thu Oct 30 15:08:36 2003
From: reggie at merfinllc.com (Reggie Dugard)
Date: Thu Oct 30 15:08:52 2003
Subject: [Tutor] More confusion on conversion
In-Reply-To: <CA3458C84C976E45B6372A6C14724C9F355E94@ridmsem02.nala.roche.com>
References: <CA3458C84C976E45B6372A6C14724C9F355E94@ridmsem02.nala.roche.com>
Message-ID: <1067544516.6379.37.camel@pika>

Vicki,

If I understand you correctly you simply want something like:

	port.write('%02X' % length)

This should write 2 bytes on the port, one for each hex digit.  If I'm
misunderstanding what you want, maybe you can clarify it a bit more.

Also, I'm sending this back to the list so that people more
knowledgeable than me can help you out as well.

Good luck with your problem.

Reggie

On Thu, 2003-10-30 at 11:23, Stanfield, Vicki {D167~Indianapolis} wrote:
> Pardon my stupidity here, but how does one write this so that I can insert it into my code. It does just what I want, but I need to write those individual values out on the serial port. I tried:
> 
> for each in [ hex(ord(x)) for x in '%02X' % length ]:
>                     port.write(each)
>                     
> but that wrote the 30 78 30 30 for the 0x00 and 30 78 30 38 for the 0x08. What I need is to write just the hex 30 and then a hex 38. Can you give me a lesson? I tried 
> 
> for each in [ hex(ord(x)) for x in '%02X' % length ]:
>                     new=string.replace(each,'0','\')
>                     port.write(new)
>                     time.sleep(.01)
>                     print new
> 
> But I get an invalid token error on the close parenthesis in the string replace statement.
> 
> --vicki
> 
> -----Original Message-----
> From: Reggie Dugard [mailto:reggie@merfinllc.com]
> Sent: Thursday, October 30, 2003 1:35 PM
> To: Vicki Stanfield
> Cc: tutor@python.org
> Subject: Re: [Tutor] More confusion on conversion
> 
> 
> Ok I won't ask :-).  How about something like:
> 
> >>> length = 10
> >>> [ hex(ord(x)) for x in '%02X' % length ]
> ['0x30', '0x41']
> >>>
> 
> Reggie
> 




From glingl at aon.at  Thu Oct 30 15:08:21 2003
From: glingl at aon.at (Gregor Lingl)
Date: Thu Oct 30 15:10:53 2003
Subject: [Tutor]  Python vs. Ruby - and a queston on Tkinter-Canvas 
In-Reply-To: <x31bvaepk7uh$.19ud307iy4cws$.dlg@40tude.net>
References: <63m5ymum4am1.n5hzjz3ncyet$.dlg@40tude.net>	<Pine.LNX.4.44.0310291615030.20823-100000@hkn.eecs.berkeley.edu>
	<x31bvaepk7uh$.19ud307iy4cws$.dlg@40tude.net>
Message-ID: <3FA16FB5.5050603@aon.at>



Andrei schrieb:

>Danny Yoo wrote on Wed, 29 Oct 2003 16:28:52 -0800 (PST):
>
>  
>
>>>Python docs are a lot better too, especially the ones in the ActiveState
>>>distro; the there isn't even a "docs" entry in my Ruby program group!
>>>Another advantage is that the whole of Python is quite English-oriented,
>>>while a lot of Ruby stuff is still in Japanese only (at least I presume
>>>it's Japanese), or really broken English.
>>>      
>>>
>>Hi Andrei,
>>
>>There are some good Ruby books out there.  In fact, the folks who wrote
>>"The Pragmatic Programmer" have released their own Ruby book online:
>>
>>    http://www.rubycentral.com/book/index.html
>>    
>>
>
>Yep, 
>
...

It was approx. 2 years ago, when I decided  to  use (and promote)  
Python  as a
first learning language in my classes (sharing my experiences with other 
teachers here in
Vienna) and there is not a single reason why I should change to another 
language, be it
Ruby or not, now. Instead many pragmatic considerations lead me to stick 
with
Python for my work.

Nevertheless I'm curious, wether a look at Ruby would be rewarding and 
interesting, just
to know what's going on in the world (of computer languages). So the 
above link led me
to a Ruby-Tk program, which I  tried, just for fun, to translate into 
Python-Tkinter

Ruby-Code:

require 'tk'

class Draw
  def do_press(x, y)
    @start_x = x
    @start_y = y
    @current_line = TkcLine.new(@canvas, x, y, x, y)
  end
  def do_motion(x, y)
    if @current_line
      @current_line.coords @start_x, @start_y, x, y
    end
  end
  def do_release(x, y)
    if @current_line
      @current_line.coords @start_x, @start_y, x, y
      @current_line.fill 'black'
      @current_line = nil
    end
  end
  def initialize(parent)
    @canvas = TkCanvas.new(parent)
    @canvas.pack
    @start_x = @start_y = 0
    @canvas.bind("1", proc{|e| do_press(e.x, e.y)})
    @canvas.bind("2", proc{ puts @canvas.postscript({}) })
    @canvas.bind("ButtonRelease-1",
                 proc{|x, y| do_release (x, y)}, "%x %y")
  end
end

root = TkRoot.new{ title 'Canvas' }
Draw.new(root)
Tk.mainloop


Translation to Python:

import Tkinter as Tk

class Draw:
    def do_press(self,e):
        self.start_x = e.x
        self.start_y = e.y
        self.current_line = self.canvas.create_line(e.x, e.y, e.x, e.y)
    def do_motion(self,e):
        if self.current_line:
            self.canvas.coords(self.current_line,
                               self.start_x, self.start_y, e.x, e.y)
    def do_release(self,e):
        if self.current_line:
            self.canvas.coords(self.current_line,
                               self.start_x, self.start_y, e.x, e.y)
            self.canvas.itemconfig(self.current_line, fill="black")
            self.current_line = None
    def __init__(self, parent):
        self.canvas = Tk.Canvas(parent)
        self.canvas.pack()
        # self.start_x = self.start_y = 0  ## is this necessary in Ruby?
        self.canvas.bind("<1>",self.do_press)
        self.canvas.bind("<B1-Motion>", self.do_motion)
        self.canvas.bind("<ButtonRelease-1>", self.do_release)
       
root = Tk.Tk()
root.title("Canvas")
Draw(root)
root.mainloop()

Indeed very similar. This example can be made even more similar, when 
using the Canvas module:

import Tkinter as Tk
from Canvas import Line

class Draw:
    def do_press(self,e):
        self.start_x = e.x
        self.start_y = e.y
        self.current_line = Line(self.canvas, e.x, e.y, e.x, e.y)
    def do_motion(self,e):
        if self.current_line:
            self.current_line.coords(((self.start_x, self.start_y), 
(e.x, e.y)))
    def do_release(self,e):
        if self.current_line:
            self.current_line.coords(((self.start_x, self.start_y), 
(e.x, e.y)))
            self.current_line.config(fill="black")
            self.current_line = None
    def __init__(self, parent):
        self.canvas = Tk.Canvas(parent)
        self.canvas.pack()
        # self.start_x = self.start_y = 0 ## is this necessary in Ruby?
        self.canvas.bind("<1>",self.do_press)
        self.canvas.bind("<B1-Motion>", self.do_motion)
        self.canvas.bind("<ButtonRelease-1>", self.do_release)
       
root = Tk.Tk()
root.title("Canvas")
Draw(root)
root.mainloop()

Alas! The canvas module is declared deprecated. So we are discouraged using
canvas items as objects, contrary to Ruby-Tk users.

####  So my MAIN QUESTION, which in fact has nothing to do with Ruby:  
#######
Why is the - former "experimental" - Canvas module declared deprecated now?
##################################################################

Only one remark concerning Python and Ruby:
One of the most useful, wonderfully beautiful features of Python is 
(imho) how
functions as first class objects are handled. (One can observe this even 
in the above
"translation". Is the back side of this coin, that Ruby doesn't need 
parentheses for
function calls (at least in some cases)?) So Python enforces to "think 
in function-objects"
and this is very fruitful for showing, teaching and experiencing the 
power of abstraction.   

And even the use of self - an often critisized feature - is from my 
point  of view
more an advantage than a disadvantage in the educational context. As it 
makes
explicit what otherwise nevertheless is the case implicitely.

Regards, Gregor

P.S. (  ;-)   ):   Those who can't bear it, could make another step 
(although only visually)
in direction to Ruby by writing:

import Tkinter as Tk
from Canvas import Line

class Draw:
    def do_press(_,e):
        _.start_x = e.x
        _.start_y = e.y
        _.current_line = Line(_.canvas, e.x, e.y, e.x, e.y)
    def do_motion(_,e):
        if _.current_line:
            _.current_line.coords(((_.start_x, _.start_y), (e.x, e.y)))
    def do_release(_,e):
        if _.current_line:
            _.current_line.coords(((_.start_x, _.start_y), (e.x, e.y)))
            _.current_line.config(fill="black")
            _.current_line = None
    def __init__(_, parent):
        _.canvas = Tk.Canvas(parent)
        _.canvas.pack()
        # _.start_x = _.start_y = 0 ## is this necessary in Ruby?
        _.canvas.bind("<1>",_.do_press)
        _.canvas.bind("<B1-Motion>", _.do_motion)
        _.canvas.bind("<ButtonRelease-1>", _.do_release)
       
root = Tk.Tk()
root.title("Canvas")
Draw(root)
root.mainloop()

:-P

P.P.S.: I hope I expressed my ideas clearly enough, so you can grasp 
what I mean. When content
becomes a bit more complex I feel the limits of my restricted knowledge 
of English. Perhaps I should
use part of my time to enhance my English instead of learning one more 
computer language.


From VICKI.STANFIELD at ROCHE.COM  Thu Oct 30 15:24:03 2003
From: VICKI.STANFIELD at ROCHE.COM (Stanfield, Vicki {D167~Indianapolis})
Date: Thu Oct 30 15:28:02 2003
Subject: [Tutor] More confusion on conversion
Message-ID: <CA3458C84C976E45B6372A6C14724C9F9E597D@ridmsem02.nala.roche.com>

Nope, this write '0A' out one the port. I need to write the hex value of the 0 and then the hex value of the 'A'. WHen I tried this:

for each in [ hex(ord(x)) for x in '%02X' % length ]:
                    port.write('%02X' %each)
                    time.sleep(.01)
                    print '%02X' %each

It was close, but it wants an integer instead of the hex values.

port.write('%02X' %each)
TypeError: an integer is required

--vicki

-----Original Message-----
From: Reggie Dugard [mailto:reggie@merfinllc.com]
Sent: Thursday, October 30, 2003 3:09 PM
To: Stanfield, Vicki {D167~Indianapolis}
Cc: tutor@python.org
Subject: RE: [Tutor] More confusion on conversion


Vicki,

If I understand you correctly you simply want something like:

	port.write('%02X' % length)

This should write 2 bytes on the port, one for each hex digit.  If I'm
misunderstanding what you want, maybe you can clarify it a bit more.

Also, I'm sending this back to the list so that people more
knowledgeable than me can help you out as well.

Good luck with your problem.

Reggie

On Thu, 2003-10-30 at 11:23, Stanfield, Vicki {D167~Indianapolis} wrote:
> Pardon my stupidity here, but how does one write this so that I can insert it into my code. It does just what I want, but I need to write those individual values out on the serial port. I tried:
> 
> for each in [ hex(ord(x)) for x in '%02X' % length ]:
>                     port.write(each)
>                     
> but that wrote the 30 78 30 30 for the 0x00 and 30 78 30 38 for the 0x08. What I need is to write just the hex 30 and then a hex 38. Can you give me a lesson? I tried 
> 
> for each in [ hex(ord(x)) for x in '%02X' % length ]:
>                     new=string.replace(each,'0','\')
>                     port.write(new)
>                     time.sleep(.01)
>                     print new
> 
> But I get an invalid token error on the close parenthesis in the string replace statement.
> 
> --vicki
> 
> -----Original Message-----
> From: Reggie Dugard [mailto:reggie@merfinllc.com]
> Sent: Thursday, October 30, 2003 1:35 PM
> To: Vicki Stanfield
> Cc: tutor@python.org
> Subject: Re: [Tutor] More confusion on conversion
> 
> 
> Ok I won't ask :-).  How about something like:
> 
> >>> length = 10
> >>> [ hex(ord(x)) for x in '%02X' % length ]
> ['0x30', '0x41']
> >>>
> 
> Reggie
> 




From reggie at merfinllc.com  Thu Oct 30 15:46:39 2003
From: reggie at merfinllc.com (Reggie Dugard)
Date: Thu Oct 30 15:46:51 2003
Subject: [Tutor] More confusion on conversion
In-Reply-To: <CA3458C84C976E45B6372A6C14724C9F9E597D@ridmsem02.nala.roche.com>
References: <CA3458C84C976E45B6372A6C14724C9F9E597D@ridmsem02.nala.roche.com>
Message-ID: <1067546799.6379.56.camel@pika>

Vicki,

Forgive me if I'm being dense, but how many bytes do you want to write
out on the port for each length?  If the answer is 2, then writing '0'
and 'A' is equivalent to writing 0 and 65 which is equivalent to writing
0x00 and 0x41 - they all have the same bit pattern: 00000000 01000001.

Sorry if I'm misunderstanding you.

Reggie

On Thu, 2003-10-30 at 12:24, Stanfield, Vicki {D167~Indianapolis} wrote:
> Nope, this write '0A' out one the port. I need to write the hex value of the 0 and then the hex value of the 'A'. WHen I tried this:
> 
> for each in [ hex(ord(x)) for x in '%02X' % length ]:
>                     port.write('%02X' %each)
>                     time.sleep(.01)
>                     print '%02X' %each
> 
> It was close, but it wants an integer instead of the hex values.
> 
> port.write('%02X' %each)
> TypeError: an integer is required
> 
> --vicki
> 
> -----Original Message-----
> From: Reggie Dugard [mailto:reggie@merfinllc.com]
> Sent: Thursday, October 30, 2003 3:09 PM
> To: Stanfield, Vicki {D167~Indianapolis}
> Cc: tutor@python.org
> Subject: RE: [Tutor] More confusion on conversion
> 
> 
> Vicki,
> 
> If I understand you correctly you simply want something like:
> 
> 	port.write('%02X' % length)
> 
> This should write 2 bytes on the port, one for each hex digit.  If I'm
> misunderstanding what you want, maybe you can clarify it a bit more.
> 
> Also, I'm sending this back to the list so that people more
> knowledgeable than me can help you out as well.
> 
> Good luck with your problem.
> 
> Reggie




From littledanehren at yahoo.com  Thu Oct 30 15:50:41 2003
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Thu Oct 30 15:50:47 2003
Subject: [Tutor] Importing from classes or functions
Message-ID: <20031030205041.40533.qmail@web41806.mail.yahoo.com>

I'm trying to write a module to make it so that you
can use Ruby-style methods on various types in Python
(similar to the methods on strings, but in Ruby,
*every* method that would be builtin or in the
standard library is callable from that variable). I'm
starting with an integer where, if you call the sin()
function, it returns the sine of the number. I called
this class (for right now) sinnum. So sinnum(5).sin()
should return -0.95892427466313845. I was able to
impliment it, but I had do import math outside of the
class. I wanted to import it within the class, since
when I'm finished, the module should contain more than
one datatype (an extended int, an extended float, an
extended string, etc). But when I try to impliment
importing within the class, the import doesn't work.

>>> class sinnum(int):
...     def __init__(s, number):
...         import math
...         s.num = number
...     def sin(s):
...         return math.sin(s)
...     
>>> x = sinnum(5)
>>> x.sin()
Traceback (most recent call last):
  File "<input>", line 1, in ?
  File "<input>", line 6, in sin
NameError: global name 'math' is not defined

I was able to simplify my error to this, if it helps:

>>> def importmath():
...     import math
...     
>>> importmath()
>>> math.sin(5)
Traceback (most recent call last):
  File "<input>", line 1, in ?
NameError: name 'math' is not defined

If Ruby-style methods for Python is a bad idea or
would be extremely inefficient, please tell me.

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Exclusive Video Premiere - Britney Spears
http://launch.yahoo.com/promos/britneyspears/

From VICKI.STANFIELD at ROCHE.COM  Thu Oct 30 15:53:39 2003
From: VICKI.STANFIELD at ROCHE.COM (Stanfield, Vicki {D167~Indianapolis})
Date: Thu Oct 30 15:54:26 2003
Subject: [Tutor] More confusion on conversion
Message-ID: <CA3458C84C976E45B6372A6C14724C9F9E597E@ridmsem02.nala.roche.com>

Probably I am the one being dense, but I know that the device on the other end expects what it calls a "hex value represented as ASCII." This means that if I want to send a decimal 10, I first have to convert decimal 10 to hex 'A' and then I have to take the hex of the letter 'A' as if it were ASCII and send that. In this example, I need to send 0x30 0x41 (as two bytes of data). In this example, doing this:

port.write('\x30')
port.write('\x41')

is the equivalent of what I want. Of course, I have to make it handle lengths other than 10 too.

Is that any clearer?

--vicki

-----Original Message-----
From: Reggie Dugard [mailto:reggie@merfinllc.com]
Sent: Thursday, October 30, 2003 3:47 PM
To: Stanfield, Vicki {D167~Indianapolis}
Cc: tutor@python.org
Subject: RE: [Tutor] More confusion on conversion


Vicki,

Forgive me if I'm being dense, but how many bytes do you want to write
out on the port for each length?  If the answer is 2, then writing '0'
and 'A' is equivalent to writing 0 and 65 which is equivalent to writing
0x00 and 0x41 - they all have the same bit pattern: 00000000 01000001.

Sorry if I'm misunderstanding you.

Reggie

On Thu, 2003-10-30 at 12:24, Stanfield, Vicki {D167~Indianapolis} wrote:
> Nope, this write '0A' out one the port. I need to write the hex value of the 0 and then the hex value of the 'A'. WHen I tried this:
> 
> for each in [ hex(ord(x)) for x in '%02X' % length ]:
>                     port.write('%02X' %each)
>                     time.sleep(.01)
>                     print '%02X' %each
> 
> It was close, but it wants an integer instead of the hex values.
> 
> port.write('%02X' %each)
> TypeError: an integer is required
> 
> --vicki
> 
> -----Original Message-----
> From: Reggie Dugard [mailto:reggie@merfinllc.com]
> Sent: Thursday, October 30, 2003 3:09 PM
> To: Stanfield, Vicki {D167~Indianapolis}
> Cc: tutor@python.org
> Subject: RE: [Tutor] More confusion on conversion
> 
> 
> Vicki,
> 
> If I understand you correctly you simply want something like:
> 
> 	port.write('%02X' % length)
> 
> This should write 2 bytes on the port, one for each hex digit.  If I'm
> misunderstanding what you want, maybe you can clarify it a bit more.
> 
> Also, I'm sending this back to the list so that people more
> knowledgeable than me can help you out as well.
> 
> Good luck with your problem.
> 
> Reggie




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

From reggie at merfinllc.com  Thu Oct 30 16:09:46 2003
From: reggie at merfinllc.com (Reggie Dugard)
Date: Thu Oct 30 16:09:56 2003
Subject: [Tutor] More confusion on conversion
In-Reply-To: <CA3458C84C976E45B6372A6C14724C9F9E597E@ridmsem02.nala.roche.com>
References: <CA3458C84C976E45B6372A6C14724C9F9E597E@ridmsem02.nala.roche.com>
Message-ID: <1067548186.6379.66.camel@pika>

In my last mail I had a bit of a brain freeze :-(.  '0' is not 0, but is
in fact 48 or 0x30 or 00110000.  This means that

port.write('\x30')
port.write('\x41')

should be equivalent to 

port.write('0A')

which is equivalent to

length = 10
port.write('%02X' % length)  # one of my previous suggestions

so I don't see why that isn't working for you.  Hopefully someone else
can see the error of my ways and point you in the right direction.

Reggie

On Thu, 2003-10-30 at 12:53, Stanfield, Vicki {D167~Indianapolis} wrote:
> Probably I am the one being dense, but I know that the device on the other end expects what it calls a "hex value represented as ASCII." This means that if I want to send a decimal 10, I first have to convert decimal 10 to hex 'A' and then I have to take the hex of the letter 'A' as if it were ASCII and send that. In this example, I need to send 0x30 0x41 (as two bytes of data). In this example, doing this:
> 
> port.write('\x30')
> port.write('\x41')
> 
> is the equivalent of what I want. Of course, I have to make it handle lengths other than 10 too.
> 
> Is that any clearer?
> 
> --vicki
> 
> -----Original Message-----
> From: Reggie Dugard [mailto:reggie@merfinllc.com]
> Sent: Thursday, October 30, 2003 3:47 PM
> To: Stanfield, Vicki {D167~Indianapolis}
> Cc: tutor@python.org
> Subject: RE: [Tutor] More confusion on conversion
> 
> 
> Vicki,
> 
> Forgive me if I'm being dense, but how many bytes do you want to write
> out on the port for each length?  If the answer is 2, then writing '0'
> and 'A' is equivalent to writing 0 and 65 which is equivalent to writing
> 0x00 and 0x41 - they all have the same bit pattern: 00000000 01000001.
> 
> Sorry if I'm misunderstanding you.
> 
> Reggie
> 
> On Thu, 2003-10-30 at 12:24, Stanfield, Vicki {D167~Indianapolis} wrote:
> > Nope, this write '0A' out one the port. I need to write the hex value of the 0 and then the hex value of the 'A'. WHen I tried this:
> > 
> > for each in [ hex(ord(x)) for x in '%02X' % length ]:
> >                     port.write('%02X' %each)
> >                     time.sleep(.01)
> >                     print '%02X' %each
> > 
> > It was close, but it wants an integer instead of the hex values.
> > 
> > port.write('%02X' %each)
> > TypeError: an integer is required
> > 
> > --vicki
> > 
> > -----Original Message-----
> > From: Reggie Dugard [mailto:reggie@merfinllc.com]
> > Sent: Thursday, October 30, 2003 3:09 PM
> > To: Stanfield, Vicki {D167~Indianapolis}
> > Cc: tutor@python.org
> > Subject: RE: [Tutor] More confusion on conversion
> > 
> > 
> > Vicki,
> > 
> > If I understand you correctly you simply want something like:
> > 
> > 	port.write('%02X' % length)
> > 
> > This should write 2 bytes on the port, one for each hex digit.  If I'm
> > misunderstanding what you want, maybe you can clarify it a bit more.
> > 
> > Also, I'm sending this back to the list so that people more
> > knowledgeable than me can help you out as well.
> > 
> > Good luck with your problem.
> > 
> > Reggie
> 
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
-- 
Reggie



From pythontutor at venix.com  Thu Oct 30 16:18:23 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Thu Oct 30 16:18:30 2003
Subject: [Tutor] More confusion on conversion
In-Reply-To: <1067546799.6379.56.camel@pika>
References: <CA3458C84C976E45B6372A6C14724C9F9E597D@ridmsem02.nala.roche.com>
	<1067546799.6379.56.camel@pika>
Message-ID: <3FA1801F.2030002@venix.com>

length = 10
for each in [ hex(ord(x)) for x in '%02X' % length ]:
     port.write( each[2:])	# don't sent the leading 0x
     time.sleep(.01)
     print each

I would expect this to work based upon your first email.


Reggie Dugard wrote:

> Vicki,
> 
> Forgive me if I'm being dense, but how many bytes do you want to write
> out on the port for each length?  If the answer is 2, then writing '0'
> and 'A' is equivalent to writing 0 and 65 which is equivalent to writing
> 0x00 and 0x41 - they all have the same bit pattern: 00000000 01000001.
> 
> Sorry if I'm misunderstanding you.
> 
> Reggie
> 
> On Thu, 2003-10-30 at 12:24, Stanfield, Vicki {D167~Indianapolis} wrote:
> 
>>Nope, this write '0A' out one the port. I need to write the hex value of the 0 and then the hex value of the 'A'. WHen I tried this:
>>
>>for each in [ hex(ord(x)) for x in '%02X' % length ]:
>>                    port.write('%02X' %each)
>>                    time.sleep(.01)
>>                    print '%02X' %each
>>
>>It was close, but it wants an integer instead of the hex values.
>>
>>port.write('%02X' %each)
>>TypeError: an integer is required
>>
>>--vicki
>>
>>-----Original Message-----
>>From: Reggie Dugard [mailto:reggie@merfinllc.com]
>>Sent: Thursday, October 30, 2003 3:09 PM
>>To: Stanfield, Vicki {D167~Indianapolis}
>>Cc: tutor@python.org
>>Subject: RE: [Tutor] More confusion on conversion
>>
>>
>>Vicki,
>>
>>If I understand you correctly you simply want something like:
>>
>>	port.write('%02X' % length)
>>
>>This should write 2 bytes on the port, one for each hex digit.  If I'm
>>misunderstanding what you want, maybe you can clarify it a bit more.
>>
>>Also, I'm sending this back to the list so that people more
>>knowledgeable than me can help you out as well.
>>
>>Good luck with your problem.
>>
>>Reggie
> 
> 
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582


From glingl at aon.at  Thu Oct 30 16:25:32 2003
From: glingl at aon.at (Gregor Lingl)
Date: Thu Oct 30 16:27:27 2003
Subject: [Tutor] Importing from classes or functions
In-Reply-To: <20031030205041.40533.qmail@web41806.mail.yahoo.com>
References: <20031030205041.40533.qmail@web41806.mail.yahoo.com>
Message-ID: <3FA181CC.4040200@aon.at>



Daniel Ehrenberg schrieb:

>I'm trying to write a module to make it so that you
>can use Ruby-style methods on various types in Python
>(similar to the methods on strings, but in Ruby,
>*every* method that would be builtin or in the
>standard library is callable from that variable). I'm
>starting with an integer where, if you call the sin()
>function, it returns the sine of the number. I called
>this class (for right now) sinnum. So sinnum(5).sin()
>should return -0.95892427466313845. 
>
You can import a module into an arbitrary namspace with the
buit in function __import__

for instance:

 >>> class C:
    m = __import__("math")    # class-attribute
    def test(self):
        print C.m.sin(C.m.pi/2)

       
 >>> c = C()
 >>> c.test()
1.0

or, as you wanted:

 >>> class sinnum:
    def __init__(self, number):
        self.m = __import__("math")  # instance - attribute
        self.num = number
    def sin(self):
        return self.m.sin(self.num)

   
 >>> x = sinnum(5)
 >>> x.sin()
-0.95892427466313845
 >>>

HTH, Gregor


>  
>


From pythontutor at venix.com  Thu Oct 30 16:45:51 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Thu Oct 30 16:46:16 2003
Subject: [Tutor] More confusion on conversion
In-Reply-To: <CA3458C84C976E45B6372A6C14724C9F9E597E@ridmsem02.nala.roche.com>
References: <CA3458C84C976E45B6372A6C14724C9F9E597E@ridmsem02.nala.roche.com>
Message-ID: <3FA1868F.5030407@venix.com>

for each in [ hex(ord(x)) for x in '%02X' % length ]:

I used that line in my earlier email.  BUT it can be simplified:

length = 10
for x in '%02X' % length:
     port.write(x)
     time.sleep(.01)
     print '%02X' % ord(x)


Note that '\x30' has the same value as '0'

 >>> print '\x30' == '0'
1

They are just alternate means of writing the same thing.  The '\x30'
emphasizes the bit value.  The '0' is for people to read.

Stanfield, Vicki {D167~Indianapolis} wrote:

> Probably I am the one being dense, but I know that the device on the other end expects what it calls a "hex value represented as ASCII." This means that if I want to send a decimal 10, I first have to convert decimal 10 to hex 'A' and then I have to take the hex of the letter 'A' as if it were ASCII and send that. In this example, I need to send 0x30 0x41 (as two bytes of data). In this example, doing this:
> 
> port.write('\x30')
> port.write('\x41')
> 
> is the equivalent of what I want. Of course, I have to make it handle lengths other than 10 too.
> 
> Is that any clearer?
> 
> --vicki
> 
> -----Original Message-----
> From: Reggie Dugard [mailto:reggie@merfinllc.com]
> Sent: Thursday, October 30, 2003 3:47 PM
> To: Stanfield, Vicki {D167~Indianapolis}
> Cc: tutor@python.org
> Subject: RE: [Tutor] More confusion on conversion
> 
> 
> Vicki,
> 
> Forgive me if I'm being dense, but how many bytes do you want to write
> out on the port for each length?  If the answer is 2, then writing '0'
> and 'A' is equivalent to writing 0 and 65 which is equivalent to writing
> 0x00 and 0x41 - they all have the same bit pattern: 00000000 01000001.
> 
> Sorry if I'm misunderstanding you.
> 
> Reggie
> 
> On Thu, 2003-10-30 at 12:24, Stanfield, Vicki {D167~Indianapolis} wrote:
> 
>>Nope, this write '0A' out one the port. I need to write the hex value of the 0 and then the hex value of the 'A'. WHen I tried this:
>>
>>for each in [ hex(ord(x)) for x in '%02X' % length ]:
>>                    port.write('%02X' %each)
>>                    time.sleep(.01)
>>                    print '%02X' %each
>>
>>It was close, but it wants an integer instead of the hex values.
>>
>>port.write('%02X' %each)
>>TypeError: an integer is required
>>
>>--vicki
>>
>>-----Original Message-----
>>From: Reggie Dugard [mailto:reggie@merfinllc.com]
>>Sent: Thursday, October 30, 2003 3:09 PM
>>To: Stanfield, Vicki {D167~Indianapolis}
>>Cc: tutor@python.org
>>Subject: RE: [Tutor] More confusion on conversion
>>
>>
>>Vicki,
>>
>>If I understand you correctly you simply want something like:
>>
>>	port.write('%02X' % length)
>>
>>This should write 2 bytes on the port, one for each hex digit.  If I'm
>>misunderstanding what you want, maybe you can clarify it a bit more.
>>
>>Also, I'm sending this back to the list so that people more
>>knowledgeable than me can help you out as well.
>>
>>Good luck with your problem.
>>
>>Reggie
> 
> 
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582


From alan.gauld at blueyonder.co.uk  Thu Oct 30 16:59:50 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Thu Oct 30 16:59:38 2003
Subject: [Tutor] More confusion on conversion
References: <49834.206.53.226.235.1067537960.squirrel@www.thepenguin.org>
Message-ID: <010d01c39f31$245ffc30$6401a8c0@xp>

> length = 10
> convert 10 to A
> convert A to 0x41

Down to here I get but

> padded version = 0x30 0x41

How is this padded to two places? 0x30 is ASCII for 48?
Do you mean 0x20 which is a space? I will assume so...

> told that it wants a single value instead of the two digit 10. How
does
> one convert a 10 (decimal value) to its hex equivalent?

10 and its hex equivalent are the same in the computer.
You display the hex version of 10 using string formating(as one way):

>>> print "%2X" % 10
 A

Note it takes up two characters(the 2 in the fmt string)
and is upper case A(the upper case X).

Now you want the hex codes for those characters:

>>> for c in ' A': print "%X" % ord(c)
20
41

HTH

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld







From pythontutor at venix.com  Thu Oct 30 17:02:49 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Thu Oct 30 17:03:01 2003
Subject: [Tutor] More confusion on conversion
In-Reply-To: <3FA1868F.5030407@venix.com>
References: <CA3458C84C976E45B6372A6C14724C9F9E597E@ridmsem02.nala.roche.com>
	<3FA1868F.5030407@venix.com>
Message-ID: <3FA18A89.2080707@venix.com>

I assume that you need to send an even number of hex characters.  I think this
code should do the trick:

length = 1020	# 3 hex digits
hexstr = '%02X' % length
if len(hexstr) % 2:	# pad to even number of digits
     hexstr = '0' + hexstr
port.write(hexstr)
print hexstr

If multiple characters go out too quickly, restore the timing loop like
before:
for x in hexstr:
     port.write(x)
     time.sleep(.01)
     print '%02X' % ord(x)

Lloyd Kvam wrote:

> for each in [ hex(ord(x)) for x in '%02X' % length ]:
> 
> I used that line in my earlier email.  BUT it can be simplified:
> 
> length = 10
> for x in '%02X' % length:
>     port.write(x)
>     time.sleep(.01)
>     print '%02X' % ord(x)
> 
> 
> Note that '\x30' has the same value as '0'
> 
>  >>> print '\x30' == '0'
> 1
> 
> They are just alternate means of writing the same thing.  The '\x30'
> emphasizes the bit value.  The '0' is for people to read.
> 
> Stanfield, Vicki {D167~Indianapolis} wrote:
> 
>> Probably I am the one being dense, but I know that the device on the 
>> other end expects what it calls a "hex value represented as ASCII." 
>> This means that if I want to send a decimal 10, I first have to 
>> convert decimal 10 to hex 'A' and then I have to take the hex of the 
>> letter 'A' as if it were ASCII and send that. In this example, I need 
>> to send 0x30 0x41 (as two bytes of data). In this example, doing this:
>>
>> port.write('\x30')
>> port.write('\x41')
>>
>> is the equivalent of what I want. Of course, I have to make it handle 
>> lengths other than 10 too.
>>
>> Is that any clearer?
>>
>> --vicki
>>
>> -----Original Message-----
>> From: Reggie Dugard [mailto:reggie@merfinllc.com]
>> Sent: Thursday, October 30, 2003 3:47 PM
>> To: Stanfield, Vicki {D167~Indianapolis}
>> Cc: tutor@python.org
>> Subject: RE: [Tutor] More confusion on conversion
>>
>>
>> Vicki,
>>
>> Forgive me if I'm being dense, but how many bytes do you want to write
>> out on the port for each length?  If the answer is 2, then writing '0'
>> and 'A' is equivalent to writing 0 and 65 which is equivalent to writing
>> 0x00 and 0x41 - they all have the same bit pattern: 00000000 01000001.
>>
>> Sorry if I'm misunderstanding you.
>>
>> Reggie
>>
>> On Thu, 2003-10-30 at 12:24, Stanfield, Vicki {D167~Indianapolis} wrote:
>>
>>> Nope, this write '0A' out one the port. I need to write the hex value 
>>> of the 0 and then the hex value of the 'A'. WHen I tried this:
>>>
>>> for each in [ hex(ord(x)) for x in '%02X' % length ]:
>>>                    port.write('%02X' %each)
>>>                    time.sleep(.01)
>>>                    print '%02X' %each
>>>
>>> It was close, but it wants an integer instead of the hex values.
>>>
>>> port.write('%02X' %each)
>>> TypeError: an integer is required
>>>
>>> --vicki
>>>
>>> -----Original Message-----
>>> From: Reggie Dugard [mailto:reggie@merfinllc.com]
>>> Sent: Thursday, October 30, 2003 3:09 PM
>>> To: Stanfield, Vicki {D167~Indianapolis}
>>> Cc: tutor@python.org
>>> Subject: RE: [Tutor] More confusion on conversion
>>>
>>>
>>> Vicki,
>>>
>>> If I understand you correctly you simply want something like:
>>>
>>>     port.write('%02X' % length)
>>>
>>> This should write 2 bytes on the port, one for each hex digit.  If I'm
>>> misunderstanding what you want, maybe you can clarify it a bit more.
>>>
>>> Also, I'm sending this back to the list so that people more
>>> knowledgeable than me can help you out as well.
>>>
>>> Good luck with your problem.
>>>
>>> Reggie
>>
>>
>>
>>
>>
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor@python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor@python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582


From alan.gauld at blueyonder.co.uk  Thu Oct 30 17:06:07 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Thu Oct 30 17:06:34 2003
Subject: [Tutor] More confusion on conversion
References: <CA3458C84C976E45B6372A6C14724C9F9E597D@ridmsem02.nala.roche.com>
	<1067546799.6379.56.camel@pika>
Message-ID: <012c01c39f32$04cf9500$6401a8c0@xp>

> out on the port for each length?  If the answer is 2, then writing
'0'
> and 'A' is equivalent to writing 0 and 65 which is equivalent to
writing
> 0x00 and 0x41 - they all have the same bit pattern: 00000000
01000001.

Yes that's what is confusing me too. Hex is only normally
relevant to display, if you are writing to a port the decimal
values will do just as well. OK, in this case it's the decimal
values for the original hex string but I wonder if you really
need so many hex conversions?

Alan G.


From littledanehren at yahoo.com  Thu Oct 30 17:10:23 2003
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Thu Oct 30 17:10:27 2003
Subject: [Tutor] Python vs. Ruby
In-Reply-To: <00c101c39ec5$2aaa5de0$6401a8c0@xp>
Message-ID: <20031030221023.32463.qmail@web41810.mail.yahoo.com>

Alan Gauld wrote:
> 2) I hate languages that insist on everything being
> an object. 
> I've used OO long enough to know there are times
> when it 
> ain't the best answer...

When not? Isn't everything in Python an object, to
some degree?
Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Exclusive Video Premiere - Britney Spears
http://launch.yahoo.com/promos/britneyspears/

From tbstep at tampabay.rr.com  Thu Oct 30 17:28:37 2003
From: tbstep at tampabay.rr.com (Todd Stephens)
Date: Thu Oct 30 17:29:21 2003
Subject: [Tutor] Re: Python vs. Ruby  [where to find more about Ruby]
In-Reply-To: <Pine.LNX.4.44.0310291615030.20823-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0310291615030.20823-100000@hkn.eecs.berkeley.edu>
Message-ID: <200310301728.37678.tbstep@tampabay.rr.com>

On Wednesday 29 October 2003 07:28 pm, Danny Yoo wrote:

>  Hmmm... but I'd better balance my karma by providing a link to a
> nice online Python book too.  *grin*
>
>      http://diveintopython.org/

Strange things with that site.  If I try to scroll down the page, 
everything "smears" and I have to reload to read it.  I've never 
encountered this before, and oddly enough the page validates as HTML 
4.01 Strict.

-- 
Todd Stephens
"Good people do not need laws to tell them to act responsibly, 
while bad people will find a way around the laws." - Plato


From vicki at thepenguin.org  Thu Oct 30 17:32:37 2003
From: vicki at thepenguin.org (Vicki Stanfield)
Date: Thu Oct 30 17:37:06 2003
Subject: [Tutor] More confusion on conversion
Message-ID: <48502.12.223.197.34.1067553157.squirrel@www.thepenguin.org>

>> length = 10
>> convert 10 to A
>> convert A to 0x41
>
> Down to here I get but
>
>> padded version = 0x30 0x41
>
> How is this padded to two places? 0x30 is ASCII for 48?
> Do you mean 0x20 which is a space? I will assume so...

That is how it gets weird. I have to send a 0x30 which represents a '0'. I
acknowledge that this is strange, but I did not come up with it. It is the
historical way of doing things. I will try this solution when I get back
to work tomorrow morning. Thanks.

--vicki




From dyoo at hkn.eecs.berkeley.edu  Thu Oct 30 18:09:42 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Oct 30 18:09:48 2003
Subject: [Tutor] Importing from classes or functions
In-Reply-To: <20031030205041.40533.qmail@web41806.mail.yahoo.com>
Message-ID: <Pine.LNX.4.44.0310301439090.15264-100000@hkn.eecs.berkeley.edu>



On Thu, 30 Oct 2003, Daniel Ehrenberg wrote:

> I'm trying to write a module to make it so that you can use Ruby-style
> methods on various types in Python (similar to the methods on strings,
> but in Ruby, *every* method that would be builtin or in the standard
> library is callable from that variable). I'm starting with an integer
> where, if you call the sin() function, it returns the sine of the
> number. I called this class (for right now) sinnum. So sinnum(5).sin()
> should return -0.95892427466313845.


Hi Daniel,


Yes, it's possible to do something like this, if we do some attribute
lookup trickery:

###
>>> class sinnum(int):
...     def __getattr__(self, attr):
...         def f(*args):
...             return apply(getattr(__builtins__, attr),
...                          (self,) + args)
...         return f
...
>>> x = sinnum(5)
>>> x.abs()
5
>>> x = sinnum(-5)
>>> x.abs()
5
###


So it's sorta working.  But this isn't quite right, though:

###
>>> x.abs().abs()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'int' object has no attribute 'abs'
###

The error here shows that the definition above isn't providing "closure",
in the sense that the value of 'x.abs()' isn't a Ruby-style "sinnum", so
we can't compose two operations, like:

    x.abs.abs()


(Tangent note: Terminology is a funny thing, and the term "closure" is
also used to describe something totally different in computer science: in
computer science terms, that embedded 'f' function that's being returned
by the __getattr__() is an example of a "closure" function.  So the bug
here is that the closure function isn't providing mathematical closure.
*grin*)


Anyway, once we see this, we can fix this problem:

###
>>> class sinnum(int):
...     def __getattr__(self, attr):
...         def f(*args):
...             return sinnum(apply(getattr(__builtins__, attr),
...                                 (self,) + args))
...         return f
...
>>> x = sinnum(42)
>>> x.pow(2).pow(2)
3111696
###




> I wanted to import it within the class, since when I'm finished, the
> module should contain more than one datatype (an extended int, an
> extended float, an extended string, etc). But when I try to impliment
> importing within the class, the import doesn't work.

Think of 'import math' as a statement that creates a local variable called
'math'.  Then the error message should be less mysterious:


> >>> class sinnum(int):
> ...     def __init__(s, number):
> ...         import math
> ...         s.num = number
> ...     def sin(s):
> ...         return math.sin(s)
> ...
> >>> x = sinnum(5)
> >>> x.sin()
> Traceback (most recent call last):
>   File "<input>", line 1, in ?
>   File "<input>", line 6, in sin
> NameError: global name 'math' is not defined


'math' here is a local variable within __init__, so it won't be visible
from the 'sin()' function.  So the error is actually not too serious: it's
a scope issue.



> If Ruby-style methods for Python is a bad idea or would be extremely
> inefficient, please tell me.

To tell the truth, I think it might be a bad idea in Python.  *grin*


It's probably not outrageously inefficient --- all Python method access is
done through attribute lookup anyway --- but it's just something that most
Python programmers won't recognize at first.



Good luck to you!


From project5 at redrival.net  Thu Oct 30 18:17:40 2003
From: project5 at redrival.net (Andrei)
Date: Thu Oct 30 18:19:58 2003
Subject: [Tutor] Re: Re: Python vs. Ruby  [where to find more about Ruby]
References: <Pine.LNX.4.44.0310291615030.20823-100000@hkn.eecs.berkeley.edu>
	<200310301728.37678.tbstep@tampabay.rr.com>
Message-ID: <bqhllbrrrar6$.12p7pn8vnxevu$.dlg@40tude.net>

Todd Stephens wrote on Thu, 30 Oct 2003 17:28:37 -0500:

> On Wednesday 29 October 2003 07:28 pm, Danny Yoo wrote:
> 
>>  Hmmm... but I'd better balance my karma by providing a link to a
>> nice online Python book too.  *grin*
>>
>>      http://diveintopython.org/
> 
> Strange things with that site.  If I try to scroll down the page, 
> everything "smears" and I have to reload to read it.  I've never 
> encountered this before, and oddly enough the page validates as HTML 
> 4.01 Strict.

Probably a browser quirk. I've never had any problems with it, despite
using several different browser engines. The author is quite fanatical
about standards, cross-browser compatibility and accessibility, so that
part should be OK.

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V
ernq gur yvfg, fb gurer'f ab arrq gb PP.


From project5 at redrival.net  Thu Oct 30 18:35:18 2003
From: project5 at redrival.net (Andrei)
Date: Thu Oct 30 18:37:37 2003
Subject: [Tutor] Re: Python vs. Ruby
References: <00c101c39ec5$2aaa5de0$6401a8c0@xp>
	<20031030221023.32463.qmail@web41810.mail.yahoo.com>
Message-ID: <1b4mbgghafw3c$.14tedktzha88e$.dlg@40tude.net>

Daniel Ehrenberg wrote on Thu, 30 Oct 2003 14:10:23 -0800 (PST):

> Alan Gauld wrote:
>> 2) I hate languages that insist on everything being
>> an object. 
>> I've used OO long enough to know there are times
>> when it 
>> ain't the best answer...
> 
> When not? Isn't everything in Python an object, to
> some degree?

>From Dive into Python:
"Different programming languages define ?object? in different ways. In
some, it means that all objects must have attributes and methods; in
others, it means that all objects are subclassable. In Python, the
definition is looser; some objects have neither attributes nor methods
(more on this later in this chapter), and not all objects are subclassable
(more on this in chapter 3). But everything is an object in the sense that
it can be assigned to a variable or passed as an argument to a function
(more in this in chapter 2)."

In Ruby, you can subclass everything, modify all classes, call methods on
everything.

Ruby              Python
=====================================
2.times do        for i in range(2):
    puts "ok"         print "ok"
end
- - - - - - - - - - - - - - - - - - -
ok                ok
ok                ok
=> 2
=====================================
5.0.+(3)          5.0 + 3
- - - - - - - - - - - - - - - - - - -
=> 8.0            8

"+" is a method of 5.0 and you can use it as such in Ruby. times() is a
method of 2. While writing 2.times() has a certain ring to it and I rather
like it, it's not something that makes a language superior or even better. 

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V
ernq gur yvfg, fb gurer'f ab arrq gb PP.


From zmerch at 30below.com  Thu Oct 30 17:32:59 2003
From: zmerch at 30below.com (Roger Merchberger)
Date: Thu Oct 30 18:40:02 2003
Subject: [Tutor] Re: Python vs. Ruby  [where to find more about
  Ruby]
In-Reply-To: <200310301728.37678.tbstep@tampabay.rr.com>
References: <Pine.LNX.4.44.0310291615030.20823-100000@hkn.eecs.berkeley.edu>
	<Pine.LNX.4.44.0310291615030.20823-100000@hkn.eecs.berkeley.edu>
Message-ID: <5.1.0.14.2.20031030173153.02cdd420@mail.30below.com>

Rumor has it that Todd Stephens may have mentioned these words:
>On Wednesday 29 October 2003 07:28 pm, Danny Yoo wrote:
>
> >  Hmmm... but I'd better balance my karma by providing a link to a
> > nice online Python book too.  *grin*
> >
> >      http://diveintopython.org/
>
>Strange things with that site.  If I try to scroll down the page,
>everything "smears" and I have to reload to read it.  I've never
>encountered this before, and oddly enough the page validates as HTML
>4.01 Strict.

Works fine in Win32 Mozilla Firebird 0.6.1...

Laterz,
Roger "Merch" Merchberger

--
Roger "Merch" Merchberger   | JC: "Like those people in Celeronville!"
sysadmin, Iceberg Computers | Me: "Don't you mean Silicon Valley???"
zmerch@30below.com          | JC: "Yea, that's the place!"
                             | JC == Jeremy Christian


From alan.gauld at blueyonder.co.uk  Thu Oct 30 18:58:25 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Thu Oct 30 18:58:11 2003
Subject: [Tutor] More confusion on conversion
References: <49834.206.53.226.235.1067537960.squirrel@www.thepenguin.org>
	<010d01c39f31$245ffc30$6401a8c0@xp>
	<48473.12.223.197.34.1067553105.squirrel@www.thepenguin.org>
Message-ID: <013101c39f41$b4e4ccd0$6401a8c0@xp>

> > How is this padded to two places? 0x30 is ASCII for 48?
> > Do you mean 0x20 which is a space? I will assume so...
>
> That is how it gets weird. I have to send a 0x30 which represents a
'0'.

Yes my mistake, 48 is the ASCOII code for zero.

So what you need is to send 48,65 down your port, which
are the ASCII codes for '0A'.

And you get the '0A' by using the string format operator:

value = 10
# create a 2 char, zero padded, upper case hex string
hexString = "%02X" % value

# send it to a port char at a time
for ch in hexString: sendToPort(ord(ch))

Should, I think, do what you want?

Alan G.


From alan.gauld at blueyonder.co.uk  Thu Oct 30 19:02:02 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Thu Oct 30 19:01:49 2003
Subject: [Tutor] More confusion on conversion
References: <CA3458C84C976E45B6372A6C14724C9F9E597E@ridmsem02.nala.roche.com>
	<1067548186.6379.66.camel@pika>
Message-ID: <014e01c39f42$36bd0100$6401a8c0@xp>

> which is equivalent to
> 
> length = 10
> port.write('%02X' % length)  # one of my previous suggestions

Nope, coz that sends a string - including the string terminator.
Vicki needs to send the two characters one after the other.
But all the hex convertions are unnecessary apart from the 
initial one.

Assuming I have understood correctly.

Alan G.



From tbstep at tampabay.rr.com  Thu Oct 30 19:09:26 2003
From: tbstep at tampabay.rr.com (Todd Stephens)
Date: Thu Oct 30 19:13:00 2003
Subject: [Tutor] Re: Re: Python vs. Ruby  [where to find more about Ruby]
In-Reply-To: <bqhllbrrrar6$.12p7pn8vnxevu$.dlg@40tude.net>
References: <Pine.LNX.4.44.0310291615030.20823-100000@hkn.eecs.berkeley.edu>
	<200310301728.37678.tbstep@tampabay.rr.com>
	<bqhllbrrrar6$.12p7pn8vnxevu$.dlg@40tude.net>
Message-ID: <200310301909.26166.tbstep@tampabay.rr.com>

On Thursday 30 October 2003 06:17 pm, Andrei wrote:

>  Probably a browser quirk. I've never had any problems with it,
> despite using several different browser engines. The author is quite
> fanatical about standards, cross-browser compatibility and
> accessibility, so that part should be OK.

I tried with MozillaFirebird and it works fine.  Odd that Konqueror 
(what I originally tried it with) should display it incorrectly in that 
manner.  I had thought that Konq was one of the most 
standards-compliant browsers.

-- 
Todd Stephens
"Good people do not need laws to tell them to act responsibly, 
while bad people will find a way around the laws." - Plato


From glingl at aon.at  Thu Oct 30 19:20:35 2003
From: glingl at aon.at (Gregor Lingl)
Date: Thu Oct 30 19:22:29 2003
Subject: [Tutor] Re: Python vs. Ruby
In-Reply-To: <1b4mbgghafw3c$.14tedktzha88e$.dlg@40tude.net>
References: <00c101c39ec5$2aaa5de0$6401a8c0@xp>	<20031030221023.32463.qmail@web41810.mail.yahoo.com>
	<1b4mbgghafw3c$.14tedktzha88e$.dlg@40tude.net>
Message-ID: <3FA1AAD3.3070600@aon.at>

...

>In Ruby, you can subclass everything, modify all classes, call methods on
>everything.
>
>Ruby              Python
>=====================================
>2.times do        for i in range(2):
>    puts "ok"         print "ok"
>end
>- - - - - - - - - - - - - - - - - - -
>ok                ok
>ok                ok
>=> 2
>=====================================
>5.0.+(3)          5.0 + 3
>- - - - - - - - - - - - - - - - - - -
>=> 8.0            8
>  
>
at least this last example is not so much different from Python:

 >>> 5.0.__add__(3)
8.0
 >>>
which shows that in Python + also is only some sort of syntactical
sugar.

On the other hand there are types of objects, e.g. type 'function',
which cannot be subclassed as far as I know (and regret).

Testtask: is it possible to subclass (numerical)  functions - say this
new class is named Fun - e.g. by adding a __add__ method, in a
way that their instances can be added, like:
 >>> from math import sin, cos
 >>> f = Fun(sin) + Fun(cos)   ### see remark below
 >>> f(1)
#### should output sin(1)+cos(1)
In short: it would be nice to create some sort of function algebra.

In Python this seems a bit weird because of the special
way functions are defined (namely via the reserved word def).
So how should (or could) one define a "fun"? Maybe by making
it "callable" somehow? (Oh, I feel that this is not a very sharply
defined problem ...)

Is a task of this sort more easily ( and/or more
in accordance with the philosophy of the language)
solvable in Ruby?

Gregor






From reggie at merfinllc.com  Thu Oct 30 19:36:06 2003
From: reggie at merfinllc.com (Reggie Dugard)
Date: Thu Oct 30 19:37:20 2003
Subject: [Tutor] More confusion on conversion
In-Reply-To: <014e01c39f42$36bd0100$6401a8c0@xp>
References: <CA3458C84C976E45B6372A6C14724C9F9E597E@ridmsem02.nala.roche.com>
	<1067548186.6379.66.camel@pika>  <014e01c39f42$36bd0100$6401a8c0@xp>
Message-ID: <1067560566.6379.77.camel@pika>

Just for my own clarification, what string terminator is sent?  Not
knowing exactly what port is, I assumed that when Vicki sent the 2
characters, one after the other, that it would be equivalent to sending
a 2 byte string.

In other words, when Vicki said she wanted the equivalent of

port.write('\x30')
port.write('\x41')

I assumed that

port.write('0A') 

would work.  Could you explain where I'm mistaken?

Reggie

On Thu, 2003-10-30 at 16:02, Alan Gauld wrote:
> > which is equivalent to
> > 
> > length = 10
> > port.write('%02X' % length)  # one of my previous suggestions
> 
> Nope, coz that sends a string - including the string terminator.
> Vicki needs to send the two characters one after the other.
> But all the hex convertions are unnecessary apart from the 
> initial one.
> 
> Assuming I have understood correctly.
> 
> Alan G.
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor



From littledanehren at yahoo.com  Thu Oct 30 19:42:13 2003
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Thu Oct 30 19:42:18 2003
Subject: [Tutor] Importing from classes or functions
In-Reply-To: <Pine.LNX.4.44.0310301439090.15264-100000@hkn.eecs.berkeley.edu>
Message-ID: <20031031004213.28021.qmail@web41802.mail.yahoo.com>

> Yes, it's possible to do something like this, if we
> do some attribute
> lookup trickery:
> 
> ###
> >>> class sinnum(int):
> ...     def __getattr__(self, attr):
> ...         def f(*args):
> ...             return apply(getattr(__builtins__,
> attr),
> ...                          (self,) + args)
> ...         return f
> ...
> >>> x = sinnum(5)
> >>> x.abs()
> 5
> >>> x = sinnum(-5)
> >>> x.abs()
> 5
> ###
> 
Would you mind explaining that code? I can't
understand it, and it doesn't seem to work if you're
using namespaces. I'd like it to work so that the math
module is imported locally and math functions can be
used without namespaces.

> 
> So it's sorta working.  But this isn't quite right,
> though:
> 
> ###
> >>> x.abs().abs()
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> AttributeError: 'int' object has no attribute 'abs'
> ###
> 
> The error here shows that the definition above isn't
> providing "closure",
> in the sense that the value of 'x.abs()' isn't a
> Ruby-style "sinnum", so
> we can't compose two operations, like:
> 
>     x.abs.abs()
> 
> 
> Anyway, once we see this, we can fix this problem:
> 
> ###
> >>> class sinnum(int):
> ...     def __getattr__(self, attr):
> ...         def f(*args):
> ...             return
> sinnum(apply(getattr(__builtins__, attr),
> ...                                 (self,) + args))
> ...         return f
> ...
> >>> x = sinnum(42)
> >>> x.pow(2).pow(2)
> 3111696
> ###
> 
> 
> 
I don't see the difference between those two classes.
> 
> > I wanted to import it within the class, since when
> I'm finished, the
> > module should contain more than one datatype (an
> extended int, an
> > extended float, an extended string, etc). But when
> I try to impliment
> > importing within the class, the import doesn't
> work.
> 
> Think of 'import math' as a statement that creates a
> local variable called
> 'math'.  Then the error message should be less
> mysterious:
> 
> 
> > >>> class sinnum(int):
> > ...     def __init__(s, number):
> > ...         import math
> > ...         s.num = number
> > ...     def sin(s):
> > ...         return math.sin(s)
> > ...
> > >>> x = sinnum(5)
> > >>> x.sin()
> > Traceback (most recent call last):
> >   File "<input>", line 1, in ?
> >   File "<input>", line 6, in sin
> > NameError: global name 'math' is not defined
> 
> 
> 'math' here is a local variable within __init__, so
> it won't be visible
> from the 'sin()' function.  So the error is actually
> not too serious: it's
> a scope issue.
> 

No, when I tried importing math outside of the
__init__ function, it didn't do anything. Someone else
on the list suggested using the __import__ function
(not definition, just using the function), and it
worked.
> 
> 
> To tell the truth, I think it might be a bad idea in
> Python.  *grin*
> 
> 
> It's probably not outrageously inefficient --- all
> Python method access is
> done through attribute lookup anyway --- but it's
> just something that most
> Python programmers won't recognize at first.

So you're saying it's a bad idea because people won't
recognize it at first? Well, I guess I'll just make it
for my personal use, then.
Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Exclusive Video Premiere - Britney Spears
http://launch.yahoo.com/promos/britneyspears/

From fredm at smartypantsco.com  Thu Oct 30 19:44:26 2003
From: fredm at smartypantsco.com (Alfred Milgrom)
Date: Thu Oct 30 19:44:09 2003
Subject: [Tutor] What am I doing wrong here in Tkinter?
Message-ID: <5.1.0.14.0.20031031112953.0342fd50@192.168.1.1>

Hi:

I am using Tkinter in Windows, but I am obviously doing something wrong in 
my code.

The following code creates a TKinter window and then tries to get the x,y 
coordinates using winfo_rootx(), etc.
When I run the code, I get correct answers for winfo_name()  and winfo_id() 
but not for winfo_rootx() (it always returns 0!)

This incorrect behaviour disappears if I insert a line to say "a = self" 
(see code below)
This seems to say to me that I have not set something correctly in the 
program, but I can't see what.

Running the following code gives me the following output:

winfo_rootx() says tk 3808 starts at 0
But now it says tk 3808 starts at 112

Can someone point me in the right direction?
Thanks in advance,
Fred Milgrom

#---------------------------------------------------------------------------

# Test of winfo_rootx()

from Tkinter import *

class GUI (Frame):
     top = Tk()

     def __init__(self, parent=top):
         global cols
         Frame.__init__(self,parent)
         self.master.title('Test of winfo_rootx()')
         self.buildUI()

     def buildUI(self):
         self.goBoard = Canvas(self, width=400 , height=400 , border = 2, 
bg="#FFE14B")
         self.goBoard.pack(side=TOP, padx=10, pady=10)

         fButtons = Frame(self)
         self.bQuit = Button(fButtons, text="Quit", command=self.top.destroy)
         self.bQuit.pack(side=LEFT, anchor=W, padx=10, pady=2)
         fButtons.pack(side=BOTTOM, fill=X)
         self.pack()

     def getcoords(self):
         print "winfo_rootx() says %s %s starts at %d" 
%(self.top.winfo_name(), self.top.winfo_id(), self.top.winfo_rootx())
         a = self
         print "But now it says %s %s starts at %d" 
%(self.top.winfo_name(), self.top.winfo_id(), self.top.winfo_rootx())

board = GUI()
board.getcoords()

#---------------------------------------------------------------------------



From glingl at aon.at  Thu Oct 30 20:24:18 2003
From: glingl at aon.at (Gregor Lingl)
Date: Thu Oct 30 20:26:15 2003
Subject: [Tutor] What am I doing wrong here in Tkinter?
In-Reply-To: <5.1.0.14.0.20031031112953.0342fd50@192.168.1.1>
References: <5.1.0.14.0.20031031112953.0342fd50@192.168.1.1>
Message-ID: <3FA1B9C2.8060106@aon.at>



Alfred Milgrom schrieb:

> Hi:
>
> I am using Tkinter in Windows, but I am obviously doing something 
> wrong in my code.

I think you are doing nothing wrong - except that you are not calling 
mainloop()
which is correct if you are working with IDLE (version < 1.0).

If you run your program from the commandline you will observe: no window 
appears,
but getccords outputs 0 twice. So this are the values before the window 
manager manages
to paint your window.
After a certain delay (or something, which causes painting of your 
window) you get
the values of the painted window.

Try the following experiment: changhe your program like this:

from Tkinter import *
from time import sleep

class GUI (Frame):
    top = Tk()

    def __init__(self, parent=top):
        global cols
        Frame.__init__(self,parent)
        self.master.title('Test of winfo_rootx()')
        self.buildUI()

    def buildUI(self):
        self.goBoard = Canvas(self, width=400 , height=400 , border = 2, 
bg="#FFE14B")
        self.goBoard.pack(side=TOP, padx=10, pady=10)

        fButtons = Frame(self)
        self.bQuit = Button(fButtons, text="get coords", 
command=self.getcoords)   ### <=== bind getccords
        self.bQuit.pack(side=LEFT, anchor=W, padx=10, pady=2)
        fButtons.pack(side=BOTTOM, fill=X)
        self.pack()

    def getcoords(self):
        print "winfo_rootx() says %s %s starts at %d" 
%(self.top.winfo_name(), self.top.winfo_id(), self.top.winfo_rootx()) 
       ###  a = self
        print "But now it says %s %s starts at %d" 
%(self.top.winfo_name(), self.top.winfo_id(), self.top.winfo_rootx())

board = GUI()
board.getcoords()
mainloop()                   ### <======

and start it from the commandline. Observe the output, push the button 
and observe the output again.
Here the first time board.getcoords() is called  before mainloop() is 
invoked, i.e. before the window is painted.
The next time - when you push the butten - the window is already here ;-)
(You will get the same results when working with IDLE 1.0 under Python 2.3)

When working from IDLE (old version, Python 2.2 or less) IDLE's own 
mainloop governs all events
(especially painting events) - IDLE's own events and your app's events. 
So it's hard to predict
when what happens in your application.

HTH
Gregor




>
> The following code creates a TKinter window and then tries to get the 
> x,y coordinates using winfo_rootx(), etc.
> When I run the code, I get correct answers for winfo_name()  and 
> winfo_id() but not for winfo_rootx() (it always returns 0!)
>
> This incorrect behaviour disappears if I insert a line to say "a = 
> self" (see code below)
> This seems to say to me that I have not set something correctly in the 
> program, but I can't see what.
>
> Running the following code gives me the following output:
>
> winfo_rootx() says tk 3808 starts at 0
> But now it says tk 3808 starts at 112
>
> Can someone point me in the right direction?
> Thanks in advance,
> Fred Milgrom
>
> #--------------------------------------------------------------------------- 
>
>
> # Test of winfo_rootx()
>
> from Tkinter import *
>
> class GUI (Frame):
>     top = Tk()
>
>     def __init__(self, parent=top):
>         global cols
>         Frame.__init__(self,parent)
>         self.master.title('Test of winfo_rootx()')
>         self.buildUI()
>
>     def buildUI(self):
>         self.goBoard = Canvas(self, width=400 , height=400 , border = 
> 2, bg="#FFE14B")
>         self.goBoard.pack(side=TOP, padx=10, pady=10)
>
>         fButtons = Frame(self)
>         self.bQuit = Button(fButtons, text="Quit", 
> command=self.top.destroy)
>         self.bQuit.pack(side=LEFT, anchor=W, padx=10, pady=2)
>         fButtons.pack(side=BOTTOM, fill=X)
>         self.pack()
>
>     def getcoords(self):
>         print "winfo_rootx() says %s %s starts at %d" 
> %(self.top.winfo_name(), self.top.winfo_id(), self.top.winfo_rootx())
>         a = self
>         print "But now it says %s %s starts at %d" 
> %(self.top.winfo_name(), self.top.winfo_id(), self.top.winfo_rootx())
>
> board = GUI()
> board.getcoords()
>
> #--------------------------------------------------------------------------- 
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>


From dyoo at hkn.eecs.berkeley.edu  Thu Oct 30 20:46:39 2003
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Oct 30 20:47:05 2003
Subject: [Tutor] Importing from classes or functions
In-Reply-To: <20031031004213.28021.qmail@web41802.mail.yahoo.com>
Message-ID: <Pine.LNX.4.44.0310301715250.27144-100000@hkn.eecs.berkeley.edu>


> > Think of 'import math' as a statement that creates a local variable
> > called 'math'.  Then the error message should be less mysterious:
> >
> > > >>> class sinnum(int):
> > > ...     def __init__(s, number):
> > > ...         import math
> > > ...         s.num = number
> > > ...     def sin(s):
> > > ...         return math.sin(s)
> > > ...
> > > >>> x = sinnum(5)
> > > >>> x.sin()
> > > Traceback (most recent call last):
> > >   File "<input>", line 1, in ?
> > >   File "<input>", line 6, in sin
> > > NameError: global name 'math' is not defined
> >
> >
> > 'math' here is a local variable within __init__, so it won't be
> > visible from the 'sin()' function.  So the error is actually not too
> > serious: it's a scope issue.
>
> No, when I tried importing math outside of the __init__ function, it
> didn't do anything.


Hi Daniel,


Let's go back for a moment.  The situation is simliar to something like
this:

###
class TestScope1:
    def __init__(self):
        x = 42

    def test(self):
        print x
###

This breaks with a familiar "NameError" exception because, in test(),
Python has no idea what 'x' means.  So the reason TestScope1 breaks is the
same reason that:

###
class sinnum(int):
    def __init__(s, number):
        import math
        s.num = number
    def sin(s):
        return math.sin(s)
###

breaks.



If we actually wanted to squirrel the value as part of the state of that
TestScope1 instance, we can say something like:

###
class TestScope1_fixed:
    def __init__(self):
        self.x = 42

    def test(self):
        print self.x
###

and we can fix sinnum() by using a similar approach.


> Someone else on the list suggested using the __import__ function (not
> definition, just using the function), and it worked.

True.  But there's nothing special about __import__().  Compare the
__import__() example with:

###
class sinnum(int):
    def __init__(self, number):
        self.num = number
        import math
        self.math = math

    def sin(self):
        return self.math.sin(self)
###

Does that make sense?  Please feel free to ask questions about this, as
variable name scope is a useful concept.




I'm actively trying to ignore the first part of your question:

> > >>> class sinnum(int):
> > ...     def __getattr__(self, attr):
> > ...         def f(*args):
> > ...             return apply(getattr(__builtins__,
> > attr),
> > ...                          (self,) + args)
> > ...         return f
> > ###
> >
> Would you mind explaining that code? I can't understand it, and it
> doesn't seem to work if you're using namespaces. I'd like it to work so
> that the math module is imported locally and math functions can be used
> without namespaces.


because I haven't figured out how to explain it well yet.  *grin*


Talk to you later!


From abli at freemail.hu  Fri Oct 31 00:30:19 2003
From: abli at freemail.hu (Abel Daniel)
Date: Fri Oct 31 00:31:21 2003
Subject: [Tutor] Re: Python vs. Ruby
In-Reply-To: <3FA1AAD3.3070600@aon.at> (Gregor Lingl's message of "Fri, 31
	Oct 2003 01:20:35 +0100")
References: <00c101c39ec5$2aaa5de0$6401a8c0@xp>
	<20031030221023.32463.qmail@web41810.mail.yahoo.com>
	<1b4mbgghafw3c$.14tedktzha88e$.dlg@40tude.net>
	<3FA1AAD3.3070600@aon.at>
Message-ID: <E1AFRrh-0001t9-00@hooloovoo>


Gregor Lingl writes:
> On the other hand there are types of objects, e.g. type 'function',
> which cannot be subclassed as far as I know (and regret).
>
> Testtask: is it possible to subclass (numerical)  functions - say this
> new class is named Fun - e.g. by adding a __add__ method, in a
> way that their instances can be added, like:
>  >>> from math import sin, cos
>  >>> f = Fun(sin) + Fun(cos)   ### see remark below
>  >>> f(1)
> #### should output sin(1)+cos(1)
> In short: it would be nice to create some sort of function algebra.
>
> In Python this seems a bit weird because of the special
> way functions are defined (namely via the reserved word def).
> So how should (or could) one define a "fun"? Maybe by making
> it "callable" somehow? (Oh, I feel that this is not a very sharply
> defined problem ...)
Well, here is a shot at it:

class Fun:
    def __init__(self, func):
        self.func=func
    
    def __call__(self, *a, **kw):
        return self.func(*a, **kw)

    def __add__(self, other):
        def f(*a, **kw):
            return self.func(*a, **kw) + other(*a, **kw)
        return Fun(f)

>>> from math import sin, cos
>>> fc=Fun(cos)
>>> fs=Fun(sin)
>>> fcs=fc+fs
>>> fc(1)+fs(1)
1.3817732906760363
>>> fcs(1)
1.3817732906760363
>>> 

Finishing up (adding other stuff from
http://python.org/doc/current/ref/numeric-types.html
and handling things like "Fun(math.sin) + 5" ) are left as an exercise
to the reader. :)

Of course Fun instances won't be functions, but the interface is the same
(they can be called), so it shouldn't matter.

-- 
Abel Daniel 

From phthenry at earthlink.net  Fri Oct 31 01:10:06 2003
From: phthenry at earthlink.net (Paul Tremblay)
Date: Fri Oct 31 01:10:20 2003
Subject: [Tutor] test if file is not ascii
Message-ID: <20031031061006.GA18340@localhost.localdomain>

Is there any relatively fast, easy way to test if a file is not ascii?

I have written a script that converts RTF to XML. An RTF file should be
ascii encoded. If not, it will result in invalid XML.

It would be nice to test the file before the conversion begins to tell
the user "Sorry, but this file is not valid RTf."

Thanks

Paul

-- 

************************
*Paul Tremblay         *
*phthenry@earthlink.net*
************************

From abli at freemail.hu  Fri Oct 31 01:37:05 2003
From: abli at freemail.hu (Abel Daniel)
Date: Fri Oct 31 01:38:19 2003
Subject: [Tutor] Re: test if file is not ascii
In-Reply-To: <20031031061006.GA18340@localhost.localdomain> (Paul Tremblay's
	message of "Fri, 31 Oct 2003 01:10:06 -0500")
References: <20031031061006.GA18340@localhost.localdomain>
Message-ID: <E1AFSuB-0001wx-00@hooloovoo>


Paul Tremblay writes:
> Is there any relatively fast, easy way to test if a file is not ascii?
>
> I have written a script that converts RTF to XML. An RTF file should be
> ascii encoded. If not, it will result in invalid XML.
>
> It would be nice to test the file before the conversion begins to tell
> the user "Sorry, but this file is not valid RTf."

You could try decoding it and catch the exception:

>>> ''.decode('us-ascii')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe1 in position 0: ordinal not in range(128)
>>> 'asdfsdfg'.decode('us-ascii')
u'asdfsdfg'
>>> 

-- 
Abel Daniel

From alan.gauld at blueyonder.co.uk  Fri Oct 31 03:59:48 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Fri Oct 31 03:59:31 2003
Subject: [Tutor] More confusion on conversion
References: <CA3458C84C976E45B6372A6C14724C9F9E597E@ridmsem02.nala.roche.com>
	<1067548186.6379.66.camel@pika> <014e01c39f42$36bd0100$6401a8c0@xp>
	<1067560566.6379.77.camel@pika>
Message-ID: <016a01c39f8d$56405e50$6401a8c0@xp>


> Just for my own clarification, what string terminator is sent?  Not
> knowing exactly what port is, I assumed that when Vicki sent the 2
> characters, one after the other, that it would be equivalent to
sending
> a 2 byte string.

A string is a sequence of characters followed by a string terminator
- usually ASCII zero (aka the NULL character). This is true in most
modern languages. Pascal derivitives on the other hand usually store
strings as a count followed by the characters, so in C based languages
like Python

'0A' = '0'+'A'+'\0'

In Pascal based languages it would be:

'0A' = 2 + '0' + 'A'

So in either case sending the string '0A' actually sends
three bytes.

If you think about it it has to be so, since a string could
be arbitrarily long how else would the receiving end know where
the string ended?

Alan G.


From alan.gauld at blueyonder.co.uk  Fri Oct 31 04:12:36 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Fri Oct 31 04:12:22 2003
Subject: [Tutor] Python vs. Ruby
References: <20031030221023.32463.qmail@web41810.mail.yahoo.com>
Message-ID: <018101c39f8f$202dd480$6401a8c0@xp>

> > I've used OO long enough to know there are times
> > when it ain't the best answer...
> 
> When not? 
> Isn't everything in Python an object, to some degree?

Yes, but Python doesn't insist that you use an OO approach 
to the solution - as Ruby and Java do. You can write short 
non OO programs in Ruby because there is an outer implies 
class but once you get to bigger programs it becomes 
difficult to create non OO modules, It's not impossible 
but you have to work harder than in Python.

Many problems are better solved using a functional 
programming approach. Others are more amenable to a 
traditional imperative approach(ie procedural).

This is very true of batch programming where you traverse 
a sequence of data applying some algorithm to each 
item in the file. You can do it with objects but 
usually there is little advantage.

Similarly very short programs rarely need the overhead of 
classes - it just increases the code count for little gain.

Think of code libraries - look at Pythons as an example 
- very few of the utility type libraries use an OO design.
Think of the Unix command line programs, most of them can 
be written far more easily using simple functions than 
by using objects.

[ Also the C++ standard library(the STL) is quite deliberately 
non OO, it uses a functional programming approach. That 
was done deliberately to make it as widely applicable as 
possible. ]

OO really comes into its own where the problem gets bigger, 
there are several instances of the same entities in memory 
at one time, the entities have a lot of similarity etc.

So OO is very powerful and appropriate in many (probably most) 
situations, but it is not the only solution. "When all you 
have is a hammer, every problem looks like a nail" applies 
in computing just as much as anywhere else!

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld




From alan.gauld at blueyonder.co.uk  Fri Oct 31 04:17:27 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Fri Oct 31 04:17:08 2003
Subject: [Tutor] Re: Re: Python vs. Ruby  [where to find more about Ruby]
References: <Pine.LNX.4.44.0310291615030.20823-100000@hkn.eecs.berkeley.edu><200310301728.37678.tbstep@tampabay.rr.com><bqhllbrrrar6$.12p7pn8vnxevu$.dlg@40tude.net>
	<200310301909.26166.tbstep@tampabay.rr.com>
Message-ID: <019601c39f8f$cdafdc20$6401a8c0@xp>

> manner.  I had thought that Konq was one of the most 
> standards-compliant browsers.

Maybe but its also buggy. Konquerer's engine is the one used 
by Apple in their Safari browser - which is now my preferred 
Mac brower - but it often finds pages that it doesn't 
display quite right, and it's nothing to do with the HTML 
it's the graphics rendering engine getting itself tied in 
knots. :-(

Alan G.

From project5 at redrival.net  Fri Oct 31 05:36:59 2003
From: project5 at redrival.net (Andrei)
Date: Fri Oct 31 05:39:19 2003
Subject: [Tutor] Re: Re: Python vs. Ruby
References: <00c101c39ec5$2aaa5de0$6401a8c0@xp>	<20031030221023.32463.qmail@web41810.mail.yahoo.com>
	<1b4mbgghafw3c$.14tedktzha88e$.dlg@40tude.net>
	<3FA1AAD3.3070600@aon.at>
Message-ID: <an72r7esxff4$.1tgmnsfqoqhkm.dlg@40tude.net>

Gregor Lingl wrote on Fri, 31 Oct 2003 01:20:35 +0100:

<snip>
> at least this last example is not so much different from Python:
> 
>  >>> 5.0.__add__(3)
> 8.0
>  >>>

Actually, my original intention was to use 5.+ 3 in Ruby, since this
doesn't seem to work in Python. 5.0.+ was more illustrative since 5.+ 3
returning 8 could be interpreted as Ruby being 'smart' and returning an
integer when adding a float and an integer :).

>>> 5.__add__(3)
  File "<input>", line 1
    5.__add__(3)
            ^
SyntaxError: invalid syntax
>>> int(5).__add__(3)
8

> which shows that in Python + also is only some sort of syntactical
> sugar.

class Tt
  def initialize(val)
    @val = val
  end
  def +(newval)
    @val + newval +1
  end
end
x = Tt.new(5)
x + 2
- - - - - - - - - - - - - - - 
=> 8

When was the last time you named a method "+" in Python? :) But it does
indeed show that the differences between the languages are mostly
skin-deep, since you can achieve the same in Python. It's just that you
can't call it "+".

> Testtask: is it possible to subclass (numerical)  functions - say this
> new class is named Fun - e.g. by adding a __add__ method, in a
> way that their instances can be added, like:
>  >>> from math import sin, cos
>  >>> f = Fun(sin) + Fun(cos)   ### see remark below
>  >>> f(1)
> #### should output sin(1)+cos(1)

from math import *

class Fun:
    def __init__(self, *funcs):
        self.funcs = []
        self.funcs.extend(funcs)
    def __add__(self, func):
        self.funcs.extend(func.funcs)
        return Fun(*self.funcs)
    def __call__(self, *args):
        results = [ f(*args) for f in self.funcs ]
        return sum(results)
        
f = Fun(sin) + Fun(cos)
for i in range(1000):
    if f(i) != sin(i)+cos(i):
        print "Error @",i

> Is a task of this sort more easily ( and/or more
> in accordance with the philosophy of the language)
> solvable in Ruby?

I figured it out in Python, but I don't know enough Ruby to do it off-hand.
But I'll bet it's possible.

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V
ernq gur yvfg, fb gurer'f ab arrq gb PP.


From op73418 at mail.telepac.pt  Fri Oct 31 06:13:26 2003
From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=)
Date: Fri Oct 31 06:12:00 2003
Subject: [Tutor] Re: Re: Python vs. Ruby
In-Reply-To: <an72r7esxff4$.1tgmnsfqoqhkm.dlg@40tude.net>
References: <00c101c39ec5$2aaa5de0$6401a8c0@xp>	<20031030221023.32463.qmail@web41810.mail.yahoo.com>
	<1b4mbgghafw3c$.14tedktzha88e$.dlg@40tude.net>
	<3FA1AAD3.3070600@aon.at>
	<an72r7esxff4$.1tgmnsfqoqhkm.dlg@40tude.net>
Message-ID: <hpg4qvg7oh0tg8lt3qp7u1v3qt53dgvo8h@4ax.com>

On Fri, 31 Oct 2003 11:36:59 +0100, you wrote:

>Gregor Lingl wrote on Fri, 31 Oct 2003 01:20:35 +0100:
>
><snip>
>> at least this last example is not so much different from Python:
>> 
>>  >>> 5.0.__add__(3)
>> 8.0
>>  >>>
>
>Actually, my original intention was to use 5.+ 3 in Ruby, since this
>doesn't seem to work in Python. 5.0.+ was more illustrative since 5.+ 3
>returning 8 could be interpreted as Ruby being 'smart' and returning an
>integer when adding a float and an integer :).
>
>>>> 5.__add__(3)
>  File "<input>", line 1
>    5.__add__(3)
>            ^
>SyntaxError: invalid syntax
>>>> int(5).__add__(3)
>8

It's a parser "problem", the dot has two possible meanings. Use
parenthesis to disambiguate, e.g.

>>> (5.).__add__(3)
8.0
>>> 

With my best regards,
G. Rodrigues

From glingl at aon.at  Fri Oct 31 07:55:00 2003
From: glingl at aon.at (Gregor Lingl)
Date: Fri Oct 31 07:57:00 2003
Subject: [Tutor] Re: Re: Python vs. Ruby
In-Reply-To: <an72r7esxff4$.1tgmnsfqoqhkm.dlg@40tude.net>
References: <00c101c39ec5$2aaa5de0$6401a8c0@xp>	<20031030221023.32463.qmail@web41810.mail.yahoo.com>	<1b4mbgghafw3c$.14tedktzha88e$.dlg@40tude.net>	<3FA1AAD3.3070600@aon.at>
	<an72r7esxff4$.1tgmnsfqoqhkm.dlg@40tude.net>
Message-ID: <3FA25BA4.4060705@aon.at>



Andrei schrieb:

>Actually, my original intention was to use 5.+ 3 in Ruby, since this
>doesn't seem to work in Python. 5.0.+ was more illustrative since 5.+ 3
>returning 8 could be interpreted as Ruby being 'smart' and returning an
>integer when adding a float and an integer :).
>
>  
>
>>>>5.__add__(3)
>>>>        
>>>>
>  File "<input>", line 1
>    5.__add__(3)
>            ^
>SyntaxError: invalid syntax
>  
>
>>>>int(5).__add__(3)
>>>>        
>>>>
>8
>  
>
 >>> (5).__add__(3)
8
 >>>

suffices (the parentheses beeing necessary to prevent Python
interpreting 5. as a float).

Gregor


From ms_barry2000 at yahoo.com  Fri Oct 31 09:01:22 2003
From: ms_barry2000 at yahoo.com (=?iso-8859-1?q?Marc=20Barry?=)
Date: Fri Oct 31 09:01:26 2003
Subject: [Tutor] Determining systems maximum float value
Message-ID: <20031031140122.52416.qmail@web11701.mail.yahoo.com>

Dear All:

This is a rather simple question (perhaps) and I have searched the archives and
haven't found an answer for it.

Basically, I want to know how to determine the maximum supported float value of
the underlying system that the Python interpreter is running on. I know that
floats are implemented using double in C and thus their maximum value depends
on the system. For example, python has a function in module 'sys' that gives
the maximum integer value:

#-----

import sys

print sys.maxint

#-----

How can this be determined for floats?

Regards,

Marc

________________________________________________________________________
Want to chat instantly with your online friends?  Get the FREE Yahoo!
Messenger http://mail.messenger.yahoo.co.uk

From vicki at thepenguin.org  Fri Oct 31 09:09:10 2003
From: vicki at thepenguin.org (Vicki Stanfield)
Date: Fri Oct 31 09:11:45 2003
Subject: [Tutor] More confusion on conversion
In-Reply-To: <1067548186.6379.66.camel@pika>
References: <CA3458C84C976E45B6372A6C14724C9F9E597E@ridmsem02.nala.roche.com> 
	<1067548186.6379.66.camel@pika>
Message-ID: <18552.206.53.226.235.1067609350.squirrel@www.thepenguin.org>

> In my last mail I had a bit of a brain freeze :-(.  '0' is not 0, but is
> in fact 48 or 0x30 or 00110000.  This means that
>
> port.write('\x30')
> port.write('\x41')
>
> should be equivalent to
>
> port.write('0A')
>
> which is equivalent to
>
> length = 10
> port.write('%02X' % length)  # one of my previous suggestions
>
> so I don't see why that isn't working for you.  Hopefully someone else
> can see the error of my ways and point you in the right direction.
>
> Reggie

I'm still trying to iron this one out, but the reason that the
port.write('0A') doesn't work is because I need to add a slight delay
between the two bytes. I thought I said that before, but I might not have.
This whole mess frustrates me.

I am trying the different suggestions that I received last night. I will
post what works.

--vicki

From vicki at thepenguin.org  Fri Oct 31 09:29:11 2003
From: vicki at thepenguin.org (Vicki Stanfield)
Date: Fri Oct 31 09:33:11 2003
Subject: [Tutor] More confusion on conversion
In-Reply-To: <5.1.0.14.2.20031030233904.026a9940@mail.30below.com>
References: <5.1.0.14.2.20031030144014.055238a8@mail.30below.com><5.1.0.14.2.20031
	030132957.05406f18@mail.30below.com><49834.206.53.226 
	.235.1067537960.squirrel@www.thepenguin.org><5.1.0.14.2.20031030132957
	.05406f18@mail.30below.com><5.1.0.14.2.20031030144014.055238a8@mail.3
	0below.com> <5.1.0.14.2.20031030233904.026a9940@mail.30below.com>
Message-ID: <35029.206.53.226.235.1067610551.squirrel@www.thepenguin.org>

I'm about ready to go batty (wasn't intended as a Halloween pun, but I'll
take it). I am so close with the following code:

hexlength = '02X' % length
print hexlength
for each in hexlength:
     port.write(each)
     time.sleep(.01)

but it generates an error:

hexlength = '02X' % length
TypeError: not all arguments converted

I print the length, and it is 10. That is 2 characters, right? Or is it 3
with the terminator? If I set hexlength to '0A', it does what I want, but
unfortunately, it is a variable.

--vicki

From abli at freemail.hu  Fri Oct 31 09:48:00 2003
From: abli at freemail.hu (Abel Daniel)
Date: Fri Oct 31 09:48:26 2003
Subject: [Tutor] function algebra (was: Re: Python vs. Ruby)
In-Reply-To: <E1AFRrh-0001t9-00@hooloovoo> (Abel Daniel's message of "Fri,
	31 Oct 2003 06:30:19 +0100")
References: <00c101c39ec5$2aaa5de0$6401a8c0@xp>
	<20031030221023.32463.qmail@web41810.mail.yahoo.com>
	<1b4mbgghafw3c$.14tedktzha88e$.dlg@40tude.net>
	<3FA1AAD3.3070600@aon.at> <E1AFRrh-0001t9-00@hooloovoo>
Message-ID: <E1AFaZI-0002RM-00@hooloovoo>


[ me, a bit earlier: ]
> Finishing up (adding other stuff from
> http://python.org/doc/current/ref/numeric-types.html
> and handling things like "Fun(math.sin) + 5" ) are left as an exercise
> to the reader. :)
I couldn't stand not doing it :)
It's a bit less readable, but should handle any numerical operation.
It also handles the case of "f=Fun(math.sin) + 5" (so that in this case
f(x) will be math.sin(x) + 5), plus it does composition:

>>> cos=Fun(math.cos)
>>> cs = cos.compose(math.sin)
>>> cs(1)
0.66636674539288054
>>> math.cos(math.sin(1))
0.66636674539288054
>>> 

------8<-------------
# we don't need to add __iadd__ and such as those fall back to using
# __add__ etc.
unary_operators=['__neg__', '__pos__', '__abs__', '__invert__',
                 '__complex__', '__int__', '__long__', '__float__',
                 '__oct__', '__hex__']
binary_operators=['__add__','__sub__','__mul__', '__floordiv__',
                  '__mod__', '__divmod__', '__lshift__', '__rshift__',
                  '__and__', '__xor__', '__or__', '__radd__',
                  '__rsub__', '__rmul__', '__rdiv__', '__rtruediv__',
                  '__rfloordiv__', '__rmod__', '__rdivmod__',
                  '__rpow__', '__rlshift__', '__rrshift__',
                  '__rand__', '__rxor__', '__ror__']
ternary_operators=['__pow__']

class Fun:
    def __init__(self, func):
        self.func=func

    def __call__(self, *a, **kw):
        return self.func(*a, **kw)

    def compose(self, other):
        def f(*a, **kw):
            return self.func(other(*a, **kw))
        return Fun(f)

    def __getattr__(self, name):
        if name in binary_operators:
            return self.binary_operation(name)
        elif name in unary_operators:
            return self.unary_operation(name)
        elif name in ternary_operators:
            return self.ternary_operation(name)
        else:
            raise AttributeError

    def binary_operation(self, name):
        def ff(other):
            def f(*a, **kw):
                return getattr(self.func(*a, **kw), name)(other(*a, **kw))
            return Fun(f)
        return ff

    def unary_operation(self, name):
        def ff():
            def f(*a, **kw):
                return getattr(self.func(*a, **kw), name)()
            return Fun(f)
        return ff

    def ternary_operation(self, name):
        def ff(other, *args):
            def f(*a, **kw):
                return getattr(self.func(*a, **kw), name)(other(*a, **kw),
                                                          *args)
            return Fun(f)
        return ff

    def __coerce__(self, other):
        if callable(other):
            return self, other
        else:
            return self, lambda x: other

-----------8<-------------------

-- 
Abel Daniel

From zmerch at 30below.com  Fri Oct 31 09:49:40 2003
From: zmerch at 30below.com (Roger Merchberger)
Date: Fri Oct 31 09:53:09 2003
Subject: [Tutor] More confusion on conversion
In-Reply-To: <35029.206.53.226.235.1067610551.squirrel@www.thepenguin.or
 g>
References: <5.1.0.14.2.20031030233904.026a9940@mail.30below.com>
	<5.1.0.14.2.20031030144014.055238a8@mail.30below.com>
	<5.1.0.14.2.20031 030132957.05406f18@mail.30below.com>
	<49834.206.53.226  .235.1067537960.squirrel@www.thepenguin.org>
	<5.1.0.14.2.20031030132957 .05406f18@mail.30below.com>
	<5.1.0.14.2.20031030144014.055238a8@mail.3 0below.com>
	<5.1.0.14.2.20031030233904.026a9940@mail.30below.com>
Message-ID: <5.1.0.14.2.20031031094831.02e0e758@mail.30below.com>

At 09:29 10/31/2003 -0500, Vicki Stanfield wrote:
>I'm about ready to go batty (wasn't intended as a Halloween pun, but I'll
>take it). I am so close with the following code:
>
>hexlength = '02X' % length

This should be:

hexlength = '%02X' % length

This should give you what you want...

HTH,
Roger "Merch" Merchberger



--
Roger "Merch" Merchberger   ---   sysadmin, Iceberg Computers
Recycling is good, right???  Randomization is better!!!

If at first you don't succeed, nuclear warhead
disarmament should *not* be your first career choice.


From abli at freemail.hu  Fri Oct 31 09:57:20 2003
From: abli at freemail.hu (Abel Daniel)
Date: Fri Oct 31 09:58:12 2003
Subject: [Tutor] Re: Python vs. Ruby
In-Reply-To: <an72r7esxff4$.1tgmnsfqoqhkm.dlg@40tude.net>
	(project5@redrival.net's
	message of "Fri, 31 Oct 2003 11:36:59 +0100")
References: <00c101c39ec5$2aaa5de0$6401a8c0@xp>
	<20031030221023.32463.qmail@web41810.mail.yahoo.com>
	<1b4mbgghafw3c$.14tedktzha88e$.dlg@40tude.net>
	<3FA1AAD3.3070600@aon.at> <an72r7esxff4$.1tgmnsfqoqhkm.dlg@40tude.net>
Message-ID: <E1AFaiI-0002Rr-00@hooloovoo>

Andrei  writes:
> class Fun:
>     def __init__(self, *funcs):
>         self.funcs = []
>         self.funcs.extend(funcs)
>     def __add__(self, func):
>         self.funcs.extend(func.funcs)
>         return Fun(*self.funcs)
>     def __call__(self, *args):
>         results = [ f(*args) for f in self.funcs ]
>         return sum(results)
>

This will behave suprisingly:

>>>import math
>>>sin=Fun(math.sin)
>>>cos=Fun(math.cos)
>>>f = sin + cos
>>>print sin(1)
will give the wrong result.

Doing C = A + B shouldn't change A or B.

-- 
Abel Daniel

From vicki at thepenguin.org  Fri Oct 31 09:55:55 2003
From: vicki at thepenguin.org (Vicki Stanfield)
Date: Fri Oct 31 09:58:43 2003
Subject: [Tutor] More confusion on conversion
In-Reply-To: <5.1.0.14.2.20031031094831.02e0e758@mail.30below.com>
References: <5.1.0.14.2.20031030233904.026a9940@mail.30below.com><5.1.0.14.2.20031
	030144014.055238a8@mail.30below.com><5.1.0.14.2.20031 
	030132957.05406f18@mail.30below.com><49834.206.53.226  
	.235.1067537960.squirrel@www.thepenguin.org><5.1.0.14.2.20031030132957
	.05406f18@mail.30below.com><5.1.0.14.2.20031030144014.055238a8@mail.3
	0below.com><5.1.0.14.2.20031030233904.026a9940@mail.30below.com> 
	<5.1.0.14.2.20031031094831.02e0e758@mail.30below.com>
Message-ID: <14839.206.53.226.235.1067612155.squirrel@www.thepenguin.org>

> At 09:29 10/31/2003 -0500, Vicki Stanfield wrote:
>>I'm about ready to go batty (wasn't intended as a Halloween pun, but I'll
>>take it). I am so close with the following code:
>>
>>hexlength = '02X' % length
>
> This should be:
>
> hexlength = '%02X' % length
>
> This should give you what you want...
>
> HTH,
> Roger "Merch" Merchberger

This appears to work. Thanks so much.

--vicki

From zmerch at 30below.com  Fri Oct 31 10:00:59 2003
From: zmerch at 30below.com (Roger Merchberger)
Date: Fri Oct 31 10:04:25 2003
Subject: [Tutor] Re: Re: Python vs. Ruby
In-Reply-To: <an72r7esxff4$.1tgmnsfqoqhkm.dlg@40tude.net>
References: <00c101c39ec5$2aaa5de0$6401a8c0@xp>
	<20031030221023.32463.qmail@web41810.mail.yahoo.com>
	<1b4mbgghafw3c$.14tedktzha88e$.dlg@40tude.net>
	<3FA1AAD3.3070600@aon.at>
Message-ID: <5.1.0.14.2.20031031095737.029245a8@mail.30below.com>

At 11:36 10/31/2003 +0100, Andrei wrote:
>Gregor Lingl wrote on Fri, 31 Oct 2003 01:20:35 +0100:

[snippety]

>x = Tt.new(5)
>x + 2
>- - - - - - - - - - - - - - -
>=> 8

So ruby thinks 5+2 = 8? It must be the best - it knows that "New Math" and 
everything! :-O

[[ It reminds me of an old math joke I saw once:
    2+2 = 5, for extremely large values of 2! ;-) ]]

Happy Halloween, everyone!
Roger "Merch" Merchberger

--
Roger "Merch" Merchberger   | "Profile, don't speculate."
sysadmin, Iceberg Computers |     Daniel J. Bernstein
zmerch@30below.com          |


From project5 at redrival.net  Fri Oct 31 10:32:52 2003
From: project5 at redrival.net (Andrei)
Date: Fri Oct 31 10:35:11 2003
Subject: [Tutor] Re: Python vs. Ruby
References: <00c101c39ec5$2aaa5de0$6401a8c0@xp>
	<20031030221023.32463.qmail@web41810.mail.yahoo.com>
	<1b4mbgghafw3c$.14tedktzha88e$.dlg@40tude.net>
	<3FA1AAD3.3070600@aon.at>
	<an72r7esxff4$.1tgmnsfqoqhkm.dlg@40tude.net>
	<E1AFaiI-0002Rr-00@hooloovoo>
Message-ID: <1i7rqjolqzwx8$.pgppwby6rjgi$.dlg@40tude.net>

Abel Daniel wrote on Fri, 31 Oct 2003 15:57:20 +0100:

> Andrei  writes:
>> class Fun:
>>     def __init__(self, *funcs):
>>         self.funcs = []
>>         self.funcs.extend(funcs)
>>     def __add__(self, func):
>>         self.funcs.extend(func.funcs)
>>         return Fun(*self.funcs)
>>     def __call__(self, *args):
>>         results = [ f(*args) for f in self.funcs ]
>>         return sum(results)
>>
> 
> This will behave suprisingly:
> 
>>>>import math
>>>>sin=Fun(math.sin)
>>>>cos=Fun(math.cos)
>>>>f = sin + cos
>>>>print sin(1)
> will give the wrong result.
> 
> Doing C = A + B shouldn't change A or B.

Good point. I hadn't done any testing beyond what I'd posted.


-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V
ernq gur yvfg, fb gurer'f ab arrq gb PP.


From pythontutor at venix.com  Fri Oct 31 10:44:07 2003
From: pythontutor at venix.com (Lloyd Kvam)
Date: Fri Oct 31 10:44:26 2003
Subject: [Tutor] More confusion on conversion
In-Reply-To: <49834.206.53.226.235.1067537960.squirrel@www.thepenguin.org>
References: <49834.206.53.226.235.1067537960.squirrel@www.thepenguin.org>
Message-ID: <3FA28347.4040200@venix.com>

Now that you've got working code, I thought I'd add a brief summary.  Please
correct as necessary.

One of the common email encodings is base64 where the message is mapped 6 bits
at a time into printable (8 bit) characters.  This device requires an equivalent
process that maps 4 bits at a time using digits and A-F, the normal uppercase hex
characters.

One extra issue was the need to introduce a delay between each character.

Having done a lot of serial port processing years ago, I have been interested
in following this problem and am glad that you have solved it.

Vicki Stanfield wrote:
> Okay, don't ask me why because the answer I got was "for historical
> reasons", but I have to take the length of something (a decimal value) and
> convert it to its hexadecimal equivalent and then convert that value to
> its hexadecimal equivalent padded to 2 places. The result is something
> like this:
> 
> length = 10
> convert 10 to A
> convert A to 0x41
> padded version = 0x30 0x41
> 
> When I try to convert the decimal 10 using either binascii.hexlify, I am
> told that it wants a single value instead of the two digit 10. How does
> one convert a 10 (decimal value) to its hex equivalent? I don't want the
> hex equivalent of 1 followed by the hex equivalent of 0. The example above
> is exactly what I must achieve.
> 
> --vicki
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582


From glingl at aon.at  Fri Oct 31 11:23:51 2003
From: glingl at aon.at (Gregor Lingl)
Date: Fri Oct 31 11:26:10 2003
Subject: [Tutor] function algebra
In-Reply-To: <E1AFaZI-0002RM-00@hooloovoo>
References: <00c101c39ec5$2aaa5de0$6401a8c0@xp>	<20031030221023.32463.qmail@web41810.mail.yahoo.com>	<1b4mbgghafw3c$.14tedktzha88e$.dlg@40tude.net>	<3FA1AAD3.3070600@aon.at>
	<E1AFRrh-0001t9-00@hooloovoo> <E1AFaZI-0002RM-00@hooloovoo>
Message-ID: <3FA28C97.6010102@aon.at>



Abel Daniel schrieb:

> ...
>
>I couldn't stand not doing it :)
>It's a bit less readable, but should handle any numerical operation.
>It also handles the case of "f=Fun(math.sin) + 5" (so that in this case
>f(x) will be math.sin(x) + 5), plus it does composition:
>  
>

Many thanks for this wonderfully crafted solution to
your "exercise left to the reader"!
Gregor
-----------------
P.S.: I'm still curious if anybody knows why module Canvas of Tkinter
is deprecated.

>------8<-------------
># we don't need to add __iadd__ and such as those fall back to using
># __add__ etc.
>unary_operators=['__neg__',....
>  
>


From reggie at merfinllc.com  Fri Oct 31 12:45:47 2003
From: reggie at merfinllc.com (Reggie Dugard)
Date: Fri Oct 31 12:46:22 2003
Subject: [Tutor] More confusion on conversion
In-Reply-To: <016a01c39f8d$56405e50$6401a8c0@xp>
References: <CA3458C84C976E45B6372A6C14724C9F9E597E@ridmsem02.nala.roche.com>
	<1067548186.6379.66.camel@pika> <014e01c39f42$36bd0100$6401a8c0@xp>
	<1067560566.6379.77.camel@pika>  <016a01c39f8d$56405e50$6401a8c0@xp>
Message-ID: <1067622347.11406.14.camel@pika>

Alan,

It is true that languages such as 'C' use '\0' to terminate strings IN
MEMORY, and the other option, which I believe Python uses for its
strings, is to store a length along with the contents of the string.

This, however, should have no effect on what is actually written by the
write method.  Certainly when sending over a network socket or writing
to a file object, no NULs are written unless you explicitly write them.

It seems that Vicki's problem was that she needed a delay between
characters (a fact which I failed to glean from her e-mails), without
the delay problem "port.write('0'); port.write('A')" should be
equivalent to "port.write('0A').

Reggie

On Fri, 2003-10-31 at 00:59, Alan Gauld wrote:
> > Just for my own clarification, what string terminator is sent?  Not
> > knowing exactly what port is, I assumed that when Vicki sent the 2
> > characters, one after the other, that it would be equivalent to
> sending
> > a 2 byte string.
> 
> A string is a sequence of characters followed by a string terminator
> - usually ASCII zero (aka the NULL character). This is true in most
> modern languages. Pascal derivitives on the other hand usually store
> strings as a count followed by the characters, so in C based languages
> like Python
> 
> '0A' = '0'+'A'+'\0'
> 
> In Pascal based languages it would be:
> 
> '0A' = 2 + '0' + 'A'
> 
> So in either case sending the string '0A' actually sends
> three bytes.
> 
> If you think about it it has to be so, since a string could
> be arbitrarily long how else would the receiving end know where
> the string ended?
> 
> Alan G.
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor



From alan.gauld at blueyonder.co.uk  Fri Oct 31 13:47:44 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Fri Oct 31 13:47:17 2003
Subject: [Tutor] More confusion on conversion
References: <CA3458C84C976E45B6372A6C14724C9F9E597E@ridmsem02.nala.roche.com>
	<1067548186.6379.66.camel@pika> <014e01c39f42$36bd0100$6401a8c0@xp>
	<1067560566.6379.77.camel@pika> <016a01c39f8d$56405e50$6401a8c0@xp>
	<1067622347.11406.14.camel@pika>
Message-ID: <01bc01c39fdf$78669ce0$6401a8c0@xp>

> It is true that languages such as 'C' use '\0' to terminate strings
IN
> MEMORY, and the other option, which I believe Python uses for its
> strings, is to store a length along with the contents of the string.

I stand corrected, I thought Python sent standard C strings
(including the NULL) during I/O operations.

> This, however, should have no effect on what is actually written by
the
> write method.  Certainly when sending over a network socket or
writing
> to a file object, no NULs are written unless you explicitly write
them.

Are you sure? It doesn't send EOL characters but I thought it
did send end of string terminators - ie NULLs?

> It seems that Vicki's problem was that she needed a delay between

Yeah, but I missed that aspect too so can't use that as
any kind of excuse! :-)

Alan G.


From amk at amk.ca  Fri Oct 31 14:12:40 2003
From: amk at amk.ca (amk@amk.ca)
Date: Fri Oct 31 14:12:56 2003
Subject: [Tutor] Tutor summary
In-Reply-To: <20031029200112.3222.qmail@linuxmail.org>
References: <20031029200112.3222.qmail@linuxmail.org>
Message-ID: <20031031191240.GA18503@rogue.amk.ca>

On Wed, Oct 29, 2003 at 08:01:12PM +0000, paul midgley wrote:
> Is there a FAQ from the tutor email group and where can I go to download it.

I don't know of a FAQ specifically for this mailing list (though it's
certainly a good idea).  The general Python FAQs at  
http://www.python.org/doc/faq/ may be helpful.

--amk

From phthenry at earthlink.net  Fri Oct 31 14:19:35 2003
From: phthenry at earthlink.net (Paul Tremblay)
Date: Fri Oct 31 14:19:46 2003
Subject: [Tutor] Re: test if file is not ascii
In-Reply-To: <E1AFSuB-0001wx-00@hooloovoo>
References: <20031031061006.GA18340@localhost.localdomain>
	<E1AFSuB-0001wx-00@hooloovoo>
Message-ID: <20031031191935.GA13823@localhost.localdomain>

On Fri, Oct 31, 2003 at 07:37:05AM +0100, Abel Daniel wrote:
> 
> You could try decoding it and catch the exception:
> 
> >>> ''.decode('us-ascii')
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> UnicodeDecodeError: 'ascii' codec can't decode byte 0xe1 in position 0: ordinal not in range(128)
> >>> 'asdfsdfg'.decode('us-ascii')
> u'asdfsdfg'
> >>> 
> 

Thanks. This is fast. For a huge, 2M file, checking each line only takes
around 19 seconds on my 350MHZ machine.

But I realize there is another problem. Bogus RTF files might contain
characters with the value less than 19, which will also result in
invalid XML. But characters with values less than 19 represent valid
ascii, so the above code will not work.

I have tried this code:

for letter in line:
   char = ord(letter)
   if char < 20:
	sys.stderr.write('File contains illegal characters.\n')
	return 101

But unfortuanately, this code seems to take way too long. It takes about
1 minutes and 45 secnds to process the same file.

I guess I won't do any checking for values less than 20. To do a check
will add quite a bit of time each time a file is processed.

Thanks

Paul 

-- 

************************
*Paul Tremblay         *
*phthenry@earthlink.net*
************************

From zmerch at 30below.com  Fri Oct 31 14:39:37 2003
From: zmerch at 30below.com (Roger Merchberger)
Date: Fri Oct 31 14:43:14 2003
Subject: [Tutor] Re: test if file is not ascii
In-Reply-To: <20031031191935.GA13823@localhost.localdomain>
References: <E1AFSuB-0001wx-00@hooloovoo>
	<20031031061006.GA18340@localhost.localdomain>
	<E1AFSuB-0001wx-00@hooloovoo>
Message-ID: <5.1.0.14.2.20031031142641.029d28a8@mail.30below.com>

At 14:19 10/31/2003 -0500, Paul Tremblay wrote:

[snippety]

>I have tried this code:
>
>for letter in line:
>    char = ord(letter)
>    if char < 20:
>         sys.stderr.write('File contains illegal characters.\n')
>         return 101

Checking each individual char [as you noticed] is insane...

... have you tried a regular expression?

Something like:
=-=-=-=-=-=-=-=

import re

bb = 'this is the search string that I want to see is in it...'
if re.search('[\x00-\x19]',bb):
   print "Yes it's in there"
else:
   Print "No, it's not in there"

=-=-=-=-=-=-=-=

However, I don't know off the top of my head how to specify special 
characters in regexps... What I listed might work, but I didn't have a 
chance to check. However, I would think it would be faster than a 
char-by-char search...

Hope this helps,
Roger "Merch" Merchberger

--
Roger "Merch" Merchberger -- sysadmin, Iceberg Computers
zmerch@30below.com

What do you do when Life gives you lemons,
and you don't *like* lemonade?????????????


From alan.gauld at blueyonder.co.uk  Fri Oct 31 19:09:24 2003
From: alan.gauld at blueyonder.co.uk (Alan Gauld)
Date: Fri Oct 31 19:08:56 2003
Subject: [Tutor] More confusion on conversion
References: <5.1.0.14.2.20031030144014.055238a8@mail.30below.com><5.1.0.14.2.20031030132957.05406f18@mail.30below.com><49834.206.53.226
	.235.1067537960.squirrel@www.thepenguin.org><5.1.0.14.2.20031030132957.05406f18@mail.30below.com><5.1.0.14.2.20031030144014.055238a8@mail.30below.com>
	<5.1.0.14.2.20031030233904.026a9940@mail.30below.com>
	<35029.206.53.226.235.1067610551.squirrel@www.thepenguin.org>
Message-ID: <002501c3a00c$684b8fa0$6401a8c0@xp>


> hexlength = '02X' % length
> TypeError: not all arguments converted

You missed the % sign in the format string.

Alan G.



From emile at fenx.com  Fri Oct 31 23:13:54 2003
From: emile at fenx.com (Emile van Sebille)
Date: Fri Oct 31 23:42:03 2003
Subject: [Tutor] Re: Determining systems maximum float value
References: <20031031140122.52416.qmail@web11701.mail.yahoo.com>
Message-ID: <bnvdik$krv$1@sea.gmane.org>

"Marc Barry"
>
> import sys
>
> print sys.maxint
>
> #-----
>
> How can this be determined for floats?
>
http://groups.google.com/groups?selm=bc82gc%24naf%241%40peabody.colorado.edu

Emile van Sebille
emile@fenx.com




From littledanehren at yahoo.com  Fri Oct 31 23:42:41 2003
From: littledanehren at yahoo.com (Daniel Ehrenberg)
Date: Fri Oct 31 23:42:48 2003
Subject: [Tutor] function algebra
In-Reply-To: <E1AFaZI-0002RM-00@hooloovoo>
Message-ID: <20031101044241.91603.qmail@web41806.mail.yahoo.com>

> I couldn't stand not doing it :)
> It's a bit less readable, but should handle any
> numerical operation.
> It also handles the case of "f=Fun(math.sin) + 5"
> (so that in this case
> f(x) will be math.sin(x) + 5), plus it does
> composition:
> 
> >>> cos=Fun(math.cos)
> >>> cs = cos.compose(math.sin)
> >>> cs(1)
> 0.66636674539288054
> >>> math.cos(math.sin(1))
> 0.66636674539288054
> >>> 
> 
> ------8<-------------
> # we don't need to add __iadd__ and such as those
> fall back to using
> # __add__ etc.
> unary_operators=['__neg__', '__pos__', '__abs__',
> '__invert__',
>                  '__complex__', '__int__',
> '__long__', '__float__',
>                  '__oct__', '__hex__']
> binary_operators=['__add__','__sub__','__mul__',
> '__floordiv__',
>                   '__mod__', '__divmod__',
> '__lshift__', '__rshift__',
>                   '__and__', '__xor__', '__or__',
> '__radd__',
>                   '__rsub__', '__rmul__',
> '__rdiv__', '__rtruediv__',
>                   '__rfloordiv__', '__rmod__',
> '__rdivmod__',
>                   '__rpow__', '__rlshift__',
> '__rrshift__',
>                   '__rand__', '__rxor__', '__ror__']
> ternary_operators=['__pow__']
> 
> class Fun:
>     def __init__(self, func):
>         self.func=func
> 
>     def __call__(self, *a, **kw):
>         return self.func(*a, **kw)
> 
>     def compose(self, other):
>         def f(*a, **kw):
>             return self.func(other(*a, **kw))
>         return Fun(f)
> 
>     def __getattr__(self, name):
>         if name in binary_operators:
>             return self.binary_operation(name)
>         elif name in unary_operators:
>             return self.unary_operation(name)
>         elif name in ternary_operators:
>             return self.ternary_operation(name)
>         else:
>             raise AttributeError
> 
>     def binary_operation(self, name):
>         def ff(other):
>             def f(*a, **kw):
>                 return getattr(self.func(*a, **kw),
> name)(other(*a, **kw))
>             return Fun(f)
>         return ff
> 
>     def unary_operation(self, name):
>         def ff():
>             def f(*a, **kw):
>                 return getattr(self.func(*a, **kw),
> name)()
>             return Fun(f)
>         return ff
> 
>     def ternary_operation(self, name):
>         def ff(other, *args):
>             def f(*a, **kw):
>                 return getattr(self.func(*a, **kw),
> name)(other(*a, **kw),
>                                                     
>      *args)
>             return Fun(f)
>         return ff
> 
>     def __coerce__(self, other):
>         if callable(other):
>             return self, other
>         else:
>             return self, lambda x: other
> 
> -----------8<-------------------
> 
> -- 
> Abel Daniel

I'm sorry, but being a beginner, as many are on this
list, I can't understand that. Would you mind
explaining it or pointing me to a website explaining
something similar?
Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Exclusive Video Premiere - Britney Spears
http://launch.yahoo.com/promos/britneyspears/

From docnova at charter.net  Fri Oct 24 01:10:51 2003
From: docnova at charter.net (docnova)
Date: Wed Nov  5 12:44:37 2003
Subject: [Tutor] Problem with variables
Message-ID: <000801c399ed$366ae5a0$3a229f18@docnova477ccv3>

This program is my first intended project. This program(upon completion) will give a complete (too my limited knowledge) numerology reading upon the input of the users name and birthday. 

There are several problems that I need to figure out how to address. The first (and biggest) is the inuput of the users name. In numerology the one of the core numbers is acheived by adding each letter of the users full name together. As of now the only solution is for the user to enter the name as such "J+O+H+N+S+M+I+T+H".

The ideal scenario would be for "John Smith" to be translated into "J+O+H+N+S+M+I+T+H"

How would I make this action possible?


Here is the source i have so far:

#This program will give a complete numerology rating :)
#Each letter represents a number. Each letter is given its proper value.
a=1;  A=1
b=2;  B=2
c=3; C=3
d=4; D=4
e=5; E=5
f=8; F=8
g=3; G=3
h=5; H=5
i=1; I=1
j=1; J=1
k=2; K=2
l=3; L=3
m=4; M=4
n=5; N=5
o=7; O=7
p=8; P=8
q=1; Q=1
r=2; R=2
s=3; S=3
t=4; T=4
u=6; U=6
v=6; V=6
w=6; W=6
x=6; X=6
y=1; Y=1
z=7; Z=7
print "Welcome"
print "This program will give you a complete numerology rating :)"
name = raw_input("Please enter your full name (first, middle, last): ")
print "Hello there", name +"."
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20031024/72b56a73/attachment.html
From sabineq at wisemail.weizmann.ac.il  Wed Oct 15 12:55:19 2003
From: sabineq at wisemail.weizmann.ac.il (Sabine Ruth Quadt)
Date: Wed Nov  5 12:45:45 2003
Subject: [Tutor] Configuring for Tk
Message-ID: <sf8d92b1.064@wisemail.weizmann.ac.il>

Hallo,

I have a problem configuring Python for Tk.

I changed the file Modules/Setup and uncommented  the lines for tkinter
and edited the lines for my TcL/Tk libraries and headers.
I execute make Makefile.
When I then run mke, I get a lot of error messages about undefined
references like the folowing:

/sabine/SOFTWARE/python/Python-2.3.2/Modules/tkappinit.c:74: undefined
reference to `Tk_MainWindow'


Can someone help me?

Thanks

Sabine

From scalet at yebu.de  Tue Oct 21 03:57:47 2003
From: scalet at yebu.de (Karl Scalet)
Date: Wed Nov  5 12:46:10 2003
Subject: [Tutor] this is ugly
Message-ID: <3F94E6F7.6050701@yebu.de>

Dear Gerhard,

on your example maybe it's worth using
regular expression, you could match those
four pattern at once, sorry I have no code
handy right now,

Karl



From hasan at SLAC.Stanford.EDU  Thu Oct 23 01:52:10 2003
From: hasan at SLAC.Stanford.EDU (Adil Hasan)
Date: Wed Nov  5 12:46:22 2003
Subject: [Tutor] executing multiple binaries from a python script
Message-ID: <Pine.GSO.4.58.0310222236580.24243@flora01.slac.stanford.edu>


 Hello,
       Can someone help me? I am trying to write a little script that will
 execute binaries one after the other. Ideally, I'd like to be able to
 create the shell session in the constructor, execute some commands, and
 then close the session. On the unix command line what I do is:

 shell> commandA  (this creates my session)
 shell>     commandB
 shell>     commandC
 shell>     commandD
 shell> commandE (ends my session)

 I'd like to be able to do this within a python class. I thought I might
 be able to use popen2, but that doesn't work (I get broken pipe errors).
 I was thinking about fork() but I cannot understand how to put this into
 a class like structure (ideally I'd like to get some handle to the fork
 and then pass that to the methods to allow me to run the other commands).

 Does anyone have an idea how to do this?
 thaks, adil


From hall at ouhep1.nhn.ou.edu  Thu Oct 23 15:24:42 2003
From: hall at ouhep1.nhn.ou.edu (Isaac Hall)
Date: Wed Nov  5 12:46:31 2003
Subject: [Tutor] Python, C, Swig, and mismatched API's
Message-ID: <Pine.LNX.4.44.0310231418270.18155-100000@ouhep1.nhn.ou.edu>

Hi folks.
Recently the powers that be decided that we needed to upgrade the version 
of python running here at work.  This had the side effect of causing a 
couple of my programs to print out some error messages I have not seen 
before, most notably one that says:

RuntimeWarning: Python C API version mismatch for module 
l3xmonitor_util_modulec: This Python has API version 1011, module 
l3xmonitor_util_modulec has version 1010.

Now, I didnt write the code that it is complaining about...someone else 
did, but my programs depend heavily on this little module, which from 
looking at the code was written in C++, and used some implementation of 
the swig program.  My question then is: what is causing the problem? Swig? 
the python.h file that gets loaded into the C++ code, or something else 
altogether?

--So Far-- this has not caused any problems, but when people that need to 
run this code fire it up and see any kind of error messages, they always 
shoot me an email, and after the 100th one, Im getting a little annoyed 
with it.

Thanks

Ike Hall

-- 


From grisha at modpython.org  Mon Oct 27 14:45:38 2003
From: grisha at modpython.org (Gregory (Grisha) Trubetskoy)
Date: Wed Nov  5 12:46:40 2003
Subject: [Tutor] Re: [mod_python] invalid literal for float int or long
	solved !
In-Reply-To: <20031027111252.H91970-100000@localhost.name>
References: <20031027111252.H91970-100000@localhost.name>
Message-ID: <20031027144335.Q39378@onyx.ispol.com>


The first one is "url, title", the second is "title, url" - was that the
problem, or was it the WHERE instead of INNER JOIN (which are same thing
IIRC).

Grisha


On Mon, 27 Oct 2003 tpc@csua.berkeley.edu wrote:

>
> fingers crossed, here's hoping the bug doesn't rear its creepy head again,
> can't really say wherefore the bug but I found a workaround, I changed the
> basic MySQL statement below:
>
> SELECT url, title FROM URLs, URLs_WITH_MATCHES WHERE URLs.id =
> URLs_WITH_MATCHES.url_id;
>
> to:
>
> SELECT title, url from URLs INNER JOIN URLs_WITH_MATCHES ON URLs.id =
> URLs_WITH_MATCHES.url_id;
>
> and voila !  I am a complete idiot.
>
> _______________________________________________
> Mod_python mailing list
> Mod_python@modpython.org
> http://mailman.modpython.org/mailman/listinfo/mod_python
>

From karshi.hasanov at utoronto.ca  Mon Oct 27 20:35:48 2003
From: karshi.hasanov at utoronto.ca (Karshi F.Hasanov)
Date: Wed Nov  5 12:46:50 2003
Subject: [Tutor] binary_read?
Message-ID: <3F9DC7F4.9090207@utoronto.ca>

Hi all,

I am trying to read a binary file using python's "read" method.
Here how it starts file:
'@\xe0\x00\x00\x00\x00f\x00\x00326112\x0010/17/103\x0022:20
\x00\x00\x00GE_MED_NMR\x00\x01\x00\x00\x00\x02\x00\x03\x00
\x0b\x00\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x01\x00;\x00
\x02\x00\x01\x01\x00\x00\x08\x00\x00\x01\x00\x00\x02\x00\x01\x00\x01?\x80
\x00\x00?\x80\x00\x00\x00\x01\x00\x01\x00\x00\x01\x00\x01\x01\x01\x00\x01\x00
\x01\x00\x00\x00\x00\x00\x01\xd9\xd8\x00\x00\x00\x00\x00\x00\x00\x00\x00C\x00\x00\x00A 

Steps:
1. f=open("Binary_file", 'rb')
2. r=f.read(512)
3.s=fromstring(r,'f'')    ( also tried different fomating codes)
I am not getting it right!!!
Can you tell me where I am wrong?
Thanks





From SPENCER_LONG at fleet.com  Wed Oct 29 13:02:17 2003
From: SPENCER_LONG at fleet.com (LONG, SPENCER)
Date: Wed Nov  5 12:46:57 2003
Subject: [Tutor] Coin toss program
Message-ID: <B9347A7A668DC84290DC609C86848EF61C3312@usboswmxmp03.ma.fbf1.com>

Hello,

I'm having difficulty writing code for the following end of chapter
exercise:

"Write a program that flips a coin 100 times and then tells you the number
of heads and tails."

Can anyone forward to this Newbie the code for how this is accomplished? So
far I have code that flips the coin once (using a random number generator),
which results in either a heads or tails.  But again, it's a single flip of
the coin.


Thanks,

Spencer

 

From monashee at junction.net  Fri Oct 31 20:45:10 2003
From: monashee at junction.net (J or M Montgomery)
Date: Wed Nov  5 12:47:06 2003
Subject: [Tutor] Re: Re: Python vs. Ruby  [where to find more about Ruby]
In-Reply-To: <200310301909.26166.tbstep@tampabay.rr.com>
References: <Pine.LNX.4.44.0310291615030.20823-100000@hkn.eecs.berkeley.edu>
	<bqhllbrrrar6$.12p7pn8vnxevu$.dlg@40tude.net>
	<200310301909.26166.tbstep@tampabay.rr.com>
Message-ID: <200310311745.10885.monashee@junction.net>

On Thursday October 30 2003 4:09 pm, Todd Stephens wrote:
> On Thursday 30 October 2003 06:17 pm, Andrei wrote:
> >  Probably a browser quirk. I've never had any problems with it,
> > despite using several different browser engines. The author is quite
> > fanatical about standards, cross-browser compatibility and
> > accessibility, so that part should be OK.
>
> I tried with MozillaFirebird and it works fine.  Odd that Konqueror
> (what I originally tried it with) should display it incorrectly in that
> manner.  I had thought that Konq was one of the most
> standards-compliant browsers.

Konqueror works fine on the site for me.

John Montgomery