Re: Py3K idea: why not drop the colon?

2006-11-16 Thread Neil Cerutti
On 2006-11-16, Steve Holden [EMAIL PROTECTED] wrote:
 I'm always surprised by the amount of energy that's put into
 this type of discussion - even the OP has suggested that this
 isn't a big issue. If it's not a big issue why is this thread
 still going? Every language has a syntax. Why not just accept
 it as a given and get on with more productive activities?

That's all very well if the language has a compromised and ad-hoc
syntax. But since Python has a nice clean syntax, it makes me
want to be associated with it by investing in its discussions. ;-)

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: remove a list from a list

2006-11-17 Thread Neil Cerutti
On 2006-11-17, Rares Vernica [EMAIL PROTECTED] wrote:
 Sorry for not being clear from the beginning and for not using
 clear variable names.

 Problem context:

 import os
 dirs_exclude = set(('a', 'b', 'e'))
 for root, dirs, files in os.walk('python/Lib/email'):
  # Task:
  # delete from dirs the directory names from dirs_exclude
  # case-insensitive

 The solution so far is:

 for i in xrange(len(dirs), 0, -1):
if dirs[i-1].lower() in dirs_exclude:
  del dirs[i-1]

 I am looking for a nicer solution.

I'd probably just skip over those dirs as I came them instead of
troubling about mutating the list. Unless the list is needed in
more than one place.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: trouble writing results to files

2006-11-29 Thread Neil Cerutti
On 2006-11-29, Roberto Bonvallet [EMAIL PROTECTED] wrote:
 BTW, iterating over range(len(a)) is an anti-pattern in Python.

Unless you're modifying elements of a, surely?

-- 
Neil Cerutti
You can't give him that cutback lane. He's so fast, and he sees it so well. He
can also run away from you if he gets a little bit of crack. --Dick Lebeau
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to detect what type a variable is?

2006-11-29 Thread Neil Cerutti
On 2006-11-29, Grant Edwards [EMAIL PROTECTED] wrote:
 On 2006-11-29, Leandro Ardissone [EMAIL PROTECTED] wrote:

 I want to know what type is a variable. For example, I get the
 contents of an xml but some content is a list or a string, and
 I need to know what type it is.

 x = 'asdf'
 type(x)
type 'str'
 i = 0
 type(i)
type 'int'

That makes me wonder how he manages to store Python objects in
xml.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: trouble writing results to files

2006-11-29 Thread Neil Cerutti
On 2006-11-29, Roberto Bonvallet [EMAIL PROTECTED] wrote:
 Neil Cerutti wrote:
 On 2006-11-29, Roberto Bonvallet [EMAIL PROTECTED] wrote:
 BTW, iterating over range(len(a)) is an anti-pattern in Python.
 
 Unless you're modifying elements of a, surely?

 enumerate is your friend :)

 for n, item in enumerate(a):
   if f(item):
   a[n] = whatever

I was going to bring it up but I had a brainfart about the order
of (n, item) in the tuple and was too lazy to look it up. ;-)

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Trying to understand rfc822.Message() behaviour

2006-11-30 Thread Neil Cerutti
On 2006-11-30, Phoe6 [EMAIL PROTECTED] wrote:
 Hi all,
 Have  a look at this snippet, I have a file direct.txt and I want to
 read it as rfc8222.Message() so that I get the Subject: and Mood: as
 Dict Keys and content separately, but I am unable to get the Content
 Properly.

 fhandle = open('direct.txt','r')
 print fhandle.read()
 Subject: testing - fortune
 Mood: happy


   Why should we subsidize intellectual curiosity?
   - Ronald Reagan


 fhandle.seek(0)
 import rfc822
 message = rfc822.Message(fhandle)
 print message
 Subject: testing - fortune
 Mood: happy



 What is happening here. Why is the message not coming up?

From the Python Documentation 12.11.1 Message Objects:

  class Message( file[, seekable]) 

A Message instance is instantiated with an input object as
parameter. Message relies only on the input object having a
readline() method; in particular, ordinary file objects
qualify. Instantiation reads headers from the input object up
to a delimiter line (normally a blank line) and stores them
in the instance. The message body, following the headers, is
not consumed. 

-- 
Neil Cerutti
We dispense with accuracy --sign at New York drug store
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Automatic increment

2006-11-30 Thread Neil Cerutti
On 2006-11-30, Thomas Ploch [EMAIL PROTECTED] wrote:
 Gheorghe Postelnicu schrieb:
 Hi,
 
 I have a situation of the following type:
 
 for line in lineList:
 for item in line.split()
 myArray[counter, itemCounter]
 itemCounter = itemCounter + 1
 counter = counter +1
 
 Is there a way to get rid of the manual incrementation of the 2 counters?
 
 Thanks,

 for counter in xrange(len(lineList)):
   for itemCounter in xrange(len(lineList[counter].split()))
   myArray[counter, itemCounter]

I was going to suggest replacing the whole loop with nothing as
the best way of removing the manual counters.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there an easier way to express this list slicing?

2006-11-30 Thread Neil Cerutti
On 2006-11-30, John Henry [EMAIL PROTECTED] wrote:
 If I have a list of say, 10 elements and I need to slice it into
 irregular size list, I would have to create a bunch of temporary
 variables and then regroup them afterwords, like:

 # Just for illustration. Alist can be any existing 10 element list
 a_list=(,)*10
 (a,b,c1,c2,c3,d1,d2,d3,d4,d5)=a_list
 alist=(a,)
 blist=(b,)
 clist=(c1,c2,c3)
 dlist=(d2,d3,d4,d5)

 That obviously work but do I *really* have to do that?

Please post actual code we can run, rather than text that is
almost, but not quite, entirely unlike Python code.

 BTW: I know you can do:
 alist=a_list[0]
 blist=a_list[1]

Note that alist and blist are not necessarily lists, as you did
not use slice notation.

 clist=a_list[2:5]
 dlist=a_list[5:]

 but I don't see that it's any better.

I think it looks much better, personally.

If you are iterating through that sequence of slices a lot,
consider using a generator that yields the sequence.

   def parts(items):
  ...   yield items[0:1]
  ...   yield items[1:2]
  ...   yield items[2:5]
  ...   yield items[5:]
 
   for seq in parts(range(10)):
  ...   print seq
  [0]
  [1]
  [2, 3, 4]
  [5, 6, 7, 8, 9]
 
-- 
Neil Cerutti
I guess there are some operas I can tolerate and Italian isn't one of them.
--Music Lit Essay
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there an easier way to express this list slicing?

2006-11-30 Thread Neil Cerutti
On 2006-11-30, Neil Cerutti [EMAIL PROTECTED] wrote:
 On 2006-11-30, John Henry [EMAIL PROTECTED] wrote:
 If I have a list of say, 10 elements and I need to slice it into
 irregular size list, I would have to create a bunch of temporary
 variables and then regroup them afterwords, like:

 # Just for illustration. Alist can be any existing 10 element list
 a_list=(,)*10
 (a,b,c1,c2,c3,d1,d2,d3,d4,d5)=a_list
 alist=(a,)
 blist=(b,)
 clist=(c1,c2,c3)
 dlist=(d2,d3,d4,d5)

 That obviously work but do I *really* have to do that?

 Please post actual code we can run, rather than text that is
 almost, but not quite, entirely unlike Python code.

Ummm... that comment is withdrawn. :-O

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Detecting recursion loops

2006-12-01 Thread Neil Cerutti
On 2006-12-01, robert [EMAIL PROTECTED] wrote:
 Ben Finney wrote:
 robert [EMAIL PROTECTED] writes:
 
 Carl Banks wrote:
 2. Consider whether you're unwittingly trying to cover up a bug.
 ISTM no matter how problematic the input is, you should at least
 be able to make progress on it.  Are you getting this error
 because, say, you're not incrementing a counter somewhere, and
 thus recalling a function with the same arguments again?
 the bug comes in from the I/O input.
 
 If a program doesn't gracefully deal with bad input, that's a bug in
 the program. You should be designing your input handler so that it
 will do something helpful (even if that's to stop immediately with an
 informative error message) in the event of bad input, rather than
 allowing that bad data to send your program into an endless loop.


 Yet that detection is what the asked alg should do. Example:
 When a HTML-(content)-relaying sends you around in a circle
 through a complex handler chain.

Being in a cycle doesn't actually prove your program will never
halt for that particular input, does it?

-- 
Neil Cerutti
Customers who consider our waitresses uncivil ought to see the manager --sign
at New York restaurant
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: converting dict to object

2006-12-02 Thread Neil Cerutti
On 2006-12-02, Michel Claveau [EMAIL PROTECTED] wrote:
 Hi!

 Yes.

 But...

 Try:d = {'a': 1, 'b': 2, 'def': 123}

 Ok, I go out...

How to convert a list of strings into a list of integers:

 a = ['82', '4', '16']

 ai = [int(i) for i in a]

Yes.

But...

Try:  a = ['82', '4', '16', 'foo']

Ok, I go out...

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: converting dict to object

2006-12-02 Thread Neil Cerutti
On 2006-12-02, John Machin [EMAIL PROTECTED] wrote:
 Neil Cerutti wrote:
 On 2006-12-02, Michel Claveau [EMAIL PROTECTED] wrote:
  Hi!
 
  Yes.
 
  But...
 
  Try:d = {'a': 1, 'b': 2, 'def': 123}
 
  Ok, I go out...

 How to convert a list of strings into a list of integers:

  a = ['82', '4', '16']

  ai = [int(i) for i in a]

 Yes.

 But...

 Try:  a = ['82', '4', '16', 'foo']

 Ok, I go out...

 Michel was making (part of) a valid point: dictionaries have
 more flexibility in choice of keys than objects have in
 attribute names.  More completely:

 Suppose d.keys() produces [one, def, foo bar, 3, 3]

 o.one is OK.

I made the assumption that Michael was also the original poster,
and had somehow laid a clever trap. If I was wrong about that, my
apologies. It's one thing to ask how to convert 'a' and 'b' to
attributes, but quite another to convert arbitrary text.

 The OP might consider adding code to the __init__ method to
 check for cases where the dictionary key is not a string
 containing a valid Python identifier (not a keyword).

That raises the interesting question of what to do in that case.
Just letting an error occur might be perfectly good behavior.
Plus, I didn't know about...

 Observation: the keyword module's iskeyword() function gives an
 easy check. If one is supporting multiple versions of Python, a
 more complicated (overkill?) approach might be desirable: use
 the latest version of Python to generate a source file
 containing the latest keywords from keyword.kwlist.

Thanks for the pointer to keyword module. I hadn't noticed it
yet.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: text adventure question

2006-12-02 Thread Neil Cerutti
On 2006-12-02, Ara Kooser [EMAIL PROTECTED] wrote:
 I am working on a text adventure game for python to get back
 into python programming. My version 0.1 used only functions so
 I could get familiar with how those work. I want to move beyond
 that. I am not sure what would be a good Python way of handling
 this.  I was wondering if classes would help? What things
 should be included in the main program?

The language used by the Infocom implementors was called ZIL, and
it so happens that the ZIL manual is available for download.
It was sort of a wimpy version of Lisp.

   http://www.mv.com/ipusers/xlisper/zil.pdf

Anyway, the ZIL manual explains how Infocom's library for text
adventures worked.  That should be inspirational for your design.
It's also an entertaining historical artifact, if the history of
computer games is your thing. Here's an amusing sampling:

  EXERCISE THREE
  Design and implement a full-size game. Submit it to testing,
  fix all resulting bugs, help marketing design a package, ship
  the game, and sell at lest 250,000 units.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Execution time of lines within a function

2006-12-04 Thread Neil Cerutti
On 2006-12-04, monkeyboy [EMAIL PROTECTED] wrote:
 I have a function that hotshot says is very slow. I can get the
 aggregate execution time, but is there a way to get the
 execution time of each line so I can find the bottleneck?

Try 'print_callees' on the stats object for your bottleneck. That
may help.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Execution time of lines within a function

2006-12-04 Thread Neil Cerutti
On 2006-12-04, monkeyboy [EMAIL PROTECTED] wrote:
 Thanks Neil,

 I looked at that, but maybe I don't understand the output. I
 was hoping to see the cummulative time for the function and
 then the time associated with each statement (line) within the
 function.

 Any suggestions?

I don't think the Python Profiler goes down to that level. The
next step might be to analyze the function yourself and try to
understand why it is so slow. Post the code here and let the
readers pick it apart.

 In the hotshot output below, I can see the function being
 called 100 times, which is correct, but the rest seems at too
 low a level for me to understand which statements are causing
 the slow execution.



 hw6r3.py:276(main)   hw6r3.py:73(findw)(100) 26700.865

Is this the print_callees output?

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Am I stupid or is 'assert' broken in Python 2.5??

2006-12-06 Thread Neil Cerutti
On 2006-12-07, Gabriel Genellina [EMAIL PROTECTED] wrote:
Yeah, it hit me seconds after I had posted my message. =0 Why
didn't I think of it during the 30 minutes I spent banging my
head against the keyboard going nuts over this 'bug' ...

 The same reason you can sometimes find what's wrong just by
 explaining the symptoms to another guy... Having to put things
 sorted and simple to understand by another, just makes you
 think clearly on the problem...

I read a story (was it by Brian Kernighan?) the they required
programmers to tell their problem to a stuffed animal first
before bothering another programmer who might be in the middle of
something. The stuffed animal often provided all the assistance
that was needed.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why not just show the out-of-range index?

2006-12-07 Thread Neil Cerutti
On 2006-12-07, Tim Chase [EMAIL PROTECTED] wrote:
 - because error messages are not debugging tools (better use unit
 
 Then what are they? Machine-generated poetry?

  me.__cmp__(gruntbuggly['freddled'].micturations, 
 bee[LURGID].gabbleblotchits[PLURDLED]) == 0

 Traceback (most recent call last):
File stdin, line 1, in ?
 VogonPoetryException: Bleem miserable venchit! Bleem forever 
 mestinglish asunder frapt!

You should warn people before posting something that dangerous. I
would at least have had time to pull the babelfish out of my ear,
and so I could have avoided the nosebleed.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-08 Thread Neil Cerutti
[Followup-To: header set to comp.lang.python.]
On 2006-12-08, Mark Tarver [EMAIL PROTECTED] wrote:
 I'm looking at Python and I see that the syntax would appeal to
 a newbie.  Its clearer than ML which is a mess syntactically.

And if you stew it like applesauce, it tastes more like prunes
than rhubarb does.

 But I don't see where the action is in Python.   Not yet
 anyway.  Lisp syntax is easy to learn.  And giving up an order
 of magnitude is a high price to pay for using it over Lisp.

I find it easier to learn syntax than special forms. But either
system comes naturally enough with practice.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Snake references just as ok as Monty Python jokes/references in python community? :)

2006-12-08 Thread Neil Cerutti
On 2006-12-08, Roy Smith [EMAIL PROTECTED] wrote:
 In article [EMAIL PROTECTED],
  [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
 I'm semi-seriously wondering if snake jokes are valid in the
 Python community since technically, Python came from Monty
 Python, not slithery animals.
 
 Problem is I don't know that anyone born after Elvis died gets
 any of these Monty Python jokes.
 
 Is it kosher to make snake jokes/references even though
 officially they don't have anything to do with the name of our
 favorite language? (*Everyone* gets snake jokes! :)

 It's people like you wot cause unrest!

I think the decent people of this newsgroup are sick and tired of
being told that the decent people of this newsgroup are sick and
tired. I'm certainly not! And I'm sick and tired of being told
that I am.

-- 
Neil Cerutti
Sermon Outline: I. Delineate your fear II. Disown your fear III. Displace your
rear --Church Bulletin Blooper
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-11 Thread Neil Cerutti
On 2006-12-09, Bill Atkins [EMAIL PROTECTED] wrote:
 I'm afraid you're on the wrong track.  Any programmer can pick
 up Lisp and be productive in it these days.  Please don't try
 to make Lisp seem more mysterious or elitist than it really is.
 It's just a programming language, and anyone can learn it:

   http://www.gigamonkeys.com/book

I got stuck (last year) in that book:

http://www.gigamonkeys.com/book/practical-a-portable-pathname-library.html

The author didn't do Common Lisp (or me) any favors by drawing my
attention to the pathname library. I suppose I missed whatever
the point was supposed to be in the midst of the mind-boggling. I
meant to get back to it but haven't yet.

-- 
Neil Cerutti
We will sell gasoline to anyone in a glass container. --sign at Santa Fe gas
station
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-12 Thread Neil Cerutti
On 2006-12-12, André Thieme [EMAIL PROTECTED] wrote:
 Contrast the much more common
 
   a[i] = b[n]
 
 with
 
   (setf (aref a i) (aref b n))
 
 and the attractions of Python may make more sense.

 Here Python and Lisp are equal, 7 tokens vs 7 tokens, but in
 Python one has to write less since [] are 2 chars while
 aref are 4, plus the setf.  But from counting the brain units
 which I regard as an important factor they are both equal.

A comparison of brain units of the above snippets is irrelevant,
since the snippets are not equivalent.  

The Python snippet will work for any object a that provides
__setitem__ and any object b that provides __getitem__.

I don't know what an equivalent Lisp snippet would be (or even
exactly how close the above snippet comes to matching the Python
code), but whatever it is would be a better foundation for
comparing brain units with the above Python.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-12 Thread Neil Cerutti
On 2006-12-13, hit_the_lights [EMAIL PROTECTED] wrote:
 Neil Cerutti schrieb:

a[i] = b[n]
 
  with
 
(setf (aref a i) (aref b n))
 
  and the attractions of Python may make more sense.
 
  Here Python and Lisp are equal, 7 tokens vs 7 tokens, but in
  Python one has to write less since [] are 2 chars while
  aref are 4, plus the setf.  But from counting the brain
  units which I regard as an important factor they are both
  equal.

 A comparison of brain units of the above snippets is
 irrelevant, since the snippets are not equivalent.

 The Python snippet will work for any object a that provides
 __setitem__ and any object b that provides __getitem__.

 I don't know what an equivalent Lisp snippet would be (or even
 exactly how close the above snippet comes to matching the
 Python code), but whatever it is would be a better foundation
 for comparing brain units with the above Python.

 It would be exactly like the example given, just aref
 replaced with something else. An example implementation:

==
 (defgeneric $ (container key))
 (defgeneric (setf $) (value container key))

 ;;; Implementation for arrays

 (defmethod $ ((container array) (key integer))
   (aref container key))

 (defmethod (setf $) (value (container array) (key integer))
   (setf (aref container key) value))
==

 And usage:

==
 CL-USER(3): (defparameter a (vector 1 2 3 4 5))
 A
 CL-USER(4): ($ a 0)
 1
 CL-USER(5): (setf ($ a 0) 9)
 9
 CL-USER(6): a
 #(9 2 3 4 5)
==

 The nice thing is, that you *can* dispatch on the container,
 the key and the value.

That's cool. Thanks for posting the code.

Is the above 'duck-typing' idiom considered very useful to a
Lisper? It seems logical to me that duck-typing works best in an
environment where it is ubiquitous. If users have to implement
accessors specifically to use your library, it is not as good as
if they had already implemented one as a matter of routine.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-12 Thread Neil Cerutti
On 2006-12-13, [EMAIL PROTECTED]
[EMAIL PROTECTED] wrote:
 Try reading again. In Lisp, you use () and *your editor*
 automatically indents according to the universal standard, or
 you leave it sloppy until other folks reading your code
 convince you to get a proper programming editor. Indentation
 does not get out of sync with semantics because the editor
 virtually never misses parentheses that the Lisp compiler sees.
 Expressions keep the same meaning even if you have to start
 breaking them across lines, etc.

Yes, it's the same way in Python. Of course, not everything is an
expression in Python, so it's not saying quite as much.

 In Python, you group in your mind, and press indentation keys
 to make it happen in your editor. The editor cannot help that
 much, because it cannot read your mind. White space screwups in
 copy-paste cannot be fixed by the editor automatically, because
 it cannot read the original programmer's mind, and you have to
 fix it manually, and risk screwing it up.

It is very easy a manual process, possibly as simple as selecting
the correct s-expr and pasting it into the right place in your
code.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Conditional iteration

2006-12-13 Thread Neil Cerutti
On 2006-12-13, Roberto Bonvallet [EMAIL PROTECTED] wrote:
 at wrote:
 More pythonic in view would be:
 
 for x in [-2, -1, 0, 1, 2, 3, 4] if x  0:
... more code ...

 Pythonic?  Do you realize that Python hasn't even adopted
 well-known statements like 'switch' and 'do while' because they
 would be redundant?

 This could be more convenient to you, but certainly not
 pythonic.  Cheers,

I tried it once myself. It seemed like a feasible thing that
might work in Python. It didn't annoy me that it didn't work, but
it did seem natural to me given the syntax of comprehensions.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-14 Thread Neil Cerutti
On 2006-12-14, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:

 Neil Cerutti wrote:
 On 2006-12-13, [EMAIL PROTECTED]
 [EMAIL PROTECTED] wrote:
  Expressions keep the same meaning even if you have to start
  breaking them across lines, etc.

 Yes, it's the same way in Python. Of course, not everything is
 an expression in Python, so it's not saying quite as much.

 I fail to see how it is the same in Python.

if self.flee == (foo.humble(pie) / 500 * hats
+ hippity.hoppity)

The indentation of the second line of that expression is entirely
irrelevant to Python. The parenthesis I added means I don't have
to use the new-line escape character (\), either.

  In Python, you group in your mind, and press indentation
  keys to make it happen in your editor. The editor cannot
  help that much, because it cannot read your mind. White
  space screwups in copy-paste cannot be fixed by the editor
  automatically, because it cannot read the original
  programmer's mind, and you have to fix it manually, and risk
  screwing it up.

 It is very easy a manual process, possibly as simple as
 selecting the correct s-expr and pasting it into the right
 place in your code.

 How does a manual correction process come out as simple as
 don't bother fixing the indentation if you don't care.?

 This is exactly the questionable math that I was questioning in
 the original post.

Python simply replaces one manual process (moving to the correct
scope (usually sitting on an open or close parenthesis) and then
hitting the grab-s-expr command) with another (after pasting,
correct the indentation--generally a trivial task). I think it's
a major stretch to call either process anything but trivially
easy for an experiences user of the language.

-- 
Neil Cerutti
The Pastor would appreciate it if the ladies of the congregation would lend
him their electric girdles for the pancake breakfast next Sunday morning.
--Church Bulletin Blooper
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-14 Thread Neil Cerutti
On 2006-12-14, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:

 Neil Cerutti wrote:
 On 2006-12-14, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
 
  Neil Cerutti wrote:
  On 2006-12-13, [EMAIL PROTECTED]
  [EMAIL PROTECTED] wrote:
   Expressions keep the same meaning even if you have to start
   breaking them across lines, etc.
 
  Yes, it's the same way in Python. Of course, not everything
  is an expression in Python, so it's not saying quite as
  much.
 
  I fail to see how it is the same in Python.

 if self.flee == (foo.humble(pie) / 500 * hats
 + hippity.hoppity)

 The indentation of the second line of that expression is entirely
 irrelevant to Python. The parenthesis I added means I don't have
 to use the new-line escape character (\), either.

 Is this so unconscious that you don't recognize you are doing
 it, even though you take a sentence to explain what you had to
 do to work around it? Adding parentheses, new-line escape
 characters---all this is a burden specific to Python.

It already indicated that you are right about Python identation
*outside* of an expression, which is where most indentation takes
place in Python. But you were wrong that it is meaningful inside
an expression.

 The reformatting (admittedly generally trivial, although again
 your qualifier of generally undermines your point) process is
 extra in Python. Period.

 1) Recognizing where your code begins and ends to begin the
 copy-paste process is not unique to either. Equal.

Reflecting on what you've written, I see you are right about this
issue. Thanks for the correction.

 5) After you are done, Pythonistas admit there is a possible
 step called manually correct the indentation.

Meaningful indentation has drawbacks *and* advantages, though.

 This is pointless discussion if you guys can't even see what
 you are saying when you write it in your own posts.

Please don't assume I speak for all Python programmers. They
might be rolling there eyes at me just as much as you are. ;-)

-- 
Neil Cerutti
In my prime I could have handled Michael Jordan.  Of course, he would be only
12 years old. --Jerry Sloan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Routine for prefixing '' before every line of a string

2006-12-14 Thread Neil Cerutti
On 2006-12-14, Roberto Bonvallet [EMAIL PROTECTED] wrote:
 Sanjay wrote:
 Is somewhere a routine useful to convert a string to lines of
 maxsize, each prefixed with a ''. This is a typical
 requirement for 'keeping existing text while replying to a
 post in a forum'.

 Take a look to the textwrap module:
 http://docs.python.org/lib/module-textwrap.html

 Here is an example:

 # the text is actually a very long line
 text = '''Lorem ipsum dolor sit amet, consectetuer adipiscing [...]'''
 prefix = ''

 import textwrap
 lines = [%s %s % (prefix, line) for line in textwrap.wrap(text, 
 width=75)]

The solution will need to be instrumented in case of text that is
already quotes to one level. All in all, I recommend using Vim's
gq command or Emacs' autofill mode, which arlready do the right
thing.

-- 
Neil Cerutti
The Rev. Merriwether spoke briefly, much to the delight of the audience.
--Church Bulletin Blooper
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tuple.index()

2006-12-14 Thread Neil Cerutti
On 2006-12-14, Nick Maclaren [EMAIL PROTECTED] wrote:

 In article [EMAIL PROTECTED],
 Glenn Hutchings [EMAIL PROTECTED] writes:
|
|  I remain baffled.  I accept the explanations, but what I am now
|  confused by is the reason for the explanations 
| 
| Maybe this archive posting, straight from the horse's mouth, will clear
| things up once and for all...
| 
| http://www.python.org/search/hypermail/python-1992/0285.html

 Wonderful!  Thanks.  Yes, that does.  It makes perfect sense.
 I did say that I thought it would be a rarely used feature :-)

Though the full rationale no longer applies to strings, which now
have plenty of methods.

-- 
Neil Cerutti
Weight Watchers will meet at 7 p.m. Please use large double door at the side
entrance. --Church Bulletin Blooper
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: WHAT is [0] in subprocess.Popen(blah).communicate()[0]

2006-12-14 Thread Neil Cerutti
On 2006-12-14, Fredrik Lundh [EMAIL PROTECTED] wrote:
 johnny wrote:

 Can someone tell me what is the reason [0] appears after
 .communicate()
 
 For example:
 last_line=subprocess.Popen([rtail,-n 1, x.txt],
 stdout=subprocess.PIPE).communicate()[0]

 as explained in the documentation, communication() returns two
 values, as a tuple.  [0] is used to pick only the first one.

 see the Python tutorial for more on indexing and slicing.

I like using pattern matching in these simple cases:

  last_line, _ = subprocess.Popen([rtail,-n 1, x.txt],
  stdout=subprocess.PIPE).communicate()

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-15 Thread Neil Cerutti
On 2006-12-15, André Thieme
[EMAIL PROTECTED] wrote:
 In Lisp it is like an IF and represents exactly what we think.
 IF in Lisp:
 (if expr
  (then-part)
  (else-part))

 nif in Lisp:
 (nif expr
   (positive-part)
   (zero-part)
   (negative-part))

 It looks as if it were a construct directly built into Lisp. If
 one wants one could even add some additional syntax, so that it
 looks like:
 (nif expr
   positive:
 (foo1)
 (foo2)
   zero:
 (foo3)
   negative:
 (foo4))

 If you regard that idea nonsense then I suggest you to not use
 Rubys if-statement anymore. But instead program your own
 version RubyIF so that in future you have to pass all code
 inside blocks to your RubyIF function. If you *really* think
 that the Lisp savings are not worth it, then you would begin
 with my suggestion today.

I don't know how to build a house. It doesn't make me want to
live in a cave. ;-)

-- 
Neil Cerutti
The third verse of Blessed Assurance will be sung without musical
accomplishment. --Church Bulletin Blooper
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: array, a better shell

2006-12-20 Thread Neil Cerutti
On 2006-12-20, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
 For array.array B means unsigned char, and such arrays accept to be
 initialized from (str) strings too, this is quite useful:

 from array import array
 a = array(B, hello)

 But it seems such capability isn't shared with the append:

 a.extend(hello)
 Traceback (most recent call last):
   File stdin, line 1, in module
 TypeError: an integer is required

Try:

 a.fromstring(hello)

-- 
Neil Cerutti
I have opinions of my own -- strong opinions -- but I don't always agree with
them. --George W. Bush
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: DOS, UNIX and tabs

2007-01-02 Thread Neil Cerutti
On 2007-01-02, Peter Decker [EMAIL PROTECTED] wrote:
 On 1/1/07, Tom Plunket [EMAIL PROTECTED] wrote:
 Maybe I'm also weird, but I use a variable-pitch font when
 programming in Python.  So a tab equals some number of
 spaces really isn't useful to me.  My setup is, tab equals
 this much space.

 A year ago I would have thought you were weird, but after
 reading a post by Ed Leafe, one of the creators of Dabo about
 using proportional fonts for readability, I thought I'd try it
 out, thinking that it was pretty wacky. Turns out that after a
 very brief adjustment period, I liked it! I've been using
 proportional fonts ever since, and have found only one
 drawback: code that is indented with spaces looks butt-ugly.
 I'm glad I switched to tabs for my code.

I first came accross it in Stroustrup's _The C++ Programming
Language_. I liked the look and the idea immediately, but my
editor of choice (by historical accident) Vim, doesn't yet
support it.

-- 
Neil Cerutti
I've had a wonderful evening, but this wasn't it. --Groucho Marx
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: array of class / code optimization

2007-01-03 Thread Neil Cerutti
On 2007-01-03, Jussi Salmela [EMAIL PROTECTED] wrote:
 hg kirjoitti:
 mm wrote:
 
 Yes, it was the (), equivalent to thiks like new() create new object
 from class xy.
   s1.append(Word)
 s1.append(Word())

 But I was looking for a struct equivalent like in c/c++.
 And/or union. I can't find it.

 Maybe you know a source (URL) Python for c/c++ programmers or things
 like that.


 Yes, I konw whats an object is...
 
 
 A struct in C is unrelated to a struct in C++ as a struct in C++ _is_ a
 class.
 
 
 hg

 What does your sentence mean, exactly? If I take a C file xyz.c
 containing a struct definition S, say, rename it to be xyz.cpp
 and feed it to a C++ compiler, the S sure remains a struct and
 the C++ compiler has no difficulty in handling it as a struct,
 so ?!?

That's true.

But it's also true that

struct foo {
  int x, y;
};

is exactly equivalent to:

class foo {
  public:
int x, y;
};

The only difference between struct and class in C++ is the
default access specification of its members.

-- 
Neil Cerutti
For those of you who have children and don't know it, we have a nursery
downstairs. --Church Bulletin Blooper
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sorting on multiple values, some ascending, some descending

2007-01-04 Thread Neil Cerutti
On 2007-01-03, dwelden [EMAIL PROTECTED] wrote:
 I have successfully used the sort lambda construct described in
 http://mail.python.org/pipermail/python-list/2006-April/377443.html.
 However, how do I take it one step further such that some
 values can be sorted ascending and others descending? Easy
 enough if the sort values are numeric (just negate the value),
 but what about text?

 Is the only option to define an external sorting function to
 loop through the list and perform the comparisons one value at
 a time?

Another trick is to factor the key application out of the sort.
This may be a good idea if when you want to minimize the number
of times your key function is called.

The idea is to mangle the list temporarily so you can use an
unkeyed sort, and then unmangle the sorted data. Here's a silly
example using a phone directory that's not stored in a format
that's easy to sort.

 a = [(Neil Cerutti, 8025552954), (Ted Smith, 8025552281), (Barny 
 Fife, 8025551105)]
 b = [( .join(reversed(x.split())), y) for (x, y) in a]
 b
[('Cerutti Neil', '8025552954'), ('Smith Ted', '8025552281'), ('Fife Barny', 
'8025551105')]
 b.sort()
 b
[('Cerutti Neil', '8025552954'), ('Fife Barny', '8025551105'), ('Smith Ted', 
'8025552281')]
 a = [( .join(reversed(x.split())), y) for (x, y) in b]
 a
[('Neil Cerutti', '8025552954'), ('Barny Fife', '8025551105'), ('Ted Smith', 
'8025552281')]

-- 
Neil Cerutti
Eddie Robinson is about one word: winning and losing. --Eddie Robinson's agent
Paul Collier
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sorting on multiple values, some ascending, some descending

2007-01-04 Thread Neil Cerutti
On 2007-01-04, Peter Otten [EMAIL PROTECTED] wrote:
 Neil Cerutti wrote:
 Another trick is to factor the key application out of the
 sort. This may be a good idea if when you want to minimize the
 number of times your key function is called.
 
 The idea is to mangle the list temporarily so you can use an
 unkeyed sort, and then unmangle the sorted data. Here's a
 silly example using a phone directory that's not stored in a
 format that's easy to sort.

 No need to jump through these hoops; list.sort(key=keyfunc)
 calls keyfunc() exactly once per list item:

 from random import shuffle
 items = range(-5, 10)
 shuffle(items)
 count = 0
 def key(value):
 ... global count
 ... count += 1
 ... return abs(value)
 ...
 items.sort(key=key)
 count
 15

Thanks for the correction! That's very useful information.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why less emphasis on private data?

2007-01-08 Thread Neil Cerutti
On 2007-01-08, Paul Rubin http wrote:
 Dennis Lee Bieber [EMAIL PROTECTED] writes:
 I'd be quite concerned about the design environment rather than the
 immediate code... Probably need something ugly like...
 
 from mod1 import B as B1
 from mod2 import B as B2
 class A(B1, B2):
  

 Interesting.  I just tried that.  mod1.py contains:

 class B:
 def foo(self): self.__x = 'mod1'

 mod2.py contains:

 class B:
 def bar(self): self.__x = 'mod2'

 And the test is:

 from mod1 import B as B1
 from mod2 import B as B2

 class A(B1, B2): pass

 a = A()
 a.foo()
 print a._B__x
 a.bar()
 print a._B__x

 Sure enough, mod2 messes up mod1's private variable.

When faced with this situation, is there any way to proceed
besides using composition instead?

-- 
Neil Cerutti
We've got to pause and ask ourselves: How much clean air do we really need?
--Lee Iacocca
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: recursive function

2007-01-08 Thread Neil Cerutti
On 2007-01-08, cesco [EMAIL PROTECTED] wrote:
 Hi,

 I have a dictionary of lists of tuples like in the following example:
 dict = {1: [(3, 4), (5, 8)],
 2: [(5, 4), (21, 3), (19, 2)],
 3: [(16, 1), (0, 2), (1, 2), (3, 4)]]

 In this case I have three lists inside the dict but this number
 is known only at runtime. I have to write a function that
 considers all the possible combinations of tuples belonging to
 the different lists and return a list of tuples of tuples for
 which the sum of the first element of the most inner tuple is
 equal to N.

 For example, assuming N = 24, in this case it should return:
 [((3, 4), (5, 4), (16, 1)), ((3, 4), (21, 3), (0, 2)), ((5, 8), (19,
 2), (0, 2))]

What do you mean by most inner tuple?

 A simple list comprehension would be enough if only I knew the
 number of keys/lists beforehand

len(dict.keys()).

-- 
Neil Cerutti
Next Sunday Mrs. Vinson will be soloist for the morning service. The pastor
will then speak on It's a Terrible Experience. --Church Bulletin Blooper
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why less emphasis on private data?

2007-01-08 Thread Neil Cerutti
On 2007-01-08, hg [EMAIL PROTECTED] wrote:
 sturlamolden wrote:

 The designers of Java, C++, C#, Ada95, Delphi, etc. seem to think that
 if an object's 'internal' variables or states cannot be kept private,
 programmers get an irresistible temptation to mess with them in
 malicious ways. But if you are that stupid, should you be programming
 in any language? The most widely used language is still C, and there is
 no concept of private data in C either, nor is it needed.


 void test(void)
 {
   static int i;
 }


 Do you agree that i is private to test ?

In C one uses the pointer to opaque struct idiom to hide data.
For example, the standard FILE pointer.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why less emphasis on private data?

2007-01-08 Thread Neil Cerutti
On 2007-01-08, Jussi Salmela [EMAIL PROTECTED] wrote:
 Neil Cerutti kirjoitti:
 In C one uses the pointer to opaque struct idiom to hide data.
 For example, the standard FILE pointer.

 To Neil Cerutti: If a programmer in C has got a pointer to some
 piece of memory, that piece is at the mercy of the programmer.
 There's no data hiding at all in this case.

That's somewhat disingenuous. You get just as much data hiding
with an opaque data type in C as you get in C++ or Java.

-- 
Neil Cerutti
Potluck supper: prayer and medication to follow. --Church Bulletin Blooper
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Colons, indentation and reformatting.

2007-01-09 Thread Neil Cerutti
On 2007-01-09, Leif K-Brooks [EMAIL PROTECTED] wrote:
 Paddy wrote:
 Thinking about it a little, it seems that a colon followed by
 non-indented code that has just been pasted in could also be
 used by a Python-aware editor as a flag to re-indent the
 pasted code.

 How would it reindent this code?

 if foo:
 print Foo!
 if bar:
 print Bar!

 Like this?

 if foo:
  print Foo!
 if bar:
  print Bar!

 Or like this?

 if foo:
  print Foo!
  if bar:
  print Bar!

That's the key issue. The colon gives the editor an easy clue
where a block starts, but the there's no simply way to determine
where the block is supposed to end.

-- 
Neil Cerutti
Remember in prayer the many who are sick of our church and community. --Church
Bulletin Blooper
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Determine an object is a subclass of another

2007-01-09 Thread Neil Cerutti
On 2007-01-09, abcd [EMAIL PROTECTED] wrote:
 How can tell if an object is a subclass of something else?

 Imagine...

 class Thing:
 pass

 class Animal:
 pass

 class Dog:
 pass

 d = Dog()

 I want to find out that 'd' is a Dog, Animal and Thing.  Such
 as...

 d is a Dog
 d is a Animal
 d is a Thing

isinstance(d, Dog)
isinstance(d, Animal)
isinstance(d, Thing)

Note that in your example d is not an instance of anything but
Dog. If you want a hierarchy, you must say so. Python doesn't
even try to make educated guesses.

class Thing:
  pass

class Animal(Thing):
  pass

class Dog(Animal):
  pass

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


A simple lexer

2007-01-09 Thread Neil Cerutti
I'm a royal n00b to writing translators, but you have to start
someplace.

In my Python project, I've decided that writing the dispatch code
to sit between the Glulx virtual machine and the Glk API will be
best done automatically, using the handy prototypes.

Below is the prototype of the lexer, and I'd like some comments
in case I'm doing something silly already.

My particular concern are: 

The loop checks for each possible lexeme one at a time, and has
rather lame error checking.

I made regexes for matching a couple of really trivial cases for
the sake of consistency. In general, is there a better way to use
re module for lexing.

Ultimately, I'm going to need to build up an AST from the lines,
and use that to generate Python code to dispatch Glk functions. I
realize I'm throwing away the id of the lexeme right now;
suggestions on the best way to store that information are
welcome.

I do know of and have experimented with PyParsing, but for now I
want to use the standard modules. After I understand what I'm
doing, I think a PyParsing solution will be easy to write.

import re

def match(regex, proto, ix, lexed_line):
m = regex.match(proto, ix)
if m:
lexed_line.append(m.group())
ix = m.end()
return ix

def parse(proto):
 Return a lexed version of the prototype string. See the
Glk specification, 0.7.0, section 11.1.4

 parse('0:')
['0', ':']
 parse('1:Cu')
['1', ':', 'Cu']
 parse('2Qb:Cn')
['2', '', 'Qb', ':', 'Cn']
 parse('4Iu#![2SF]+Iu:Is')
['4', 'Iu', '#!', '[', '2', 'S', 'F', ']', '+', 'Iu', ':', 'Is']

arg_count = re.compile('\d+')
qualifier = re.compile('[][+#!]*')
type_name = re.compile('I[us]|C[nus]|[SUF]|Q[a-z]')
o_bracket = re.compile('\\[')
c_bracket = re.compile('\\]')
colon = re.compile(':')
ix = 0
lexed_line = []
m = lambda regex, ix: match(regex, proto, ix, lexed_line)
while ix  len(proto):
old = ix
ix = m(arg_count, ix)
ix = m(qualifier, ix)
ix = m(type_name, ix)
ix = m(o_bracket, ix)
ix = m(c_bracket, ix)
ix = m(colon, ix)
if ix == old:
print Parse error at %s of %s % (proto[ix:], proto)
ix = len(proto)
return lexed_line

if __name__ == __main__:
import doctest
doctest.testmod()

-- 
Neil Cerutti
We dispense with accuracy --sign at New York drug store
-- 
http://mail.python.org/mailman/listinfo/python-list


An iterator with look-ahead

2007-01-10 Thread Neil Cerutti
For use in a hand-coded parser I wrote the following simple
iterator with look-ahead. I haven't thought too deeply about what
peek ought to return when the iterator is exhausted. Suggestions
are respectfully requested. As it is, you can't be sure what a
peek() = None signifies until the next iteration unless you
don't expect None in your sequence.

Using itertools.tee is the alternative I thought about, but
caveates in the documentation disuaded me.

class LookAheadIter(object):
 An iterator with the a peek() method, so you can see what's coming next.

If there is no look-ahead, peek() returns None.

 nums = [1, 2, 3, 4, 5]
 look = LookAheadIter(nums)
 for a in look:
...print (a, look.peek())
(1, 2)
(2, 3)
(3, 4)
(4, 5)
(5, None)

def __init__(self, data):
self.iter = iter(data)
self.look = self.iter.next()
self.exhausted = False
def __iter__(self):
return self
def peek(self):
if self.exhausted:
return None
else:
return self.look
def next(self):
item = self.look
try:
self.look = self.iter.next()
except StopIteration:
if self.exhausted:
raise
else:
self.exhausted = True
return item

-- 
Neil Cerutti
We've got to pause and ask ourselves: How much clean air do we really need?
--Lee Iacocca
-- 
http://mail.python.org/mailman/listinfo/python-list


Working with named groups in re module

2007-01-10 Thread Neil Cerutti
A found some clues on lexing using the re module in Python in an
article by Martin L÷wis.

http://www.python.org/community/sigs/retired/parser-sig/towards-standard/

He writes:
  [...]
  A scanner based on regular expressions is usually implemented
  as an alternative of all token definitions. For XPath, a
  fragment of this expressions looks like this:


  (?PNumber\\d+(\\.\\d*)?|\\.\\d+)|
  (?PVariableReference\\$ + QName + )|
  (?PNCName+NCName+)|
  (?PQName+QName+)|
  (?PLPAREN\\()|

  Here, each alternative in the regular expression defines a
  named group. Scanning proceeds in the following steps:

 1. Given the complete input, match the regular expression
 with the beginning of the input.
 2. Find out which alternative matched.
 [...]

Item 2 is where I get stuck. There doesn't seem to be an obvious
way to do it, which I understand is a bad thing in Python.
Whatever source code went with the article originally is not
linked from the above page, so I don't know what Martin did.

Here's what I came up with (with a trivial example regex):

  import re
  r = re.compile('(?Pxx+)|(?Paa+)')
  m = r.match('aaxaxx')
  if m:
for k in r.groupindex:
  if m.group(k):
# Find the token type.
token = (k, m.group())

I wish I could do something obvious instead, like m.name().

-- 
Neil Cerutti
After finding no qualified candidates for the position of principal, the
school board is pleased to announce the appointment of David Steele to the
post. --Philip Streifer
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: An iterator with look-ahead

2007-01-10 Thread Neil Cerutti
On 2007-01-10, Fredrik Lundh [EMAIL PROTECTED] wrote:
 if you're doing simple parsing on an iterable, it's easier and
 more efficient to pass around the current token and the
 iterator's next method:

 http://online.effbot.org/2005_11_01_archive.htm#simple-parser-1

Thank you. Much better.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Working with named groups in re module

2007-01-10 Thread Neil Cerutti
On 2007-01-10, Fredrik Lundh [EMAIL PROTECTED] wrote:
 Neil Cerutti wrote:
 A found some clues on lexing using the re module in Python in
 an article by Martin L÷wis.

   Here, each alternative in the regular expression defines a
   named group. Scanning proceeds in the following steps:

  1. Given the complete input, match the regular expression
  with the beginning of the input.
  2. Find out which alternative matched.

 you can use lastgroup, or lastindex:

 http://effbot.org/zone/xml-scanner.htm

 there's also a hidden ready-made scanner class inside the SRE
 module that works pretty well for simple cases; see:

 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/457664

Thanks for the excellent pointers.

I got tripped up:

 m = re.match('(a+(b*)a+)', 'aaa')
 dir(m)
['__copy__', '__deepcopy__', 'end', 'expand', 'group', 'groupdict', 'groups', 
'span', 'start']

There are some notable omissions there. That's not much of an
excuse for my not understanding the handy docs, but I guess it
can can function as a warning against relying on the interactive
help.

I'd seen the lastgroup definition in the documentation, but I
realize it was exactly what I needed. I didn't think carefully
enough about what last matched capturing group actually meant,
given my regex. I don't think I saw name there either. ;-)

  lastgroup 
  
  The name of the last matched capturing group, or None if the
  group didn't have a name, or if no group was matched at all. 

-- 
Neil Cerutti
We dispense with accuracy --sign at New York drug store
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need startup suggestions for writing a MSA viewer GUI in python

2007-01-10 Thread Neil Cerutti
On 2007-01-10, hg [EMAIL PROTECTED] wrote:
 Joel Hedlund wrote:
 Thanks for taking the time!
 /Joel Hedlund

 I do not know if PyGtk and PyQT have demos, but wxPython does
 and includes PyPlot: an easy way to look at the basic features.

PyQT does come with an impressive plethora of demos.

-- 
Neil Cerutti
The concert held in Fellowship Hall was a great success. Special thanks are
due to the minister's daughter, who labored the whole evening at the piano,
which as usual fell upon her. --Church Bulletin Blooper
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: An iterator with look-ahead

2007-01-10 Thread Neil Cerutti
On 2007-01-10, Steven Bethard [EMAIL PROTECTED] wrote:
 Neil Cerutti wrote:
 For use in a hand-coded parser I wrote the following simple
 iterator with look-ahead.

 There's a recipe for this:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/304373

 Note that the recipe efficiently supports an arbitrary
 look-ahead, not just a single item.

 I haven't thought too deeply about what peek ought to return
 when the iterator is exhausted. Suggestions are respectfully
 requested.

 In the recipe, StopIteration is still raised on a peek()
 operation that tries to look past the end of the iterator.

That was all I could think of as an alternative, but that makes
it fairly inconvenient to use. I guess another idea might be to
allow user to provide a no peek return value in the
constructor, if they so wish.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Print message with Colors

2007-01-11 Thread Neil Cerutti
On 2007-01-11, Laurent Pointal [EMAIL PROTECTED] wrote:
 prk a écrit :
 Hi Folks,
 
 Is there any procesure for print messages with colors.

 Yes, see:

 http://www.google.fr/search?q=python+print+color
 http://groups.google.fr/groups?as_q=python+print+colornum=100as_ugroup=comp.lang.python

 See also ANSI escape sequences for the more general subject of
 color printing on terminals.

If you're using Windows NT, 2000, or XP don't bother reading
about ANSI escape sequences. They will not work at all with
Python on those platforms, even if you use the crummy old
COMMAND.COM. I believe it's because Python on those platforms in
a console application, which on NT, 2000 and XP doesn't support
ANSI escape sequences. It makes IPython's appearance less cool. :-(

Try http://effbot.org/downloads/#console for color output that
works.

-- 
Neil Cerutti
We're going to be exciting.  Of course, it was exciting when the Titanic went
down. --Bob Weiss
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Type casting a base class to a derived one?

2007-01-11 Thread Neil Cerutti
On 2007-01-11, Frederic Rentsch [EMAIL PROTECTED] wrote:
 If I derive a class from another one because I need a few extra
 features, is there a way to promote the base class to the
 derived one without having to make copies of all attributes?

 class Derived (Base):
def __init__ (self, base_object):
   # ( copy all attributes )
   ...

 This looks expensive. Moreover __init__ () may not be available
 if it needs to to something else.

 Thanks for suggestions

How does it make sense to cast a base to a derived in your
application?

-- 
Neil Cerutti
I'm traveling to all 51 states to see who can stop 85. --Chad Johnson
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __init__ vs __new__

2007-01-11 Thread Neil Cerutti
On 2007-01-11, Daniel Klein [EMAIL PROTECTED] wrote:
 I've have a program that is using both of the methods below (in
 different classes of course) for initializing the class. The
 example below shows a class with the 2 methods with one
 commented out.

 class JsubroutineParameters(list):
 Represents a list of arguments for external subroutine calls.
 # We only need to override methods which add objects to the list.

 def __init__(self, alist = []):
 for objekt in alist: _validateParameter(objekt)
 self.extend(alist)

 #def __new__(cls, alist = []):
 #for objekt in alist: _validateParameter(objekt)
 #return list.__new__(cls, alist)

 I don't really notice any behavioral difference. Is there in
 fact any difference in using one over the other? Performance?
 Side effects? ???

 I am using Python version 2.5.

The second version doesn't work the way you might be assuming.

Guido's paper says that mutable builtins like list have a dummy
__new__ static method. So 'return list.__new__(cls, alist)' does
nothing. It seems to work because the base class __init__
performs the initialization (assuming your __init__ above is
commented out). You can see this by providing a dummy __init__.

class Example(list):
  def __new__(cls, alist):
return list.__new__(cls, alist)
  def __init__(self, alist):
pass

 a = Example(range(5))
 a
[]

There is no need to use __new__ for mutable builtin types. Since
all you want from this construction is a side-effect, you can
nevertheless use it in this case.

Your __init__ should call the base-class __init__.

It's usually a bad idea to provide mutable types as default
arguments. Since you aren't modifying alist in __init__ you can
get away with it here, but getting in the habit of using the
below idiom might save you from a gotcha someday.

class JsubroutineParameters(list):
  def __init__(self, alist=None):
if alist is None:
  alist = []
for objekt in alist: _validateParameter(objekt)
list.__init__(self, alist)

You will no longer need to call append.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What happened to SPE?

2007-01-11 Thread Neil Cerutti
On 2007-01-11, Paulo Pinto [EMAIL PROTECTED] wrote:
 does anyone know what happened to SPE?

 It seems that the address http://pythonide.stani.be
 is no longer valid. :(

SPE lost its web host, and last I heard is looking for a new
home. For now you can get it here: 

  http://sourceforge.net/projects/spe/

-- 
Neil Cerutti
We don't necessarily discriminate.  We simply exclude certain types of people.
--Colonel Gerald Wellman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fixed keys() mapping

2007-01-11 Thread Neil Cerutti
On 2007-01-11, George Sakkis [EMAIL PROTECTED] wrote:
 I wrote an 'fkdict' dict-like class for mappings with a fixed
 set of keys but I'm wondering if there's a simpler way to go
 about it.

 First off, the main motivation for it is to save memory in case
 of many dicts with the same keys, for example when reading from
 a csv.DictReader or constructing dicts out of rows fetched from
 a database. For example, test_mem(dict) takes up around 246 MB
 according to the Windows task manager while test_mem(fkdict)
 takes around 49 MB:

It occurs to me you could create custom classes using __slots__
to get something similar. It's not terribly convenient.

class XYDict(object):
  __slots__ = ['x', 'y']
  def __getitem__(self, item):
return self.__getattribute__(item)
  def __setitem__(self, key, item):
return self.__setattr__(key, item)

This isn't terribly convenient because you have to create a new
class for every new set of keys. It isn't obvious to me how to
program a metaclass to automate the process. A lot more
boilerplate is necessary to act like a dict.

 def test_mem(maptype):
 d = [(i,str(i)) for i in range(1000)]
 ds = [maptype(d) for i in xrange(1)]
 raw_input('finished')

 An additional benefit is predictable ordering (e.g.
 fkdict.fromkeys('abcd').keys() == list('abcd')), like several
 ordered-dict recipes.

 The implementation I came up with goes like this: each fkdict
 instance stores only the values as a list in self._values. The
 keys and the mapping of keys to indices are stored in a
 dynamically generated subclass of fkdict, so that self._keys
 and self._key2index are also accessible from the instance. The
 dynamically generated subclasses are cached so that the second
 time an fkdict with the same keys is created, the cached class
 is called.

 Since the keys are determined in fkdict.__init__(), this scheme
 requires changing self.__class__ to the dynamically generated
 subclass. As much as I appreciate Python's dynamic nature, I am
 not particularly comfortable with objects that change their
 class and the implications this may have in the future (e.g.
 how well does this play with inheritance). Is this a valid use
 case for type-changing behavior or is there a better, more
 mainstream OO design pattern for this ? I can post the
 relevant code if necessary.

Since the type gets changed before __init__ finishes, I don't see
any problem with it. It sounds cool.

-- 
Neil Cerutti
It isn't pollution that is hurting the environment; it's the impurities in our
air and water that are doing it. --Dan Quayle
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: passing a variable to an external program

2007-01-11 Thread Neil Cerutti
On 2007-01-11, Rich [EMAIL PROTECTED] wrote:
 I want to run an external program using os.system() but I want to
 include a variable in the middle of the command line.

 An example of the type of thing I want to be able to do:
 pathname = os.path.dirname(sys.argv[0])
 os.system('cscript /nologo ' + pathname + '\test.vbs')

Use / instead of \, or \\ instead of \.

-- 
Neil Cerutti
Ushers will eat latecomers. --Church Bulletin Blooper
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Matching Directory Names and Grouping Them

2007-01-12 Thread Neil Cerutti
On 2007-01-11, J [EMAIL PROTECTED] wrote:
 Steve-

 Thanks for the reply. I think what I'm trying to say by similar
 is pattern matching. Essentially, walking through a directory
 tree starting at a specified root folder, and returning a list
 of all folders that matches a pattern, in this case, a folder
 name containing a four digit number representing year and a
 subdirectory name containing a two digit number representing a
 month. The matches are grouped together and written into a text
 file. I hope this helps.

Here's a solution using itertools.groupby, just because this is
the first programming problem I've seen that seemed to call for
it. Hooray!

from itertools import groupby

def print_by_date(dirs):
r Group a directory list according to date codes.

 data = [
... root/Input2/2002/03/,
... root/Input1/2001/01/,
... root/Input3/2005/05/,
... root/Input3/2001/01/,
... root/Input1/2002/03/,
... root/Input3/2005/12/,
... root/Input2/2001/01/,
... root/Input3/2002/03/,
... root/Input2/2005/05/,
... root/Input1/2005/12/]
 print_by_date(data)
root/Input1/2001/01/
root/Input2/2001/01/
root/Input3/2001/01/
BLANKLINE
root/Input1/2002/03/
root/Input2/2002/03/
root/Input3/2002/03/
BLANKLINE
root/Input2/2005/05/
root/Input3/2005/05/
BLANKLINE
root/Input1/2005/12/
root/Input3/2005/12/
BLANKLINE


def date_key(path):
return path[-7:]
groups = [list(g) for _,g in groupby(sorted(dirs, key=date_key), date_key)]
for g in groups:
print '\n'.join(path for path in sorted(g))
print

if __name__ == __main__:
import doctest
doctest.testmod()

I really wanted nested join calls for the output, to suppress
that trailing blank line, but I kept getting confused and
couldn't sort it out.

It would better to use the os.path module, but I couldn't find
the function in there lets me pull out path tails.

I didn't filter out stuff that didn't match the date path
convention you used.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Boilerplate in rich comparison methods

2007-01-13 Thread Neil Cerutti
On 2007-01-13, Steven D'Aprano [EMAIL PROTECTED] wrote:
 On Sat, 13 Jan 2007 10:04:17 -0600, Paul McGuire wrote:
 [snip]

 Surely this is only worth doing if the comparison is expensive?
 Testing beats intuition, so let's find out...

 class Compare:
 def __init__(self, x):
 self.x = x
 def __eq__(self, other):
 return self.x == other.x

 class CompareWithIdentity:
 def __init__(self, x):
 self.x = x
 def __eq__(self, other):
 return self is other or self.x == other.x

 Here's the timing results without the identity test:

 import timeit
 x = Compare(1); y = Compare(1)
 timeit.Timer(x = x, from __main__ import x,y).repeat()
 [0.20771503448486328, 0.16396403312683105, 0.16507196426391602]
 timeit.Timer(x = y, from __main__ import x,y).repeat()
 [0.20918107032775879, 0.16187810897827148, 0.16351795196533203]

 And with the identity test:

 x = CompareWithIdentity(1); y = CompareWithIdentity(1)
 timeit.Timer(x = x, from __main__ import x,y).repeat()
 [0.20761799812316895, 0.16907095909118652, 0.16420602798461914]
 timeit.Timer(x = y, from __main__ import x,y).repeat()
 [0.2090909481048584, 0.1968839168548584, 0.16479206085205078]

 Anyone want to argue that this is a worthwhile optimization? :)

Perhaps. But first test it with ==.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Anyone has a nice view_var procedure ?

2007-01-16 Thread Neil Cerutti
On 2007-01-15, Gabriel Genellina [EMAIL PROTECTED] wrote:
 At Monday 15/1/2007 17:45, Stef Mientki wrote:

Is there some handy/ nice manner to view the properties of some variable ?
As a newbie, I often want to see want all the properties of a var,
and also some corner values (large arrays) etc.

 You can try dir(x), vars(x). If you want a nice print, see
 the pprint module.

 py import csv
 py x = csv.DictReader('') # a bogus object
 py x
csv.DictReader instance at 0x00BC79B8
 py dir(x)
 ['__doc__', '__init__', '__iter__', '__module__', 'fieldnames', 
 'next', 'reader'
 , 'restkey', 'restval']
 py vars(x)
 {'restkey': None, 'restval': None, 'fieldnames': None, 'reader': 
_csv.reader ob
 ject at 0x00BC98B8}
 py from pprint import pprint
 py pprint(vars(x))
 {'fieldnames': None,
   'reader': _csv.reader object at 0x00BC98B8,
   'restkey': None,
   'restval': None}
 py

It's an unfortunately limited sort of introspection. To rehash a
recent experience:

 import re
 import pprint
 r = re.match((x+)|(y+), xxx)
 pprint.pprint(dir(r))
['__copy__',
 '__deepcopy__',
 'end',
 'expand',
 'group',
 'groupdict',
 'groups',
 'span',
 'start']
 r.lastindex
1

The documentation is deliberately vague:

dir( [object]) 
  
  [...] The list is not necessarily
  complete. If the object is a module object, the list contains
  the names of the module's attributes. If the object is a type
  or class object, the list contains the names of its attributes,
  and recursively of the attributes of its bases. Otherwise, the
  list contains the object's attributes' names, the names of its
  class's attributes, and recursively of the attributes of its
  class's base classes. The resulting list is sorted
  alphabetically. [...]

It's unclear to me what attributes an object could have that
aren't included in the above list.

  Note: Because dir() is supplied primarily as a convenience for
  use at an interactive prompt, it tries to supply an interesting
  set of names more than it tries to supply a rigorously or
  consistently defined set of names, and its detailed behavior
  may change across releases. 

In other words, dir is just for fun, like monkey bars. ;)

-- 
Neil Cerutti
The eighth-graders will be presenting Shakespeare's Hamlet in the church
basement on Friday at 7 p.m. The congregation is invited to attend this
tragedy. --Church Bulletin Blooper
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: whats wrong with my reg expression ?

2007-01-16 Thread Neil Cerutti
On 2007-01-15, Gert Cuykens [EMAIL PROTECTED] wrote:
 thx

 PS i also cant figure out what is wrong here ?

 rex=re.compile('^(?Pvalue[^]*)$',re.M)
 for v in l:
 v=rex.match(v).group('value')
 v=v.replace('','')
 return(l)

 v=rex.match(v).group('value')
 AttributeError: 'NoneType' object has no attribute 'group'

When the regex doesn't match, match returns None.

-- 
Neil Cerutti
Strangely, in slow motion replay, the ball seemed to hang in the air for even
longer. --David Acfield
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: assert versus print [was Re: The curious behavior of integer objects]

2007-01-16 Thread Neil Cerutti
On 2007-01-16, Ron Adam [EMAIL PROTECTED] wrote:
 I have to admit that part of why assert seems wrong to me is
 the meaning of the word implies something you shouldn't be able
 to ignore.  While warnings seem like something that can be
 disregarded.

Experienced C coders expect assert to behave like that.

The only reason (I know of) to turn off error checking is to
optimize. However, removing tests won't usually make a big enough
speed difference to be worth the burthen of testing two different
versions of the same source code.

So to me the assert statement is either dubious syntax-sugar or
dangerous, depending on Python's command line arguments.

The warning module would seem to have limited applications.
Searching my Python distribution shows that it's used for
deprecation alerts, and elsewhere for turning those selfsame
alerts off. How copacetic! It is the null module. ;-)

-- 
Neil Cerutti
Facts are stupid things. --Ronald Reagan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regular expressions question

2007-01-16 Thread Neil Cerutti
On 2007-01-16, Victor Polukcht [EMAIL PROTECTED] wrote:
 Actually, i'm trying to get the values of first field (Global) , fourth
 (200, 4), and fifth (100%) and sixth (100%).

 Everything except fourth is simple.

 g = Global etsi3  *   4 ok 30 100% 100% Outgoing
 import re
 r = re.search('\*\s+(\d+)', g)
 r.group()
'*   4'
 r.group(1)
'4'

-- 
Neil Cerutti
We're not afraid of challenges. It's like we always say: If you want to go out
in the rain, be prepared to get burned. --Brazillian soccer player
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regular expressions question

2007-01-16 Thread Neil Cerutti
On 2007-01-16, Victor Polukcht [EMAIL PROTECTED] wrote:
 On Jan 16, 5:40 pm, Neil Cerutti [EMAIL PROTECTED] wrote:
 On 2007-01-16, Victor Polukcht [EMAIL PROTECTED] wrote:

  Actually, i'm trying to get the values of first field (Global) , fourth
  (200, 4), and fifth (100%) and sixth (100%).

  Everything except fourth is simple.
  g = Global etsi3  *   4 ok 30 100% 100% Outgoing
  import re
  r = re.search('\*\s+(\d+)', g)
  r.group()
 '*   4'
  r.group(1)'4'

 The same regular expression should work for another string (with *200).

Sorry about that. It should have been:

r = re.search('\*\s*(\d+)', g)

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A note on heapq module

2007-01-17 Thread Neil Cerutti
On 2007-01-16, [EMAIL PROTECTED]
[EMAIL PROTECTED] wrote:
 Scott David Daniels:
 I'd suggest some changes.  It is nice to have Heaps with equal
 contents equal no matter what order the inserts have been
 done. Consider how you want Heap([1, 2, 3]) and Heap([3, 1,
 2]) to behave. Similarly, it is nice to have str and repr
 produce canonical representations (I would skip the __str__
 code, myself, though). Also, subclasses should get their
 identities tweaked as so:

 My version was a *raw* one, just an idea, this is a bit better:
 http://rafb.net/p/nLPPjo35.html
 I like your changes. In the beginning I didn't want to put
 __eq__ __ne__ methods at all, because they are too much slow,
 but being them O(n ln n) I think your solution is acceptable.

 Some methods may have a name different from the heap functions:
 def smallest(self):
 def push(self, item):
 def pop(self):
 def replace(self, item):

 Two things left I can see: I think the __init__ may have a
 boolean inplace parameter to avoid copying the given list, so
 this class is about as fast as the original heapify function
 (but maybe such thing is too much dirty for a Python stdlib):

One more idea, cribbed from the linked list thread elsewhere: it
might be nice if your Heap could optionally use an underlying
collections.deque instead of a list.

I don't know how excellent Python's deque is, but it's possible a
deque would provide a faster heap than a contiguous array. C++'s
std::deque is the default implementation of C++'s
std::priority_queue for that reason (unless I'm confused again).

-- 
Neil Cerutti
We will sell gasoline to anyone in a glass container. --sign at Santa Fe gas
station
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: generate tuples from sequence

2007-01-17 Thread Neil Cerutti
On 2007-01-17, Will McGugan [EMAIL PROTECTED] wrote:
 Hi,

 I'd like a generator that takes a sequence and yields tuples containing
 n items of the sqeuence, but ignoring the 'odd' items. For example

 take_group(range(9), 3) - (0,1,2) (3,4,5) (6,7,8)

 This is what I came up with..

 def take_group(gen, count):
 i=iter(gen)
 while True:
 yield tuple([i.next() for _ in xrange(count)])

 Is this the most efficient solution?

This is starting to seem like an FAQ. ;)

The Python library contains a recipe for this in the itertools
recipes in the documentation (5.16.3).

def grouper(n, iterable, padvalue=None):
grouper(3, 'abcdefg', 'x') -- ('a','b','c'), ('d','e','f'), ('g','x','x')
return izip(*[chain(iterable, repeat(padvalue, n-1))]*n)

It's more general and cryptic than what you asked for, though.

-- 
Neil Cerutti
We're not afraid of challenges. It's like we always say: If you want to go out
in the rain, be prepared to get burned. --Brazillian soccer player
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A note on heapq module

2007-01-18 Thread Neil Cerutti
On 2007-01-18, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
 Neil Cerutti:
 One more idea, cribbed from the linked list thread elsewhere:
 it might be nice if your Heap could optionally use an
 underlying collections.deque instead of a list. I don't know
 how excellent Python's deque is, but it's possible a deque
 would provide a faster heap than a contiguous array. C++'s
 std::deque is the default implementation of C++'s
 std::priority_queue for that reason (unless I'm confused
 again).

 If you have some minutes you can do few speed tests and show us
 the code and the timing results...

I'll see what I can come up with. I'll have to test using the
native Python implementation, which should work with deque,
rather than the optimized C implementation, which doesn't. 

Unfortunately the inability to take advantage of the C
implementation of heapq might swamp any possible advantage of
using deque instead of list in a Heap class.

-- 
Neil Cerutti

-- 
Posted via a free Usenet account from http://www.teranews.com

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: One more regular expressions question

2007-01-18 Thread Neil Cerutti
On 2007-01-18, Victor Polukcht [EMAIL PROTECTED] wrote:
 My pattern now is:

 (?Pvar1[^(]+)(?Pvar2\d+)\)\s+(?Pvar3\d+)

 And i expect to get:

 var1 = Unassigned Number 
 var2 = 1
 var3 = 32

 I'm sure my regexp is incorrect, but can't understand where
 exactly.

Break it up using verbose notation to help yourself. Also, use
more helpful names. With names like var1 and var2 you might as
well not used named groups.

r = re.compile(r(?x)
(?Perror [^(]+ )
(?Perrno \d+ )
\)
\s+
(?Plineno \d+ ))

This way it's clearer that there's a \) with no matching \(.

-- 
Neil Cerutti
This team is one execution away from being a very good basketball team. --Doc
Rivers

-- 
Posted via a free Usenet account from http://www.teranews.com

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A note on heapq module

2007-01-18 Thread Neil Cerutti
On 2007-01-18, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
 Neil Cerutti:
 One more idea, cribbed from the linked list thread elsewhere:
 it might be nice if your Heap could optionally use an
 underlying collections.deque instead of a list. I don't know
 how excellent Python's deque is, but it's possible a deque
 would provide a faster heap than a contiguous array. C++'s
 std::deque is the default implementation of C++'s
 std::priority_queue for that reason (unless I'm confused
 again).

 If you have some minutes you can do few speed tests and show us
 the code and the timing results...

collections.deque is the loser.

Here's the output of the program from my last run:

list: 5.81679827554
deque: 6.40347742423
C heapq: 2.24028186815

Here's the program. You can customize it somewhat to attempt to
model a real program. It builds up a heap of random integers to
some size, performs random pushes and pops for a while, and then
pops the heap down until it's empty.

import random
import timeit

OPCOUNT = 5000
HEAP_SIZE = 100

# Create a random sequence of pushes and pops.
pushes = 0
ops = []
for i in xrange(OPCOUNT):
x = random.randint(0, 1)
if x == 0 or pushes  HEAP_SIZE:
pushes += 1
ops.append(0)
else: 
pushes -= 1
ops.append(1)
# Pop off the rest
for i in xrange(pushes):
ops.append(1)

def test(mod, cont):
for op in ops:
if op:
mod.heappop(cont)
else:
mod.heappush(cont, random.randint(0, 150))

# heapqd is the pure Python heapq module without the C implementation.
t1 = timeit.Timer(test(heapqd, list()),
from __main__ import test; import heapqd)
t2 = timeit.Timer(test(heapqd, deque()), 
from __main__ import test; \
from collections import deque; \
import heapqd)
t3 = timeit.Timer(test(heapq, list()),
from __main__ import test; import heapq)
print list:, t1.timeit(100)
print deque:, t2.timeit(100)
print C heapq:, t3.timeit(100)

-- 
Neil Cerutti
The Pastor would appreciate it if the ladies of the congregation would lend
him their electric girdles for the pancake breakfast next Sunday morning.
--Church Bulletin Blooper

-- 
Posted via a free Usenet account from http://www.teranews.com

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Traversing the properties of a Class

2007-01-18 Thread Neil Cerutti
On 2007-01-18, EdG [EMAIL PROTECTED] wrote:
 For debugging purposes, I would like to traverse the class
 listing out all the properties.

This is the first thing that came to mind.

def show_properties(cls):
  for attr in dir(cls):
if isinstance(getattr(cls, attr), property):
  print attr

-- 
Neil Cerutti

-- 
Posted via a free Usenet account from http://www.teranews.com

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How can I create a linked list in Python?

2007-01-18 Thread Neil Cerutti
On 2007-01-18, sturlamolden [EMAIL PROTECTED] wrote:

 Paul Rubin wrote:

 But that's what Lisp does too.

 Ok, I may have to reread Paul Graham's book on ANSI Common Lisp
 then.

Here's something silly I whipped up to play with.

r Lisp style singly-linked lists called llist. 



def consp(o):
return isinstance(o, Cons)

def car(c):
 Return the car of a lisp-list. Undefined for nil. 
if null(c):
raise AttributeError(nil has no cdr)
return c.car

def cdr(c):
 Return the cdr of a lisp=list. 
if null(c):
return nil
return c.cdr

def cons(o, c):
 Build a new cons cell from an object and a Cons. 
return Cons(o, c)

def null(c):
return c is nil

def rplaca(c, o):
c.car = o
return c

def rplacd(c, o):
c.cdr = o
return c

def llist(li):
 Build a llist from a list. 
c = nil
for a in reversed(li):
if isinstance(a, list):
c = cons(llist(a), c)
else:
c = cons(a, c)
return c

class Cons(object):
def __init__(self, car, cdr):
self.car = car
self.cdr = cdr
def __repr__(self):
def helper(li, s):
if null(li):
return s + )
else:
return helper(cdr(li), s +  %s % repr(car(li)))
return helper(self.cdr, ( + repr(self.car))

class Nil(Cons):
def __init__(self):
Cons.__init__(self, None, None)
def __repr__(self):
return '()'

nil = Nil()

print cons(5, nil)
print cons(5, cons(3, nil))
print cons(cons(5, (cons(7, nil))), cons(cons(5, cons(3, nil)), nil))
print nil
print llist([1, ['a', 'b', 'c'], 2, 3])

There's lots more more stuff to add, but the fun wore out. I'd
like if it the cdr of nil could actually be nil, instead of None
with a special case in cdr, but I couldn't figure out a neat way
to do it.

-- 
Neil Cerutti
I've had a wonderful evening, but this wasn't it. --Groucho Marx

-- 
Posted via a free Usenet account from http://www.teranews.com

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OT Annoying Habits (Was: when format strings attack)

2007-01-20 Thread Neil Cerutti
On 2007-01-20, Nick Maclaren [EMAIL PROTECTED] wrote:

 In article [EMAIL PROTECTED],
 Carroll, Barry [EMAIL PROTECTED] writes:
| 
| My thanks to Aahz and the others who responded.  I also did some
| Googling on my own.  I found out that top-posting is the norm in the
| e-mail world.  Bottom- and inline-posting are the norm in the newsgroup
| world. =20

 Sorry, even that is not so.  I have been using Email since the 1960s,
 and top-posting has been used only by the inconsiderate.

...or the beleaguered. Since my school's IT switched to Exchange,
correct email composition is really annoying.

The only way to do it is to manually cut into a real editor, and
then past back in the entire message. This is not worth the
hassle for interoffice communication, since everyone else is
stuck with stupid top-posting, too.

It's been an interesting journey, from some unix-based terminal
email, to Lotus Notes (ARRGH!), then a happy time using IMAP, and
now back to (ARRGH!).

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Are there sprintf in Python???

2007-01-23 Thread Neil Cerutti
On 2007-01-22, questions? [EMAIL PROTECTED] wrote:
 Are there any sprintf in Python?
 I know you can print to files(or redefine sys.stout) and later open the
 file content.

 Are there similar function to sprintf in C?

No, but you can compose a similar function very easily.

def sprintf(format, *objects):
  return format % tuple(objects)

Since strings are immutable it's not convenient to provide a
pass-out parameter as in C. If you want to check for errors
you'll have to catch the exceptions, rather than inspect the
return value as you can in C.

-- 
Neil Cerutti
Symphonies of the Romantic era were a lot longer in length. --Music Lit Essay

-- 
Posted via a free Usenet account from http://www.teranews.com

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to document Python code...

2007-01-23 Thread Neil Cerutti
On 2007-01-22, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
 Boris Ozegovic:
 Does Python has API just like in Java, for example
 http://java.sun.com/j2se/1.5.0/docs/api/allclasses-noframe.html ctrl-f and
 than click on class you are searching for, and finally you get clean list
 of all fields and methods.  Where can I find similar in Python, for
 example, if I would like to see which methods list/dictionary has.

 You can do that from the shell, with help(name) or dir(name),
 where name can be a class, object, most things.

It is OK for a lark, but sadly dir is not suitable enough. You do
need to refer to the documentation off-line or you'll miss vital
entries. It won't hurt to read effbot.org, either, as I keep
finding out.

Also check out the interactive help system. If you've got the
html versions of the docs installed, it functions somewhat like
perldoc. Type help() at the interactive prompt to get started.

-- 
Neil Cerutti
Will the last person to leave please see that the perpetual light is
extinguished --sign at New England church

-- 
Posted via a free Usenet account from http://www.teranews.com

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: match nested parenthesis

2007-01-23 Thread Neil Cerutti
On 2007-01-23, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
 hi
 i wish to find an reg exp for matching nested parenthesis of
 varying level like
 string =

It is not possible, because the set of strings containing
balanced parenthesis is not regular. Python re's aren't *really*
regular expressions, so you might be able to hack something up
using extensions (I'm not sure if it's been proven that you
can'). I believe regexes are the wrong tool for the job.

 somewords1(words(somewords2)-(some(some)words3)somestuff)somestuff
 and be able to evaluate the pair starting from the inner
 most(the deepest level) , ie (some) up till the outer most.
 What is a good reg exp to do this? or is simple string
 manipulations enough? 

Write a context free grammar and a recognizer for that grammar,
instead. Python developers haven't been able to agree on any such
module to include in the standard distribution yet,
unfortunately. But fortunately (consequently), there are tons of
nice parser and scanner generators available on the net. Try
pyparsing for a start, as it's a recent, maintained package with
excellent support on this group at the moment.

Or just compose your own little function by hand. A stack-based
solution (implemented using a list as a stack) should be easy enough.

-- 
Neil Cerutti
And now the sequence of events in no particular order. --Dan Rather

-- 
Posted via a free Usenet account from http://www.teranews.com

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Thoughts on using isinstance

2007-01-24 Thread Neil Cerutti
On 2007-01-24, abcd [EMAIL PROTECTED] wrote:
 In my code I am debating whether or not to validate the types of data
 being passed to my functions.  For example

 def sayHello(self, name):
 if not name:
 rasie name can't be null
 if not isinstance(name, str):
 raise name must be a string
 print Hello  + name

 Is the use of isinstance a bad way of doing things?  is it a
 heavy operation?  for example, if I use this in each function
 validate input will it slow things down a lot?

 just curious how you might handle this type of situation (other
 than not validating at all).

Validation of parameters is an excellent idea, but *not*
validation of datatypes. The problem is that sayHello can
function properly with many more objects than just strings, if
you write it differently. The following version accepts any
iterable over strings.

def sayHello(self, name):
  it = iter(name)
  print Hello, ''.join(it)

It still lacks validation. But to validate a name you will need
to conceive a set of regular strings that contains every name
you'd like to accept. Names probably aren't worth validating,
although you might reasonably reject a few things, like the empty
string.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Re-thinking my if-thens - a software engineering question

2007-01-24 Thread Neil Cerutti
On 2007-01-24, metaperl [EMAIL PROTECTED] wrote:
 if dict_key == 'PCN':
   fields = dict_val.split(/)
 mo = re.match( '(\w{2})(\d{2})(\d{2})' , fields[1] )
   if mo:
   dict_val = %s/%s%s/%s % (fields[0], mo.group(1), 
 mo.group(3),
 fields[2][1:])
   else:
   dict_val = dict_val

 Ok, so now here is what has happened. This code was based on
 the assumption that dict_val would have 2 forward slashes in
 it. It turns out that I need to follow a different process of
 massaging when no slashes are present. A naive solution would
 be something like:

 if dict_key == 'PCN':
 fields = dict_val.split(/)
 if fields == 3:
 dict_val = pcn_three(fields) # where pcn_three
 is the code above
 else:
 # new logic

 But I am wondering if I should abstract the flow of control
 into a class or something.

This is what I do in Python when a new requirement pops up:

 1. Write the simplest/first thing that comes to mind to fix it.
 1. a) Am I done? Probably. But maybe not.
 2. Now I examine what I've written to see the lay of the code.
Only after writing something new once do I usually have
enough information to write it better. In other words,
writing the code organizes my thoughts. I usually have to
fully understand something, even to get a kludgey solution to
work. The Kludgey solution informs the design of something
better.
 2. a) Got to 1. a)

In the case above, I've tried to figure out what you're
specifically doing, and failed. So I don't have more specific
advice.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Static variables

2007-01-24 Thread Neil Cerutti
On 2007-01-24, Florian Lindner [EMAIL PROTECTED] wrote:
 does python have static variables? I mean function-local
 variables that keep their state between invocations of the
 function.

Yup.  Here's a nice way. I don't how recent your Python must be
to support this, though.

 def foo(x):
...   print foo.static_n, x
...   foo.static_n += 1
...
 foo.static_n = 0
 for i in range(5):
...   foo(?)
...
0 ?
1 ?
2 ?
3 ?
4 ?

If you need to use an earlier version, then a boxed value
stored as a keyword parameter will also work.

 def foo(x, s=[0]):
...   print s[0], x
...   s[0] += 1
...
 for i in range(5):
...   foo(!)
...
0 !
1 !
2 !
3 !
4 !

The latter is not as nice, since your static variable is easy
to clobber by passing something into the function.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Please have a look at this class

2007-01-25 Thread Neil Cerutti
On 2007-01-25, antred [EMAIL PROTECTED] wrote:
 While working on a program I encountered a situation where I'd
 construct a largish data structure (a tree) from parsing a host
 of files and would end up having to throw away parts of my
 newly built tree if a file turned out to contain invalid data.

The first idea that occurs to me is to provide a merge function
for your data structure, which you use to merge in another tree
object when that data is known to be valid.

So the process would work like this:

 temp_tree = process(the_file)
 if temp_tree.is_valid():
   real_tree.merge(temp_tree)

CODE SNIPPET

 u = Unrollable()
 u.someValue = 3.14
 u.aString = 'Hi there'

 # If we decide we want to keep those changes ...
 u.commit()

 # Or we could have reverted to the original. This would have restored
 the state prior to the last call to commit() (or simply the
 state at the beginning, if there hasn't been a call to commit
 yet).
 #u.rollback()

/CODE SNIPPET

 The basic idea behind this is that each instance of the
 Unrollable class keeps an internal dictionary (which, in lieu
 of a better name I'm currently calling 'sand box') to which all
 changed attribute values are saved (attribute changes are
 intercepted via __setattr__). Then, with a call to commit(),
 all attributes are transferred to the instance's __dict__
 dictionary and hence become actual attributes per se.

A nice use for this class might be to pass large mutable objects
to a functions as if it were immutable without needing to copy
them. Unfortunately it only works for one level of call. I think.

-- 
Neil Cerutti

-- 
Posted via a free Usenet account from http://www.teranews.com

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python+ncurses: I can't display accents

2007-01-26 Thread Neil Cerutti
On 2007-01-26, Fabrice DELENTE [EMAIL PROTECTED] wrote:
 I'm trying to display french characters (è -- that's e grave --
 or à -- agrave) in python 2.5, with the ncurses wrapper that
 comes it, and I can't. My locale is set correctly
 (fr_FR.iso885915), and my terminal (rxvt-unicode) is able to
 display those chars.

What have you tried?

-- 
Neil Cerutti

-- 
Posted via a free Usenet account from http://www.teranews.com

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python+ncurses: I can't display accents

2007-01-26 Thread Neil Cerutti
On 2007-01-26, Fabrice DELENTE [EMAIL PROTECTED] wrote:
 What have you tried?

 I've tried

 stdscr.addstr(0,0,aéïoù)

 or

 stdscr.addstr(0,0,leçon)

 The ASCII chars show correctly, but the accented characters
 don't, so I see 'ao' or 'leon' on the screen.

 The term in which I display is 8-bit-able, so the problem is
 either on ncurses side, or on python side.

What happens when you try this?

stdscr.addstr(0,0, uleçon.encode('iso8859-15'))

I don't really expect it to work, but if anything will, that is
it. Curses supports only ASCII and a some special symbol codes
defined by curses.

 I have

 #!/usr/local/bin/python
 #coding: iso8859-15

Be sure to write your non-ASCII strings as unicode literals, and
then encode them just before displaying or storing them
somewhere.

-- 
Neil Cerutti

-- 
Posted via a free Usenet account from http://www.teranews.com

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert String to list of chars

2007-01-26 Thread Neil Cerutti
On 2007-01-27, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
 How can I convert a string to a char list?
 for example

 hello -- ['h','e','l','l','o']

 I have been searching but I can't find my answers

list(hello)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python+ncurses: I can't display accents

2007-01-26 Thread Neil Cerutti
On 2007-01-27, Thomas Dickey [EMAIL PROTECTED] wrote:
 Neil Cerutti [EMAIL PROTECTED] wrote:
 I don't really expect it to work, but if anything will, that
 is it. Curses supports only ASCII and a some special symbol
 codes defined by curses.

 un - no.  Curses supports whatever the flavor of curses you
 have does. Often that's the 8-bit flavor of ncurses, but the
 limitation is definitely in the python configuration.

Thanks for the clarification. I was going by the some Python
documentation, but I did notice contradictory information in
other discussion. The 8-bit ncurses is supposed to support
iso-8859-1 through iso-8859-15, i.e., all the byle encodings. I
don't know why Python's bindings don't work.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help me understand this

2007-01-30 Thread Neil Cerutti
On 2007-01-30, Gabriel Genellina [EMAIL PROTECTED] wrote:
 En Tue, 30 Jan 2007 06:34:01 -0300, Beej [EMAIL PROTECTED] escribió:

 But here's one I still don't get:

 type(2)
 type 'int'
 type((2))
 type 'int'
 (2).__add__(1)
 3
 2.__add__(1)
   File stdin, line 1
 2.__add__(1)
 ^
 SyntaxError: invalid syntax

 It appears to be a bug, either in the grammar implementation, or in the  
 grammar documentation.
 These are the relevant rules:

 attributeref ::= primary . identifier

 primary ::= atom | attributeref | subscription | slicing | call

 atom ::= identifier | literal | enclosure

 literal ::= stringliteral | integer | longinteger | floatnumber |  
 imagnumber

 An integer is a primary so 2.__add(1) should be valid.

Not if the tokenizer passes the parser a float.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: division by 7 efficiently ???

2007-02-02 Thread Neil Cerutti
On 2007-02-01, Michael Yanowitz [EMAIL PROTECTED] wrote:
   I think it is off by 1 in small numbers, off by a little more with large
 numbers:
 def div7 (N):
 ...return (N3) + ((N-7*(N3))3)
 ...
 div7 (70)
 9
 div7 (77)
 10
 div7 (700)
 98
 div7 (7)
 0
 div7 (10)
 1
 div7 (14)
 1
 div7 (21)
 2
 div7 (700)
 98
 div7 (7000)
 984


Heh, heh. That's reminding of the fabulous O(n) Dropsort
algorithm I saw linked from Effbot's blog.

-- 
Neil Cerutti
I'm tired of hearing about money, money, money, money, money. I just want to
play the game, drink Pepsi, wear Reebok. --Shaquille O'Neal
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I print out in the standard output coloured lines

2007-02-02 Thread Neil Cerutti
On 2007-02-02, rzed [EMAIL PROTECTED] wrote:
 [EMAIL PROTECTED] wrote in
 news:[EMAIL PROTECTED]: 

 On Feb 2, 1:16 pm, rzed [EMAIL PROTECTED] wrote:
 [EMAIL PROTECTED] wrote
 innews:[EMAIL PROTECTED]: 

  Hi,

I'm interested in printing out coloured lines of my
application and
  I don't know what to use. Can anybody give me an idea??

 You could speed up the process if you explain what your
 application is and what you mean by colored lines. Does your
 application emit output to a plotter, an ink-jet printer, or a
 color laser printer? Is it a drawing program? An editor in
 which you want lines colored to highlight context? It might be
 useful to know what system you are running as well. Just a
 little detail here. 

 --
 rzed
 
 Well, yes, it's a program that prints out lines to the standard
 output with a print command, and I want to print them coloured.
 For example: 
 
 print Hello World!!
 
 I want it in red colour.
 
 That's all.

 If you're on Linux, you could use the curses module. There may
 be a precompiled Windows version compatible with your Python
 version, or maybe not, but the Windows source is available, and
 you may be able to get it to work with your Python with some
 effort. Linux distros include curses, I think. For Windows
 curses, take a look at http://adamv.com/dev/python/curses/.
 You will understand why the phrase Windows curses is used, I
 expect. 

On Windows, there's pdcurses for DOS or ncurses for the Cygwin
platform, but I don't know how to get either to work with Python.

Far simpler to get working in Windows is Fredrik Lundh's Console.

  http://www.effbot.org/downloads/#console

If you're using Windowd 98 or earlier there are versions of a
Python readline library that provide cursor addressing and color
using the ANSI excape sequences.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: need help on a data structure problem

2007-02-02 Thread Neil Cerutti
On 2007-02-02, Ben Finney [EMAIL PROTECTED] wrote:
 Dongsheng Ruan [EMAIL PROTECTED] writes:

 Not quite related with Python. But my Data Structure course is
 experiemented on python and there is no data structure group, So I
 have to post here:

 Better, you should discuss it in your class, with your teacher.

Also: comp.algorithms is the usual Usenet place for discussion of
algorithms and data structures.

However most of the talk there is pretty high-falutin'.

-- 
Neil Cerutti
It isn't pollution that is hurting the environment; it's the impurities in our
air and water that are doing it. --Dan Quayle
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Overloading the tilde operator?

2007-02-02 Thread Neil Cerutti
On 2007-02-02, Ben Finney [EMAIL PROTECTED] wrote:
 James Stroud [EMAIL PROTECTED] writes:
 Ben Finney wrote:
  The Python runtime parser is designed to parse Python, not
  some arbitrary language that someone chooses to implement in
  Python.

 You haven't addressed why the limitation isn't arbitrary.

 Good thing I wasn't trying to do that, then. I was pointing out
 the source of the limitation.

 The Python syntax parser must follow the rules of the Python
 language. If you accept that premise, it follows that the '~'
 operator is unary only. If you *don't* accept that premise, I
 have no help to offer.

There's been only one (or two?) languages in history that
attempted to provide programmers with the ability to implement
new infix operators, including defining precedence level and
associativity (I can't think of the name right now).

C++, for example, works the same way as Python here. You can
override most of the operators, but you cannot change their
arity, associativity, or precedence level.

-- 
Neil Cerutti
Let us join David and Lisa in the celebration of their wedding and bring their
happiness to a conclusion. --Church Bulletin Blooper
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie/ merging lists of lists with items in common

2007-02-02 Thread Neil Cerutti
On 2007-02-02, ardief [EMAIL PROTECTED] wrote:
 Hi everyone
 Here is my problem:
 I have a list that looks like this -
 [['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c', '15'], ['c',
 '4'], ['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'], ['e', '7']]

 and I would like to end up with something like this, i.e. with
 the only one list per letter:

 [['a', ['13' '3']], ['b', '6'], ['c', ['12', '15', '4']], ['d', '2'],
 ['e', ['11', '5', '16', '7']]]

 I have the feeling it's trivial, and I've scoured the group
 archives - sets might be a possibility, but I'm not sure how to
 operate on a list of lists with sets.

This is a job for... duhn-duhn-DH! Captain CHAOS!

Er... I mean itertools.groupby.

I took the liberty of not assuming the alist was sorted already.
This could be a one-liner if you wanted to be evil.

def bundle_alist(seq):
 Bundle together some alist tails. 

 seq = [['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c', '15'], 
['c', '4'], ['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'], ['e', '7']]
 bundle_alist(seq)
[['a', ['13', '3']], ['b', ['6']], ['c', ['12', '15', '4']], ['d', ['2']], 
['e', ['11', '5', '16', '7']]]


from itertools import groupby
def key_func(t):
return t[0]
groups = groupby(sorted(seq, key=key_func), key_func)
seq = []
for item in groups:
seq.append([item[0], [a[1] for a in item[1]]])
return seq


-- 
Neil Cerutti
Music gets more chromatic and heavy towards the end of the century. One of the
popular questions of the day was, Why? --Music Lit Essay
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie/ merging lists of lists with items in common

2007-02-02 Thread Neil Cerutti
On 2007-02-02, Laurent Pointal [EMAIL PROTECTED] wrote:
 Neil Cerutti a écrit :
 On 2007-02-02, ardief [EMAIL PROTECTED] wrote:
zip

 This is a job for... duhn-duhn-DH! Captain CHAOS!
 
 Er... I mean itertools.groupby.
 
zip
 def key_func(t):
 return t[0]

 Not needed: -- from operator import itemgetter

I agree. But I used it anyway, to make it easier to see that the
sort and the groupby must be and are using the same key function.

In this case I admit it's a not a huge readability win, but I was
also following the Do Not Repeat Yourself Rule, which makes the
key function easier to refactor.

 See in the example:
 http://docs.python.org/lib/itertools-example.html

 So much stuff in libraries, so few we know. Thanks to doc
 writers, Usenet contributors  Google search engines.

Yup.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing pythonish code

2007-02-02 Thread Neil Cerutti
On 2007-02-02, Toby A Inkster [EMAIL PROTECTED] wrote:
 Mizipzor wrote:
 One thing is that in c++ im used to have private members in
 classes and no member is altered except through the public
 functions of the class.

 By convention, class members starting with a single underscore
 are considered private. 

An important consideration is that this convention is simply a
lower level of enforcement than C++ provides. Private members in
C++ are accessible if you use pointers.

 Class members starting with a double underscore are mangled
 which makes it more difficult for other code (even subclasses!)
 to access the member. Difficult though -- not impossible.

I think it's best to never use such names in new code. Python's
mangling is troubled, since it uses unqualified names in the
mangle, resulting in ambiguity.

-- 
Neil Cerutti
Ushers will eat latecomers. --Church Bulletin Blooper
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Checking default arguments

2007-02-02 Thread Neil Cerutti
On 2007-02-02, Igor V. Rafienko [EMAIL PROTECTED] wrote:
 Hi,

 I was wondering whether it was possible to find out which
 parameter value is being used: the default argument or the
 user-supplied one. That is:  

 def foo(x, y=bar):
 # how to figure out whether the value of y is 
 # the default argument, or user-supplied?

 foo(1, bar) = user-supplied
 foo(1)= default

 {}.pop seems to be able to make this dictinction.

You can fake it (this may be how dict.pop work) by not providing
defaults, but using positional arguments.

Here's a silly example, which returns a tuple if the user
supplies the second argument, and a list otherwise.

def foo(x, *args):
  if len(args) == 0:
y_provided = True
y = bar
  else:
y_provided = False
y = args[0]
  if y_provided:
return (x, y)
  else:
return [x, y]

-- 
Neil Cerutti
Wonderful bargains for men with 16 and 17 necks --sign at clothing store
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to suppress DeprecationWarning: Old style callback, use cb_func(ok, store) instead

2007-02-03 Thread Neil Cerutti
On 2007-02-03, Gabriel Genellina [EMAIL PROTECTED] wrote:
 En Sat, 03 Feb 2007 06:12:33 -0300, Peter Otten [EMAIL PROTECTED]  
 escribió:

 John Nagle wrote:

How do I suppress DeprecationWarning: Old style callback, use
cb_func(ok,
 store) instead.  A library is triggering this message, the library is
 being fixed, but I need to make the message disappear from the output  
 of a
 CGI program.

 import warnings
 warnings.filterwarnings(ignore, message=Old style callback, use
 cb_func(ok, store) instead)

 Or you can be more aggressive and filter out all DeprecationWarnings:
 warnings.simplefilter(ignore,DeprecationWarning)
 (same as using option -Wignore::DeprecationWarning on the python command  
 line)

Ah, yes! The null module. Python should have more of these. I
mean shouldn't. ;)

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: confused about resizing array in Python

2007-02-05 Thread Neil Cerutti
On 2007-02-04, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote:
 How about the traditional programming languages like C, Pascal
 or C++?

 For a start they don't have a built in list type.  C and Pascal
 don't even have one in the standard library.  C++ has STL
 vectors and if you, the programmer, decide to store pointers in
 it instead of structures or objects then you have something
 like Python's list type.

You need to store some form of smart pointer (rather than a bare
pointer) in C++ standard containers in order to avoid heart, head
and stomach aches. A reference counted pointer type will come
fairly close to Python semantics.

-- 
Neil Cerutti
Eddie Robinson is about one word: winning and losing. --Eddie Robinson's agent
Paul Collier
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: HELP NEEDED ... Regd. Regular expressions PyQt

2007-02-05 Thread Neil Cerutti
On 2007-02-03, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
 I am trying to work out a regular expression in a PyQt
 environment for time in hh:mm:ss format. Any suggestions?

After you find your time in hh:mm:ss format, be sure to check out
time.strptime for a quick conversion.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Trouble fixing a broken ASCII string - replace mode in codec not working.

2007-02-06 Thread Neil Cerutti
On 2007-02-06, Robert Kern [EMAIL PROTECTED] wrote:
 John Nagle wrote:
   File D:\projects\sitetruth\InfoSitePage.py, line 285, in httpfetch
  sitetext = sitetext.encode('ascii','replace')  # force to clean ASCII
 
 UnicodeDecodeError: 'ascii' codec can't decode byte 0x92 in
 position 29151: ordinal not in range(128)
 
 Why is that exception being raised when the codec was told 'replace'?

 The .encode('ascii') takes unicode strings to str strings.
 Since you gave it a str string, it first tried to convert it to
 a unicode string using the default codec ('ascii'), just as if
 you were to have done unicode(sitetext).encode('ascii',
 'replace').

 I think you want something like this:

   sitetext = sitetext.decode('ascii', 'replace').encode('ascii', 'replace')

This is the cue for the translate method, which will be much
faster and simpler for cases like this. You can build the
translation table yourself, or use maketrans.

 asciitable = string.maketrans(''.join(chr(a) for a in xrange(127, 256)), 
...'?'*127)


You'd only want to do that once. Then to strip off the non-ascii:

sitetext.translate(asciitable)

I used a similar solution in an application I'm working on that
must uses a Latin-1 byte-encoding internally, but displays on
stdout in ascii.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Vim search under cursor

2007-02-07 Thread Neil Cerutti
On 2007-02-07, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
 Hi, I am using gvim to edit python source files. When I press * or
 #, I would want to search for the attribute name under the cursor
 and not the entire string.
  For example, If I have os.error and pressing * on top of error
 searches for os.error rather than error. How to set this, any Idea?

It's will to break things, but you can do this by editing the
iskeyword string and adding in the '.'. :h 'iskeyword'.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: doctests for interactive functions

2007-02-08 Thread Neil Cerutti
On 2007-02-08, Brian van den Broek [EMAIL PROTECTED] wrote:
 All classes take an optional argument input_function that
 determines how the class instance gets its input. If this is
 not provided, it defaults to raw_input. doctest tests reassign
 it so that they can be run automatically.

What I've done in these cases is create a file containing my test
input, and before running the doctests I remap sys.stdin to my
file of test data. Then you don't need test code cluttering up
your functions.

-- 
Neil Cerutti
We don't necessarily discriminate.  We simply exclude certain types of people.
--Colonel Gerald Wellman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: doctests for interactive functions

2007-02-09 Thread Neil Cerutti
On 2007-02-08, Brian van den Broek [EMAIL PROTECTED] wrote:
 Can I run the rough structure of my code past you to see if it
 is in the vicinity of what you mean? (I have removed some
 details for sake of a short(er :-)) post.)

Yes, this is a good way to think about it. Separate input from
validation. The downside is that control flow grows warts.

 My .get method looks like:

 def get(self, input_function=raw_input):
  while True:
  self._prompt_user()
  self._input = input_function()
  if self._is_valid_input():
  break
  else:
  self._process_invalid_input()
  self._set_data()

 The base class ._prompt_user just displays a prompt. Individual
 subclasses might implement ._prompt_user to both display a
 prompt, and further information about constraints on valid
 inputs, or generate a menu of options on the fly, etc.

 Subclasses implement ._is_valid_input to return True if the
 input meets the desired constraints, False otherwise. So,
 YesNo._is_valid_input ensures that ._input.lower() is in ['y',
 'n', 'yes', 'no'], for instance.

Your scheme may run into trouble with unexpected end of file when
input_function is not raw_input. File methods don't raise an
exception for EOF, they just return , the empty string. So you
may need to check of that return value, and raise IOError for
that case.

 ._process_invalid_input is implemented to provide useful
 feedback about invalid input. So,
 YesNo._process_invalid_input() emits a reminder that a value in
 ['y', 'n', 'yes', 'no'] is needed, for instance.

 ._set_data is usually implemented to just store the user's
 input as .data, but in some cases, it first subjects it to
 further processing. For instance YesNo._set_data sets .data to
 True if the user entered a yes value, False if they entered a
 no value.

 Is this the sort of thing you mean, or is this the sort of
 coupling you suggest I avoid?

It has to be coupled somewhere. This seems like a good place to
do it. The private methods can all be tested individually, so the
doctests for get can be quite simple, or even absent.

Note that sequestering the test input in a file doesn't allow for
good examples, unfortunately.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is Python for me?

2007-02-09 Thread Neil Cerutti
On 2007-02-09, jiddu [EMAIL PROTECTED] wrote:
 Hi,

 I'm planning to create a poker calculator, I learned some basic
 in highschool years ago and I was told for beginners Python is
 a good language to start.

Python *is* a good language to start.

 What I wanted to do is to first write a program which will be
 able to run through all the possible combinations of cards
 dealt out and use some counters to calculate different
 probabilities at different stages. Since that is a lot of data
 I think I have to store it in some kind of database or
 spreadsheet type thing? 

Unfortunately, that is a very *difficult* problem; no programming
library (save a hypothetical poker probability library) can make
it easy.

 Then I wanted to write a simple user interface so I could use
 my mouse to make selections of cards that I am dealt and that
 come on the flop and how many opponents and have the program
 find the calculated information and display it on the screen.

 I am wondering if I learn to use Python will I be able to write
 something like this? My friend studied some C in college so I
 thought I'd learn C++, turns out it is a very complicated
 language so I thought maybe I should try something else before
 I commit more time to the language.

Python can help you with creating an user interface, and with
several simple, powerful data structures. I think you ought to
lower your ambition a bit, at first. Firts write a program to
rank complete sets of poker hands. That should hold you for a
while.

-- 
Neil Cerutti
The recording I listened to had Alfred Brendel doing the dirty work of
performing this sonata (Liszt B minor) --Music Lit Essay
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to find all the same words in a text?

2007-02-11 Thread Neil Cerutti
On 2007-02-10, Johny [EMAIL PROTECTED] wrote:
 I need to find all the same words in a text .
 What would be the best idea  to do that?
 I used string.find but it does not work properly for the words.
 Let suppose I want to find a number 324 in the  text

 '45  324 45324'

 there is only one occurrence  of 324 word but string.find()   finds 2
 occurrences  ( in 45324 too)

 Must I use regex?
 Thanks for help

The first thing to do is to answer the question: What is a word?

The second thing to do is to design some code that can find
words in strings.

The last thing to do is to search those actual words for the word
you're looking for.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: gvim: doc string editing

2007-02-11 Thread Neil Cerutti
On 2007-02-11, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
 Hi, I am using gvim, and am looking for a way to tell gvim to
 automatically wrap long lines into multiple lines ( by
 automatically inserting the newline character) when I edit doc
 strings. I am sure somebody must have done this.

If tw (textwidth) is set to some apposite number, then it should
just work (unfortunately, this will also cause your code to wrap
unless you set up the comment strings properly for Python).
Alternatively, you can use the gq formatting command to wrap the
comment after it is composed.

Do :h format_comments for the full dope.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regular Expressions

2007-02-12 Thread Neil Cerutti
On 2007-02-10, Geoff Hill [EMAIL PROTECTED] wrote:
 What's the way to go about learning Python's regular
 expressions? I feel like such an idiot - being so strong in a
 programming language but knowing nothing about RE. 

A great way to learn regular expressions is to implement them.

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


<    1   2   3   4   5   6   7   8   9   10   >