Re: Append data to a list within a dict

2007-04-15 Thread Tina I
Alex Martelli wrote:
> Tina I <[EMAIL PROTECTED]> wrote:
>...
>> He he... at the age of 40 I'm well beyond school work ;)
> 
> Why would that be?  My wife's over 40, yet she's a student (currently at
> Stanford -- they were overjoyed to admit her, with lot of life
> experience as well as previous studies, apparently).  She's not taking
> elementary courses on Python (having co-written a book on Python,
> tech-reviewed a few, and having been the first woman coopted as a member
> of the PSF:-), but she _has_ been taken equivalent ones on Java and C++
> (languages she didn't previously know), as well as calculus,
> neurophysiology, and other strange things that are part of the "Symbolic
> Systems" studies.
> 
> Down with ageism!-)
> 
> 
> Alex
>  
It's not really ageism, just how I feel *my self* about going back to 
school. I'm not done learning though, it's just that I can give my self 
the luxury of learning whatever I want, just what I want at the pace 
that I want. And since I happen to like computers that's mostly what I 
concentrate about. Right now I'm hooked on Python, but also messing 
about with PHP and Javascript. Tried some Java but didn't like it... 
Threw out Windows a couple of years ago and have spent quite some time 
learning the ins and outs of Linux.

So even if I probably will never go back to school I'm looking forward 
to many many years learning new and exciting things :)

Tina
(Sorry for the way OT post. I just couldn't stop my own ramble ;)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Really badly structured Python Books.

2007-04-15 Thread readability
On Apr 14, 2:37 pm, "Andre P.S Duarte" <[EMAIL PROTECTED]>
wrote:
> I started reading the beginning Python book. It is intended for people
> who are starting out in the Python world. But it is really
> complicated, because he tries to explain, then after a bad explanation
> he puts out a bad example. I really recommend NOT reading the book.
> For it will make you want not to continue in Python. This is just me
> letting the air out of my lungs. No need to reply this is just a
> recommendation. Txs for the opportunity .

My experience with technical books of all types is that often you'll
find some that don't work for you at all, while they'll be great for
other people. If it is the Apress volume you're talking of, I quite
like it because its more practical than the Learning Python book from
o'reilly. Although the one I preferred the most was the online text of
Dive into Python; http://diveintopython.org/. I can see where you're
coming from though.

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


Re: proposed PEP: iterator splicing

2007-04-15 Thread Paul Rubin
John Nagle <[EMAIL PROTECTED]> writes:
> > Less clutter, and avoids yet another temp variable polluting the namespace.
>  Are we in danger of running out of temp variables?

There is unfortunately no way to contain the scope of a loop index to the
inside of the loop.  Therefore introducing more useless loop indexes creates
more scorekeeping work and bug attractants.  Better to get rid of them.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tuples, index method, Python's design

2007-04-15 Thread Paul Rubin
"Rhamphoryncus" <[EMAIL PROTECTED]> writes:
> Indexing cost, memory efficiency, and canonical representation: pick
> two.  You can't use a canonical representation (scalar values) without
> some sort of costly search when indexing (O(log n) probably) or by
> expanding to the worst-case size (UTF-32).  Python has taken the
> approach of always providing efficient indexing (O(1)), but you can
> compile it with either UTF-16 (better memory efficiency) or UTF-32
> (canonical representation).

I still don't get it.  UTF-16 is just a data compression scheme, right?
I mean, s[17] isn't the 17th character of the (unicode) string regardless
of which memory byte it happens to live at?  It could be that that accessing
it takes more than constant time, but that's hidden by the implementation.

So where does the invariant c==s[s.index(c)] fail, assuming s contains c?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: proposed PEP: iterator splicing

2007-04-15 Thread Anton Vredegoor
Paul Rubin wrote:

> def some_gen():
>...
>yield *some_other_gen()
> 
> comes to mind.  Less clutter, and avoids yet another temp variable
> polluting the namespace.
> 
> Thoughts?

Well, not directly related to your question, but maybe these are some 
ideas that would help determine what we think generators are and what we 
would like them to become.

I'm currently also fascinated by the new generator possibilities, for 
example sending back a value to the generator by making yield return a 
value. What I would like to use it for is when I have a very long 
generator and I need just a slice of the values. That would mean running 
through a loop, discarding all the values until the generator is in the 
desired state and only then start doing something with the output. 
Instead I would like to directly set or 'wind' -like a file- a generator 
into some specific state. That would mean having some convention for 
generators signaling their length (like xrange):

 >>> it = xrange(100)
 >>> len(it)
100
 >>>

Note: xrange didn't create a list, but it has a length!

Also we would need some convention for a generator to signal that it can 
jump to a certain state without computing all previous values. That 
means the computations are independent and could for example be 
distributed across different processors or threads.

 >>> it = range(100)
 >>> it[50:]
[50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 
68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 
86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
 >>>

But currently this doesn't work for xrange:

 >>> it = xrange(100)
 >>> it[50:]
Traceback (most recent call last):
   File "", line 1, in ?
TypeError: sequence index must be integer
 >>>

Even though xrange *could* know somehow what its slice would look like.

Another problem I have is with the itertools module:

 >>> itertools.islice(g(),1)
Traceback (most recent call last):
   File "", line 1, in ?
ValueError: Stop argument must be a non-negative integer or None.
 >>>

I want islice and related functions to use long integers for indexing. 
But of course this only makes sense when there already are generator 
slices possible, else there would be no practical way to reach such big 
numbers by silently looping through the parts of the sequence until one 
reaches the point one is interested in.

I also have thought about the thing you are proposing, there is 
itertools.chain of course but that only works when one can call it from 
'outside' the generator.

Suppose one wants to generate all unique permutations of something. One 
idea would be to sort the sequence and then start generating successors 
until one reaches the point the sequence is completely reversed. But 
what if one wants to start with the actual state the sequence is in? One 
could generate successors until one reaches the 'end' and then continue 
by generating successors from the 'beginning' until one reaches the 
original state. Note that by changing the cmp function this generator 
could also iterate in reverse from any point. There only would need to 
be a way to change the cmp function of a running generator instance.

from operator import ge,le
from itertools import chain

def mutate(R,i,j):
 a,b,c,d,e = R[:i],R[i:i+1],R[i+1:j],R[j:j+1],R[j+1:]
 return a+d+(c+b+e)[::-1]

def _pgen(L, cmpf = ge):
 R = L[:]
 yield R
 n = len(R)
 if n >= 2:
 while True:
 i,j = n-2,n-1
 while cmpf(R[i],R[i+1]):
 i -= 1
 if i == -1:
 return
 while cmpf(R[i],R[j]):
 j -= 1
 R = mutate(R,i,j)
 yield R

def perm(L):
 F = _pgen(L)
 B = _pgen(L,le)
 B.next()
 return chain(F,B)

def test():
 P = '12124'
 g = perm(P)
 for i,x in enumerate(g):
 print '%4i) %s' %(i, x)

if __name__ == '__main__':
 test()

A.




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


Standardizing XML

2007-04-15 Thread ZeeGeek
Is there a module for python to standardize XML?  Since MSN Live Space
doesn't use standard XML in the posts, I want to standardize them so
that I can use them elsewhere.

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


Re: Python editor/IDE on Linux?

2007-04-15 Thread Daniel Gee
In Linux I just use Gedit. In windows I settle for Notepad2. With
python having help built into the interpreter, anything more than line
numbering, simple syntax highlighting, and auto-indent when you hit
enter just doesn't seem necessary. Vim has b and c, but not a.

Using Kate for Python would probably be very similar to using Gedit
(from my limited experience with Kate).

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


Re: Lists and Tuples and Much More

2007-04-15 Thread Hendrik van Rooyen
 "James Stroud" <[EMAIL PROTECTED]> wrote:

> Hendrik van Rooyen wrote:

> >
> > But if you limit it to one thing and its inverse, its quite useful, and it
> > would be nice to have one "doubledict" that can be accessed as speedily
> > from either end...
> >
> > Sort of an internally linked list of mixed hashed immutables, where:
> >
> > doubledict["Frank Everyman"] yields addy, and
> > doubledict[addy] yields "Frank Everyman"
> >
> > It would have direct applicability in things like the label table in
> > an assembler, for debugging and so on.
> >
> > - Hendrik
> >
>
> I'm thinking that, to avoid big a lot of ambiguity, such a double dict
> would need to be implemented as two distinctly referenced data structures:

not sure that I agree with this - what I have in mind is almost like this:

{a:b,b:a,.} - but avoiding the overhead of storing the "keys" and "data"
twice...

Guess at notation:

{,,}  - I know the <> is ugly so lets try:

{(a:b),(c:d),...}- not much better...


>
> class DD(object):
>def __init__(self, adict):
>  self._fwd = {}
>  self._fwd.update(adict)
>  self._bkwk = dict(v,k for k,v in adict.items())
>def fwd(self, k)
>  return self._fwd[k]
>def bkwd(self, k)
>  return self._bkwd[k]
>def __setitem__(self, k, v):
>  self._fwd[k] = v
>  self._bkwd[v] = k
>def __getitem__(self, k):
>  if (k in self._fwd) and (k in self._bkwd):
>raise KeyError, 'Which do I look in first?'
>  else:
>raise KeyError, 'Too much guesswork. Use fwd() or bkwd().'
>
> James

This is the problem - you can also do it with two dicts, but then you have to
do try-except and handle KeyError if you guess wrong. This is what I have
been doing.

I think that trying to go "back and forth" is a mistake - easier to just have
one
link, and store "thing" and "pointer to thing's partner".

In practice you would probably either "know" what you are dealing with
because of where you got the thing you are looking up from, or in true
duck typing style you would not "care".

On the other hand, if you store two links, then you can have:

"thing", "pointer to next thing in group", "pointer to previous thing in group"

and then you can have something like:

dd={(a:b:c),(d:e:f:g:h),}

and that would return a list [a,b,c], from any of dd[a], dd[b], dd][c],
and likewise for "entry points" of d,e,f,g, or h, to yield [d,e,f,g,h]

This makes me think that the correct notation would be:

{[a,b,c],[d,e,f,g,h],...}

but maybe not because it looks like a set of lists...

then how about:

{[a:b:c],[d:e:f:g:h],...}

and yes I know that:

{[a:b:c:f],[d:e:f:g:h],...} - can't be done using
only two pointers,  not even with fancy footwork

- Hendrik


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


Re: Python Feature Request: Allow changing base of member indices to 1

2007-04-15 Thread Nick Craig-Wood
Sherm Pendley <[EMAIL PROTECTED]> wrote:
>  "Paddy" <[EMAIL PROTECTED]> writes:
> 
> > Having more than one index start point would be a maintenance
> > nightmare best avoided.
> 
>  Quite right.
> 
> > (It can be done in Perl).
> 
>  When was the last time you used Perl? It was allowed in Perl 4 and earlier,
>  because many Perl users were moving from Awk, which uses an array base of 1.
>  Even then, having multiple index start points within a single program wasn't
>  the idea; the idea was to allow programs originally written in Awk to be
>  ported to Perl with minimal updating.
> 
>  It was deprecated as of 5.0 though - which was released in '94. It still
>  works, for the sake of backwards compatibility, but its use in new code is
>  highly discouraged.

I seem to remember from "Programming Perl" that Larry Wall said it was
a serious mistake to add this feature to perl.

If it is a feature too far for perl then it is *definitely* a feature
too far for python ;-)

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: combination function in python

2007-04-15 Thread bearophileHUGS
DanielJohnson:
> Please help, I couldnt find the function through help.

You can't find it because it's not there:

def factorial(n):
"""factorial(n): return the factorial of the integer n.
factorial(0) = 1
factorial(n) with n<0 is -factorial(abs(n))
"""
result = 1
for i in xrange(1, abs(n)+1):
result *= i
if n >= 0:
return result
else:
return -result

def binomial(n, k):
"""binomial(n, k): return the binomial coefficient (n k)."""
assert n>0 and isinstance(n, (int, long)) and isinstance(k, (int,
long))
if k < 0 or k > n:
return 0
if k == 0 or k == n:
return 1
return factorial(n) // (factorial(k) * factorial(n-k))

Bye,
bearophile

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


Re: Python and XML?

2007-04-15 Thread Stefan Behnel
Leonard J. Reder wrote:
> What I as really after though was other possible solutions
> like JAX in the Java world or Gnosis in the Python world.
> 
> Something that can take a Relax NG Schema and compile
> it into a bunch of parser/generator objects for handling
> an XML format.

That's why I was asking why you need this. Validation is provided by RNG
itself, so all you would need is some kind of mapping that outputs and parses
it for you? What's your target format? Python objects?

http://codespeak.net/lxml/objectify.html

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


Re: Standardizing XML

2007-04-15 Thread Stefan Behnel
ZeeGeek wrote:
> Is there a module for python to standardize XML?  Since MSN Live Space
> doesn't use standard XML in the posts, I want to standardize them so
> that I can use them elsewhere.

Could you give a hint what you mean with "standardize"? What's non
standardized XML for you?

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


Re: Python editor/IDE on Linux?

2007-04-15 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Dotan Cohen
wrote:

> Has anyone any experience with Python in Kate or Kdevelop?

I'm using Kate/KWrite quite often.  Syntax highlighting and an auto
indention for Python are standard features.  The only "extra" I'm using is
the word completion plug-in to spare myself too much typing and limit
typing errors in long names.

Along with the editor there's always a terminal with IPython running to
test and explore my own code and libraries.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python editor/IDE on Linux?

2007-04-15 Thread Paddy
On Apr 15, 9:33 am, "Daniel Gee" <[EMAIL PROTECTED]> wrote:
> In Linux I just use Gedit. In windows I settle for Notepad2. With
> python having help built into the interpreter, anything more than line
> numbering, simple syntax highlighting, and auto-indent when you hit
> enter just doesn't seem necessary. Vim has b and c, but not a.

I'm not sure of what you are numbering, but vim does have:
 * Line numbering.
 * Syntax highlighting.
 * Auto-indenting.

>
> Using Kate for Python would probably be very similar to using Gedit
> (from my limited experience with Kate).


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


Re: Getting started with python

2007-04-15 Thread James Stroud
Eric wrote:
> Hello, after reading some of the book Programming Python it seems that
> python is something I would like to delve deeper into. The only thing
> is, I have no idea what I should try and write. So I was hoping that
> someone here could help point me to a group/project that would be a
> good starting place for a person with limited python knowledge, but
> that is willing to learn whatever is necessary. I'm hoping that with a
> goal I can start to learn python instead of just playing around with
> it. Thanks.
> 

Here is a protocol I have used in the past:

1. Realize there is a program you really wish you had.
2. Find out that, upon relentless googling, no
   such program exists that meets your needs exactly.
3. If 2 fails and a program exists, go back to 1.
4. Proceed to write this program no matter what it takes--you
   may even face some "sitdowns" with your friends, family,
   and/or employers.
5. (Very important)
   A. Refer to this list periodically for help but making
  sure to properly phrase you questions.
   B. Try not to rewrite any libraries by first ascertaining
  whether a library doesn't already exist for the
  sub-task you are programming.
6. Enjoy the new program you have written and the new
   knowledge you have gained.

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


OverflowError: mktime argument out of range ???

2007-04-15 Thread Jorgen Bodde
Hi  List

I am working on an app to store guitar songs I am practicing, and for
the fun of it I want to store the date of songs when they were
originally made. So far so good..

However, my taste of music is "Rag Time Blues" and that os OLD, very
OLD music. So it happened I entered a song from the date " 28 dec
1928".

It appears time.mktime cannot handle these 'extremities' ? I get an
overflow error. is there by any chance a solution to this? I do know
modern languages support at least 1900 as date (and now that I come to
think of it, songs from J.S. Bach are excluded from entering as well)
..

This is what I try:

>>> time.mktime((1928, 12,28, 0, 0, 0,  0, 0, 0))
Traceback (most recent call last):
  File "", line 1, in 
OverflowError: mktime argument out of range

The only solution I can think of is making a custom time class that
handles all years, dates and months, but that is plain silly. I want
to be able to use the long date formatting etc, and that would mean
rewriting that part as well.

Any help is appreciated!
- Jorgen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: combination function in python

2007-04-15 Thread Steven D'Aprano
On Sun, 15 Apr 2007 02:38:31 -0700, bearophileHUGS wrote:

> DanielJohnson:
>> Please help, I couldnt find the function through help.
> 
> You can't find it because it's not there:
> 
> def factorial(n):
> """factorial(n): return the factorial of the integer n.
> factorial(0) = 1
> factorial(n) with n<0 is -factorial(abs(n))
> """
> result = 1
> for i in xrange(1, abs(n)+1):
> result *= i
> if n >= 0:
> return result
> else:
> return -result
> 
> def binomial(n, k):
> """binomial(n, k): return the binomial coefficient (n k)."""
> assert n>0 and isinstance(n, (int, long)) and isinstance(k, (int,
> long))
> if k < 0 or k > n:
> return 0
> if k == 0 or k == n:
> return 1
> return factorial(n) // (factorial(k) * factorial(n-k))


That's a naive and slow implementation. For even quite small values of n
and k, you end up generating some seriously big long ints, and then have
to (slowly!) divide them.

A better implementation would be something like this:

def binomial(n, k):
if not 0 <= k <= n:
return 0
if k == 0 or k == n:
return 1
# calculate n!/k! as one product, avoiding factors that 
# just get canceled
P = k+1
for i in xrange(k+2, n+1):
P *= i
# if you are paranoid:
# C, rem = divmod(P, factorial(n-k))
# assert rem == 0
# return C
return P//factorial(n-k)


There's probably even a really clever way to avoid that final division,
but I suspect that would cost more in time and memory than it would save.


-- 
Steven.

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


Re: tuples, index method, Python's design

2007-04-15 Thread Neil Hodgson
Paul Rubin:

> I still don't get it.  UTF-16 is just a data compression scheme, right?
> I mean, s[17] isn't the 17th character of the (unicode) string regardless
> of which memory byte it happens to live at?  It could be that that accessing
> it takes more than constant time, but that's hidden by the implementation.

Python Unicode strings are arrays of code units which are either 16 
or 32 bits wide with the width of a code unit determined when Python is 
compiled. s[17] will be the 18th code unit of the string and is found by 
indexing with no ancillary data structure or processing to interpret the 
string as a sequence of code points.

This is the same technique used by other languages such as Java. 
Implementing the Python string type with a data structure that can 
switch between UTF-8, UTF-16 and UTF-32 while preserving the appearance 
of a UTF-32 sequence has been proposed but has not gained traction due 
to issues of complexity and cost.

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


Re: OverflowError: mktime argument out of range ???

2007-04-15 Thread Michael Bentley

On Apr 15, 2007, at 5:41 AM, Jorgen Bodde wrote:

> This is what I try:
>
 time.mktime((1928, 12,28, 0, 0, 0,  0, 0, 0))
> Traceback (most recent call last):
>   File "", line 1, in 
> OverflowError: mktime argument out of range

Probably depends on your system.  It doesn't break for me:

 >>> import time
 >>> time.mktime((1928, 12,28, 0, 0, 0,  0, 0, 0))
-1294164000.0


---
Simplicity is the ultimate sophistication.
   -Leonardo da Vinci



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


Re: OverflowError: mktime argument out of range ???

2007-04-15 Thread Diez B. Roggisch
Jorgen Bodde schrieb:
> Hi  List
> 
> I am working on an app to store guitar songs I am practicing, and for
> the fun of it I want to store the date of songs when they were
> originally made. So far so good..
> 
> However, my taste of music is "Rag Time Blues" and that os OLD, very
> OLD music. So it happened I entered a song from the date " 28 dec
> 1928".
> 
> It appears time.mktime cannot handle these 'extremities' ? I get an
> overflow error. is there by any chance a solution to this? I do know
> modern languages support at least 1900 as date (and now that I come to
> think of it, songs from J.S. Bach are excluded from entering as well)
> ..
> 
> This is what I try:
> 
 time.mktime((1928, 12,28, 0, 0, 0,  0, 0, 0))
> Traceback (most recent call last):
>  File "", line 1, in 
> OverflowError: mktime argument out of range
> 
> The only solution I can think of is making a custom time class that
> handles all years, dates and months, but that is plain silly. I want
> to be able to use the long date formatting etc, and that would mean
> rewriting that part as well.

import datetime
datetime.date(1928, 12, 28)

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


Re: Python editor/IDE on Linux?

2007-04-15 Thread 7stud
On Apr 15, 2:33 am, "Daniel Gee" <[EMAIL PROTECTED]> wrote:
>
> anything more than line
> numbering, simple syntax highlighting, and auto-indent when you hit
> enter just doesn't seem necessary. Vim has b and c, but not a.
>

a:
:set nu
:set nonu

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


Re: OverflowError: mktime argument out of range ???

2007-04-15 Thread Jorgen Bodde
Ok thanks, I missed out on datetime where the methods I need are also present.

I'll be refactoring my data a bit, thanks again!
- Jorgen

On 4/15/07, Diez B. Roggisch <[EMAIL PROTECTED]> wrote:
> Jorgen Bodde schrieb:
> > Hi  List
> >
> > I am working on an app to store guitar songs I am practicing, and for
> > the fun of it I want to store the date of songs when they were
> > originally made. So far so good..
> >
> > However, my taste of music is "Rag Time Blues" and that os OLD, very
> > OLD music. So it happened I entered a song from the date " 28 dec
> > 1928".
> >
> > It appears time.mktime cannot handle these 'extremities' ? I get an
> > overflow error. is there by any chance a solution to this? I do know
> > modern languages support at least 1900 as date (and now that I come to
> > think of it, songs from J.S. Bach are excluded from entering as well)
> > ..
> >
> > This is what I try:
> >
>  time.mktime((1928, 12,28, 0, 0, 0,  0, 0, 0))
> > Traceback (most recent call last):
> >  File "", line 1, in 
> > OverflowError: mktime argument out of range
> >
> > The only solution I can think of is making a custom time class that
> > handles all years, dates and months, but that is plain silly. I want
> > to be able to use the long date formatting etc, and that would mean
> > rewriting that part as well.
>
> import datetime
> datetime.date(1928, 12, 28)
>
> Diez
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Standardizing XML

2007-04-15 Thread Jan Danielsson
ZeeGeek wrote:
> Is there a module for python to standardize XML?  Since MSN Live Space
> doesn't use standard XML in the posts, I want to standardize them so
> that I can use them elsewhere.

   Hmm... XML _is_ standardized. If it doesn't follow the specs, then
it's not XML. If you want to make XML out of something which isn't XML,
you'll probably have to be a little more specific about how this other
format works.


-- 
Kind regards,
Jan Danielsson
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: combination function in python

2007-04-15 Thread bearophileHUGS
Steven D'Aprano:
> That's a naive and slow implementation. For even quite small values
> of n and k, you end up generating some seriously big long ints,
> and then have to (slowly!) divide them.
> A better implementation would be something like this:

You are right, thank you for the improvement (the advantage of the
older implementation is that it's naive, so it's a bit more probably
correct compared to more complex code I may write. For Python code I
often tend to write a naive version first, create many testcases,
slowly fixing all the corner cases (like factorial(-5)), and only
later find a faster/better implementation if I have some time to do it
or if I need it. If I need to do lot of binomials the gmpy by Alex
helps).

Bye,
bearophile

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


Re: function with list argument defaulting to [] - what's going on here???

2007-04-15 Thread Tim Leslie
On 14 Apr 2007 20:20:42 -0700, Paddy <[EMAIL PROTECTED]> wrote:
> On Apr 15, 3:58 am, Steven D'Aprano
> <[EMAIL PROTECTED]> wrote:
> > On Sat, 14 Apr 2007 17:33:11 -0800, Troy Melhase wrote:
> > > On 4/14/07, Mike <[EMAIL PROTECTED]> wrote:
> > >> While trying to write a recursive function involving lists, I came
> > >> across some (to me) odd behavior which I don't quite understand. Here's
> > >> a trivial function showing the problem.
> >
> > > fromhttp://docs.python.org/ref/function.html:
> >
> > > Default parameter values are evaluated when the function definition is
> > > executed. This means that the expression is evaluated once, when the
> > > function is defined, and that that same ``pre-computed'' value is used
> > > for each call. This is especially important to understand when a
> > > default parameter is a mutable object, such as a list or a dictionary:
> > > if the function modifies the object (e.g. by appending an item to a
> > > list), the default value is in effect modified.
> >
> > This comes up so often that I wonder whether Python should issue a warning
> > when it sees [] or {} as a default argument.
> >
> > What do people think? A misuse or good use of warnings?
> >
> > --
> > Steven.
>
> I wonder if it is a check done by Pylint or PyChecker?

It is a check done by pylint

Tim

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


Re: OverflowError: mktime argument out of range ???

2007-04-15 Thread John Machin
On Apr 15, 8:48 pm, Michael Bentley <[EMAIL PROTECTED]> wrote:
> On Apr 15, 2007, at 5:41 AM, Jorgen Bodde wrote:
>
> > This is what I try:
>
>  time.mktime((1928, 12,28, 0, 0, 0,  0, 0, 0))
> > Traceback (most recent call last):
> >   File "", line 1, in 
> > OverflowError: mktime argument out of range
>
> Probably depends on your system.

Maybe it does. It sure would be nice to get a definite answer. Pity
nobody documented the time module. Oh yeah, and the secret closed-shop
source code -- damnation! Anyone got a bootleg pirate copy of
timemodule.c lying around anywhere?

>  It doesn't break for me:

Please consider the possibility that it didn't break for the OP
either.

>
>  >>> import time
>  >>> time.mktime((1928, 12,28, 0, 0, 0,  0, 0, 0))
> -1294164000.0
>
> ---
> Simplicity is the ultimate sophistication.
>-Leonardo da Vinci


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


Re: combination function in python

2007-04-15 Thread Jussi Piitulainen
Steven D'Aprano writes:
> bearophileHUGS wrote:
...
>> return factorial(n) // (factorial(k) * factorial(n-k))
> 
> That's a naive and slow implementation. For even quite small values
> of n and k, you end up generating some seriously big long ints, and
> then have to (slowly!) divide them.

A better _definition_ of the binomial coefficient with upper index r
and lower index k is (r * (r - 1) * ...) / (k * (k - 1) * ...) with k
factors in both products. These are called falling factorial powers by
Graham, Knuth and Patashnik. Their notation is to write n^k and k^k
but with the exponent underlined; the latter is just k!, when k > 0. A
straightforward implementation below.

> A better implementation would be something like this:
> 
> def binomial(n, k):
> if not 0 <= k <= n:
> return 0
> if k == 0 or k == n:
> return 1
> # calculate n!/k! as one product, avoiding factors that 
> # just get canceled
> P = k+1
> for i in xrange(k+2, n+1):
> P *= i
> # if you are paranoid:
> # C, rem = divmod(P, factorial(n-k))
> # assert rem == 0
> # return C
> return P//factorial(n-k)
> 
> There's probably even a really clever way to avoid that final
> division, but I suspect that would cost more in time and memory than
> it would save.

Here's one non-clever one for integers n, k that uses n^k / k^k
(falling powers) with the smaller of k and n - k as lower index:

def choose(n, k):
   if 0 <= k <= n:
   ntok = 1
   ktok = 1
   for t in xrange(1, min(k, n - k) + 1):
  ntok *= n
  ktok *= t
  n -= 1
   return ntok // ktok
   else:
   return 0
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: proposed PEP: iterator splicing

2007-04-15 Thread Steven Bethard
Paul Rubin wrote:
> The boilerplate
> 
> def some_gen():
>...
>for x in some_other_gen():
>yield x
>...
> 
> is so common (including the case where some_other_gen is the same as
> some_gen, i.e. it's a recursive call) that I find myself wanting
> a more direct way to express it:
> 
> def some_gen():
>...
>yield *some_other_gen()
> 
> comes to mind.  Less clutter, and avoids yet another temp variable
> polluting the namespace.
> 
> Thoughts?

This has been brought up before and there was mixed support:

http://www.python.org/dev/summary/2006-01-16_2006-01-31/#yielding-from-a-sub-generator

My guess is that the only way it has any chance is if someone takes the 
time to implement it and posts a full-fledged PEP to python-dev.

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


Re: Getting started with python

2007-04-15 Thread Army1987
"Paddy" <[EMAIL PROTECTED]> ha scritto nel messaggio 
news:[EMAIL PROTECTED]

> On a different tack, from:
> http://tickletux.wordpress.com/2007/01/24/using-fizzbuzz-to-find-developers-who-grok-coding/
> It seems you need to learn how to write a Fizz-Buzz
> program to get a job now-a-days :-)

Something less idiotic? I took longer to type a program to do that than to 
figure out how to do that. 


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


Re: Getting started with python

2007-04-15 Thread [EMAIL PROTECTED]
On Apr 14, 7:46 pm, "Eric" <[EMAIL PROTECTED]> wrote:
> Hello, after reading some of the book Programming Python it seems that
> python is something I would like to delve deeper into. The only thing
> is, I have no idea what I should try and write. So I was hoping that
> someone here could help point me to a group/project that would be a
> good starting place for a person with limited python knowledge, but
> that is willing to learn whatever is necessary. I'm hoping that with a
> goal I can start to learn python instead of just playing around with
> it. Thanks.

If you want to play around with simple graphics and writing simple
ascii files to disk then dex tracker may be a good project for you.  I
am currently playing around with generating random sounds to disk and
random rythoms.  (I also have a harder graphics problem that when I
solve will break the music program wide open).  
https://sourceforge.net/projects/dex-tracker
You would go to the (project homepage) website for dependencies
http://www.stormpages.com/edexter/csound.html (not all are required
for all sub-programs but you do want wxwindows).  It would probily be
cool to expand the idea into non-random series of numbers and I have
just started to code this particular tool.  I can upload it to my
google groups if you are intrested

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


Re: Getting started with python

2007-04-15 Thread [EMAIL PROTECTED]
On Apr 14, 7:46 pm, "Eric" <[EMAIL PROTECTED]> wrote:
> Hello, after reading some of the book Programming Python it seems that
> python is something I would like to delve deeper into. The only thing
> is, I have no idea what I should try and write. So I was hoping that
> someone here could help point me to a group/project that would be a
> good starting place for a person with limited python knowledge, but
> that is willing to learn whatever is necessary. I'm hoping that with a
> goal I can start to learn python instead of just playing around with
> it. Thanks.

I have a little sub-project where I generate random numbers to a music
file (a simpe ascii format that works in a grid)
http://www.stormpages.com/edexter/csound.html or if you see some other
part of it you would like to work on or expand..
https://sourceforge.net/projects/dex-tracker I haven't added the sub-
project yet but I can upload it to some google space if you are
intrested..  (uses wxwindows and python 2.5)

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


Re: proposed PEP: iterator splicing

2007-04-15 Thread Kay Schluehr
On Apr 15, 10:23 am, Anton Vredegoor <[EMAIL PROTECTED]>
wrote:

> I'm currently also fascinated by the new generator possibilities, for
> example sending back a value to the generator by making yield return a
> value. What I would like to use it for is when I have a very long
> generator and I need just a slice of the values. That would mean running
> through a loop, discarding all the values until the generator is in the
> desired state and only then start doing something with the output.
> Instead I would like to directly set or 'wind' -like a file- a generator
> into some specific state.

Maybe you should start by developing a design pattern first and
publish it in the Cookbook. I have the fuzzy impression that the idea
you are after, requires more powerfull control structures such as
delimited continuations that are beyond ths scope of Pythons simple
coroutines.

Kay

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


Re: Getting started with python

2007-04-15 Thread Dorai
On Apr 15, 3:35 am, James Stroud <[EMAIL PROTECTED]> wrote:
> Eric wrote:
> > Hello, after reading some of the book Programming Python it seems that
> > python is something I would like to delve deeper into. The only thing
> > is, I have no idea what I should try and write. So I was hoping that
> > someone here could help point me to a group/project that would be a
> > good starting place for a person with limited python knowledge, but
> > that is willing to learn whatever is necessary. I'm hoping that with a
> > goal I can start to learn python instead of just playing around with
> > it. Thanks.
>
> Here is a protocol I have used in the past:
>
> 1. Realize there is a program you really wish you had.
> 2. Find out that, upon relentless googling, no
>such program exists that meets your needs exactly.
> 3. If 2 fails and a program exist s, go back to 1.
> 4. Proceed to write this program no matter what it takes--you
>may even face some "sitdowns" with your friends, family,
>and/or employers.
> 5. (Very important)
>A. Refer to this list periodically for help but making
>   sure to properly phrase you questions.
>B. Try not to rewrite any libraries by first ascertaining
>   whether a library doesn't already exist for the
>   sub-task you are programming.
> 6. Enjoy the new program you have written and the new
>knowledge you have gained.
>
> James

Start out with something simple and go deeper. For example, here is
one progression:

1. A simple program that counts words (wc) - read from a file,
tokenize, count
2. A variation of wc that does word frequency count (counts how many
times each word occurs) - wfc - In addition to 1, this allows you to
use a data structure to store words and search for them to update the
count. You may also sort the output.
3. A variation of wfc that reads from a file a set of noise words and
stores them in memory. As you are tokenizing, drop the noise words
from counting (or count noise words)

You could do similar things with database programming (start with
something simple and gradually increase the level of complexity or any
other area.

You can also access Python cookbook, use the examples as a starting
point and build variations. This not only allows you to read some well
written code but also understand various techniques.

Another suggestion is to get hold of a book "Software Tools" and try
to code all the examples in Python.

I found the best way to learn a language is to read some code, write
some code and keep improving it. Many improvements will suggest
themselves as you keep coding.

Hope this helps.

Dorai
www.thodla.com

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


Re: tuples, index method, Python's design

2007-04-15 Thread Roel Schroeven
Paul Rubin schreef:
> "Rhamphoryncus" <[EMAIL PROTECTED]> writes:
>> Indexing cost, memory efficiency, and canonical representation: pick
>> two.  You can't use a canonical representation (scalar values) without
>> some sort of costly search when indexing (O(log n) probably) or by
>> expanding to the worst-case size (UTF-32).  Python has taken the
>> approach of always providing efficient indexing (O(1)), but you can
>> compile it with either UTF-16 (better memory efficiency) or UTF-32
>> (canonical representation).
> 
> I still don't get it.  UTF-16 is just a data compression scheme, right?
> I mean, s[17] isn't the 17th character of the (unicode) string regardless
> of which memory byte it happens to live at?  It could be that that accessing
> it takes more than constant time, but that's hidden by the implementation.
> 
> So where does the invariant c==s[s.index(c)] fail, assuming s contains c?

I didn't get it either, but now I understand. Like you, I thought Python 
Unicode strings contain a canonical representation (in interface, not 
necessarily in implementation) but apparently that is not true; see 
Neil's post and the reference manual 
(http://docs.python.org/ref/types.html#l2h-22).

A simple example on my Python installation, apparently compiled to use 
UTF-16 (sys.maxunicode == 65535):

 >>> s = u'\u1d400'
 >>> s.index(s)
0
 >>> s[0]
u'\u1d40'
 >>> s == s[0]
False


In this case s[0] is not the full Unicode scalar, but instead just the 
first part of the surrogate pair consisting of 0x1D40 (in s[0]) and 
0x (in s[1]).

-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

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


Re: Calling private base methods

2007-04-15 Thread Isaac Rodriguez

> The fact that I had
> to resort to this trick is a big indication of course that genuinely
> private members (as opposed to a 'keep off' naming convention) are a bad
> idea in general.


The fact that you had to resort to this trick is a big indication that
the library you were using is bad designed; it has nothing to do with
private members being a bad idea. You were using a library which
interface was in-complete (provided that you "genuinely" really needed
to access the private member to do what you wanted to do).

Private members is a great thing. They are the foundations of
encapsulation and object oriented design. The fact that Python allows
you to access "private" methods because the only "restriction" is the
name mangling does not mean you should access them and use them
directly.

I don't see the way private members are handled in Python a strenght
or a weakness of the language as compared to other languages. However,
I do see libraries that do not provide all the needed interface
methods as poor designed, or programmers that try to work around the
public interface of a class when it is not needed as poor programmers.

Thanks,

- Isaac.

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


Re: proposed PEP: iterator splicing

2007-04-15 Thread Anton Vredegoor
Kay Schluehr wrote:

> Maybe you should start by developing a design pattern first and
> publish it in the Cookbook. I have the fuzzy impression that the idea
> you are after, requires more powerfull control structures such as
> delimited continuations that are beyond ths scope of Pythons simple
> coroutines.

I was reacting to a request for thoughts. I firmly believe that there 
should be a relatively unrestricted brainstorming phase before one tries 
to implement things. I have often noticed a lot of counterproductive 
bickering about use cases and implementations on the developers list, 
but luckily not so much here. There is something like premature 
optimizations with respect to creative processes too!

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


is laziness a programer's virtue?

2007-04-15 Thread Xah Lee
Laziness, Perl, and Larry Wall

Xah Lee, 20021124

In the unix community there's quite a large confusion and wishful
thinking about the word laziness. In this post, i'd like to make some
clarifications.

American Heritage Dictionary third edition defines laziness as:
“Resistant to work or exertion; disposed to idleness.”

When the sorcerer Larry Wall said “The three chief virtues of a
programmer are: Laziness, Impatience and Hubris”, he used the word
“laziness” to loosely imply “natural disposition that results in being
economic”. As you can see now, “Resistant to work or exertion” is
clearly not positive and not a virtue, but “natural disposition that
results in economy” is a good thing if true.

When Larry Wall said one of programer's virtue is laziness, he wants
the unix morons to conjure up in their brains the following
proposition as true: “Resistant to work or exertion is a natural human
disposition and such disposition actually results behaviors being
economic”. This statement may be true, which means that human laziness
may be intuitively understood from evolution. However, this statement
is a proposition on all human beings, and is not some “virtue” that
can be applied to a group of people such as programers.

Demagogue Larry Wall is smart in creating a confusion combined with
wishful thinking. By making subtle statements like this, he semi-
intentionally confuses average programers to think that it is OK to be
not thorough, it is OK to be sloppy, it is OK to disparage computer
science. (like the incompetent unixers and perlers are)

Can you see the evil and its harm in not understanding things clearly?
This laziness quote by Wall is a tremendous damage to the computing
industry. It is a source among others that spurs much bad fashion
trends and fuckups in the industry. It is more damaging than any
single hack or virus. It is social brain-washing at work, like the
diamond company De Beers' tremendously successful sales slogan: “A
Diamond is Forever” or Apple's grammatically fantastic “Think
Different”.

The most fundamental explanation of why Larry Wall's sophistry are
damaging to society is simply this: What he said is not true and they
are widely spread and conceived as worthwhile. This is a form of mis-
information. This is a manifestation of Love without Knowledge as i
expounded before, with subtle but disastrous consequences (already).

[DISCLAIMER: all mentions of real persons are opinion only.]


This post is archived at:
http://xahlee.org/UnixResource_dir/writ/perl_laziness.html

  Xah
  [EMAIL PROTECTED]
∑ http://xahlee.org/

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

Re: combination function in python

2007-04-15 Thread Mark Dickinson
On Apr 15, 8:37 am, Jussi Piitulainen <[EMAIL PROTECTED]>
wrote:
> def choose(n, k):
>if 0 <= k <= n:
>ntok = 1
>ktok = 1
>for t in xrange(1, min(k, n - k) + 1):
>   ntok *= n
>   ktok *= t
>   n -= 1
>return ntok // ktok
>else:
>return 0

It might be even better to do the divisions as you go, rather than
leaving
them all to the end.  That way the intermediate results stay smaller.
So
(leaving out the bounds checking) one just does:

def choose(n, k):
ntok = 1
for t in xrange(min(k, n-k)):
ntok = ntok*(n-t)//(t+1)
return ntok

Mark

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


Re: how to strip the domain name in python?

2007-04-15 Thread Marko . Cain . 23
On Apr 14, 10:36 am, [EMAIL PROTECTED] wrote:
> On Apr 14, 12:02 am, Michael Bentley <[EMAIL PROTECTED]>
> wrote:
>
>
>
> > On Apr 13, 2007, at 11:49 PM, [EMAIL PROTECTED] wrote:
>
> > > Hi,
>
> > > I have a list of url names like this, and I am trying to strip out the
> > > domain name using the following code:
>
> > >http://www.cnn.com
> > >www.yahoo.com
> > >http://www.ebay.co.uk
>
> > > pattern = re.compile("http:(.*)\.(.*)", re.S)
> > > match = re.findall(pattern, line)
>
> > > if (match):
> > > s1, s2 = match[0]
>
> > > print s2
>
> > > but none of the site matched, can you please tell me what am i
> > > missing?
>
> > change re.compile("http:(.*)\.(.*)", re.S) to re.compile("http:\/
> > \/(.*)\.(.*)", re.S)
>
> Thanks. I try this:
>
> but when the 'line' ishttp://www.cnn.com, I get 's2' com,
> but i want 'cnn.com' (everything after the first '.'), how can I do
> that?
>
> pattern = re.compile("http:\/\/(.*)\.(.*)", re.S)
>
> match = re.findall(pattern, line)
>
> if (match):
>
> s1, s2 = match[0]
>
> print s2

Can anyone please help me with my problem?  I still can't solve it.

Basically, I want to strip out the text after the first '.' in url
address:

http://www.cnn.com -> cnn.com

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


Re: combination function in python

2007-04-15 Thread Anton Vredegoor
Jussi Piitulainen wrote:

>> There's probably even a really clever way to avoid that final
>> division, but I suspect that would cost more in time and memory than
>> it would save.

We're getting closer and closer to something I already posted a few 
times here. This implementation was unfortunate because I consistently 
used an uncommon name for it so people couldn't easily find it (mea 
culpa), and maybe also because it uses the despised reduce builtin.

def noverk(n,k):
 return reduce(lambda a,b: a*(n-b)/(b+1),xrange(k),1)

BTW I hereby give up the strange name for this and request a better name 
that everybody will use so there will be no confusion anymore. Maybe 
comb(n,k) ?

> Here's one non-clever one for integers n, k that uses n^k / k^k
> (falling powers) with the smaller of k and n - k as lower index:
> 
> def choose(n, k):
>if 0 <= k <= n:
>ntok = 1
>ktok = 1
>for t in xrange(1, min(k, n - k) + 1):
>   ntok *= n
>   ktok *= t
>   n -= 1
>return ntok // ktok
>else:
>return 0


Ha, my function uses smaller subproducts :-)

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


Re: That might be the case for more complex objects...

2007-04-15 Thread Steve Holden
James Stroud wrote:
> Bart Willems wrote:
>> Dennis Lee Bieber wrote:
[...]
>> Lists behave as described above, integers and floats don't.
>>
>> By the way, a classic language like C has features like this too; 
>> they're called pointers.
> 
> I think that after a += 1, a memory location with a 6 is created and now 
>   a points to that because += has assignment buried in it.

This is the difference between mutable and immutable types.

  >>> a = 5
  >>> b = a
  >>> a += 1
  >>> a
6
  >>> b
5
  >>> a = [1,2,3,4,5]
  >>> b = a
  >>> a += [6,7,8]
  >>> a
[1, 2, 3, 4, 5, 6, 7, 8]
  >>> b
[1, 2, 3, 4, 5, 6, 7, 8]
  >>>

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Recent Ramblings   http://holdenweb.blogspot.com

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


Re: how to strip the domain name in python?

2007-04-15 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Marko.Cain.23
wrote:

> On Apr 14, 10:36 am, [EMAIL PROTECTED] wrote:
>> On Apr 14, 12:02 am, Michael Bentley <[EMAIL PROTECTED]>
>> wrote:
>>
>>
>>
>> > On Apr 13, 2007, at 11:49 PM, [EMAIL PROTECTED] wrote:
>>
>> > > Hi,
>>
>> > > I have a list of url names like this, and I am trying to strip out the
>> > > domain name using the following code:
>>
>> > >http://www.cnn.com
>> > >www.yahoo.com
>> > >http://www.ebay.co.uk
>>
>> > > pattern = re.compile("http:(.*)\.(.*)", re.S)
>> > > match = re.findall(pattern, line)
>>
>> > > if (match):
>> > > s1, s2 = match[0]
>>
>> > > print s2
>>
>> > > but none of the site matched, can you please tell me what am i
>> > > missing?
>>
>> > change re.compile("http:(.*)\.(.*)", re.S) to re.compile("http:\/
>> > \/(.*)\.(.*)", re.S)
>>
>> Thanks. I try this:
>>
>> but when the 'line' ishttp://www.cnn.com, I get 's2' com,
>> but i want 'cnn.com' (everything after the first '.'), how can I do
>> that?
>>
>> pattern = re.compile("http:\/\/(.*)\.(.*)", re.S)
>>
>> match = re.findall(pattern, line)
>>
>> if (match):
>>
>> s1, s2 = match[0]
>>
>> print s2
> 
> Can anyone please help me with my problem?  I still can't solve it.
> 
> Basically, I want to strip out the text after the first '.' in url
> address:
> 
> http://www.cnn.com -> cnn.com

from urlparse import urlsplit

def get_domain(url):
net_location = urlsplit(url)[1]
return '.'.join(net_location.rsplit('.', 2)[-2:])

def main():
print get_domain('http://www.cnn.com')

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reading from sys.stdin

2007-04-15 Thread Steve Holden
7stud wrote:
> On Apr 14, 7:43 am, Steve Holden <[EMAIL PROTECTED]> wrote:
>> 7stud wrote:
>>> On Apr 13, 6:20 am, Michael Hoffman <[EMAIL PROTECTED]> wrote:
>> [...]
>>
>>> But if you hit return on a blank line, there is no error.  In other
>>> words, will stop on a blank line and not return EOFError.
>>> Anyway, it seems everyone is saying that when you iterate over a file,
>>> the whole file is first read into memory.  Therefore iterating over
>>> sys.stdin is consistent: you have to type Ctrl+D to signal EOF before
>>> the iteration can start.  Is that about right?
>> No. The file content is usually buffered, but the buffering doesn't
>> necessarily include the whole content of the file.
>>
>> If you are iterating over the file the correct way to access the next
>> line is to call the file's  .next() method, as I indicated before.
>>
>> If you are reading lines the appropriate way is to use readline().
>>
>> And, as you have already seen an error message telling you, mixing the
>> two types is unlikely to give you usable results.
>>
> Does iterating over stdin work the same way?  If one were to type in
> enough lines to fill the buffer would iteration begin before entering
> EOF with Ctrl+D?
> 
Why don't you try it and tell me? That's what the interactive 
interpreter is for.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Recent Ramblings   http://holdenweb.blogspot.com

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


Re: proposed PEP: iterator splicing

2007-04-15 Thread Georg Brandl
Steven Bethard schrieb:
> Paul Rubin wrote:
>> The boilerplate
>> 
>> def some_gen():
>>...
>>for x in some_other_gen():
>>yield x
>>...
>> 
>> is so common (including the case where some_other_gen is the same as
>> some_gen, i.e. it's a recursive call) that I find myself wanting
>> a more direct way to express it:
>> 
>> def some_gen():
>>...
>>yield *some_other_gen()
>> 
>> comes to mind.  Less clutter, and avoids yet another temp variable
>> polluting the namespace.
>> 
>> Thoughts?
> 
> This has been brought up before and there was mixed support:
> 
> http://www.python.org/dev/summary/2006-01-16_2006-01-31/#yielding-from-a-sub-generator
> 
> My guess is that the only way it has any chance is if someone takes the 
> time to implement it and posts a full-fledged PEP to python-dev.

BTW, I've implemented a different feature, namely extended unpacking, such as

a, *b, c = range(10)

where I already had to add the concept of a ``starred'' expression.
If someone wants to do it, we can probably share some code.


Georg


-- 
Thus spake the Lord: Thou shalt indent with four spaces. No more, no less.
Four shall be the number of spaces thou shalt indent, and the number of thy
indenting shall be four. Eight shalt thou not indent, nor either indent thou
two, excepting that thou then proceed to four. Tabs are right out.

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


Re: how to strip the domain name in python?

2007-04-15 Thread Steven Howe




[EMAIL PROTECTED] wrote:

  On Apr 14, 10:36 am, [EMAIL PROTECTED] wrote:
  
  
On Apr 14, 12:02 am, Michael Bentley <[EMAIL PROTECTED]>
wrote:





  On Apr 13, 2007, at 11:49 PM, [EMAIL PROTECTED] wrote:
  


  
Hi,

  


  
I have a list of url names like this, and I am trying to strip out the
domain name using the following code:

  


  
http://www.cnn.com
www.yahoo.com
http://www.ebay.co.uk

  


  
pattern = re.compile("http:(.*)\.(.*)", re.S)
match = re.findall(pattern, line)

  


  
if (match):
s1, s2 = match[0]

  


  
print s2

  


  
but none of the site matched, can you please tell me what am i
missing?

  


  change re.compile("http:(.*)\.(.*)", re.S) to re.compile("http:\/
\/(.*)\.(.*)", re.S)
  

Thanks. I try this:

but when the 'line' ishttp://www.cnn.com, I get 's2' com,
but i want 'cnn.com' (everything after the first '.'), how can I do
that?

pattern = re.compile("http:\/\/(.*)\.(.*)", re.S)

match = re.findall(pattern, line)

if (match):

s1, s2 = match[0]

print s2

  
  
Can anyone please help me with my problem?  I still can't solve it.

Basically, I want to strip out the text after the first '.' in url
address:

http://www.cnn.com -> cnn.com

  

Generalized, you'll want to add some 'try' test to verify the not
returning just root domains ('com', 'edu', 'net' etc)

Start with spliting?
from string import split, find
url=''
url.split('//')
['http:', 'www.cnn.com']

site = url.split('//')[1:][0]
site ='www.cnn.com'

site.find('.')
3
site[site.find('.')+1:]
'cnn.com'
domain = site[site.find('.')+1:]

from string import split, find
def getDomain( url=''):
    site = url.split('//')[1:][0]
    domain = site[site.find('.')+1:]
    return domain



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

yield, curry, mix-in, new.function, global, closure, .... what will work?

2007-04-15 Thread ecir . hana
Dear list,

maybe I'm overlooking something obvious or this is not possible at all
or I don't know. Please, consider the following code:



## insert here anything you like

def changer():
change_i('changed_i')
change_j('changed_j')

def run(i='', j=''):

## insert here anything you like

return i, j

run() == 'changed_i', 'changed_j'



Let me explain: First, changer() is kind of templating language so it
should be written down in this form - however, it can change during
run-time as you like. Basically, it is just ordinary python code which
changes (should change) the local variables of another function,
run(). Oh, and it has to be *thread-safe*.

Here's what I tried and didn't work (maybe I just haven't tried hard
enough):
- pass i, j around: changer(i, j) and change_i(i, arg) - easiest, most
obvious solution - can't do it, certainly not during writing of the
code - have to preserve changer()'s form
- global variable - not thread-safe
- in run(), create dummy closure for changer() and call it -
new.function(blah, blah, blah, dummy.func_closure) - not thread safe,
i guess, and besides change_i() and change_j() would also need a such
a trick - I am not sure how to  alter the codeobject of changer()
- new.function(new.code(... - oh my, this won't work
- in run(), modify change_i() and change_j() so it actually yield-s
the changes, collect them here - something like: change_i.__call__  =
return yield ('changed_i', 'comes_from_changer_i()') - doesn't work,
of course
- update locals() - yes!! - no!! - doen't work, it's just a copy
- curry, mix-in, ... - hmm
- eval(blah, blah, locals()) - not safe, ugly - maybe? what do you
think?
- find out which file changer() is written in, which line it starts
and ends, read that file's section, parse, edit, append the needed
local variable's declarations, compile to changer_new() and changer =
changer_new - there has to be something better! :)

So, to wrap up, the question is: how can I pass a variable from one
function to another, without writing down function's argument during
coding, and still be thread-safe?

I can only hope you are still with me and not very confused

Thanks for any feedback!!

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


Re: Python Feature Request: Allow changing base of member indices to 1

2007-04-15 Thread Javier Bezos

> Here is a document giving good reasons for indexing to start at
> zero, as in Python.
> http://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html
> The author has done a bit:
> http://en.wikipedia.org/wiki/Dijkstra

Dijkstra's argument is obsolete, as it is based on
how array length was computed many years ago -- if
we have an array a = b..e, then the lenght of a
is e-b (half open range). Good at low level
programming.

But a quarter of a century after we know concepts
are much better than low level programming and
explicit computations -- if we have an array
a = b..e, then the length of a should be a.length()
(or a.length(b,e)), and it is independent of
arbitrary ranges, index bases, or even steps
(eg, {-4, -2, 0, 2, 4}).

Of course, the index base should be always the
same _by default_ (individual lists could require
another index base, and that's fine). Otherwise
it would a mess, as you said.

Javier
-
http://www.texytipografia.com 


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


Re: tuples, index method, Python's design

2007-04-15 Thread Rhamphoryncus
On Apr 15, 1:55 am, Paul Rubin  wrote:
> "Rhamphoryncus" <[EMAIL PROTECTED]> writes:
> > Indexing cost, memory efficiency, and canonical representation: pick
> > two.  You can't use a canonical representation (scalar values) without
> > some sort of costly search when indexing (O(log n) probably) or by
> > expanding to the worst-case size (UTF-32).  Python has taken the
> > approach of always providing efficient indexing (O(1)), but you can
> > compile it with either UTF-16 (better memory efficiency) or UTF-32
> > (canonical representation).
>
> I still don't get it.  UTF-16 is just a data compression scheme, right?
> I mean, s[17] isn't the 17th character of the (unicode) string regardless
> of which memory byte it happens to live at?  It could be that that accessing
> it takes more than constant time, but that's hidden by the implementation.
>
> So where does the invariant c==s[s.index(c)] fail, assuming s contains c?

On linux (UTF-32):
>>> c = u'\U0010'
>>> c
u'\U0010'
>>> list(c)
[u'\U0010']

On windows (UTF-32):
>>> c = u'\U0010'
>>> c
u'\U0010'
>>> list(c)
[u'\udbff', u'\udfff']

The unicode type's repr hides the distinction but you can see it with
list.  Your "single character" is actually two surrogate code points.
s[s.index(c)] would only give you the first surrogate character

--
Adam Olsen, aka Rhamphoryncus

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


Authenticating clients and servers

2007-04-15 Thread Chaz Ginger
I am writing a distributed server system using Python. I need to support
authentication and was wondering what approaches are available under
Python and what are the best practices.

Thanks in advance
Chaz
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Standardizing XML

2007-04-15 Thread ZeeGeek
On Apr 15, 7:08 am, Jan Danielsson <[EMAIL PROTECTED]> wrote:
> ZeeGeek wrote:
> > Is there a module for python to standardize XML?  Since MSN Live Space
> > doesn't use standard XML in the posts, I want to standardize them so
> > that I can use them elsewhere.
>
>Hmm... XML _is_ standardized. If it doesn't follow the specs, then
> it's not XML. If you want to make XML out of something which isn't XML,
> you'll probably have to be a little more specific about how this other
> format works.

Thanks for correcting me.  I worded it inproperly.  For example, in
the code returned by Live Space, they use  instead of  so
that Blogger will complain that this tag is not valid because it
doesn't have a closing tag.  Another example is that the contents of a
lot of the tag attributes like "color" and "size" are not surrounded
by quotes.

>
> --
> Kind regards,
> Jan Danielsson

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


Re: yield, curry, mix-in, new.function, global, closure, .... what will work?

2007-04-15 Thread Paul Rubin
[EMAIL PROTECTED] writes:
> Let me explain: First, changer() is kind of templating language so it
> should be written down in this form - however, it can change during
> run-time as you like. Basically, it is just ordinary python code which
> changes (should change) the local variables of another function,
> run(). Oh, and it has to be *thread-safe*.

That is total madness.  Just use a normal object or dictionary with a lock.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Standardizing XML

2007-04-15 Thread Jonathan Ballet
Le 15 Apr 2007 11:02:20 -0700,
"ZeeGeek" <[EMAIL PROTECTED]> a écrit :

> Thanks for correcting me.  I worded it inproperly.  For example, in
> the code returned by Live Space, they use  instead of  so
> that Blogger will complain that this tag is not valid because it
> doesn't have a closing tag.  Another example is that the contents of a
> lot of the tag attributes like "color" and "size" are not surrounded
> by quotes.

Maybe you can try BeautifulSoup module which aims to handle things like
that : http://www.crummy.com/software/BeautifulSoup/

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


Re: Standardizing XML

2007-04-15 Thread ZeD
ZeeGeek wrote:

> in the code returned by Live Space, they use  instead of  so
> that Blogger will complain that this tag is not valid because it
> doesn't have a closing tag.  Another example is that the contents of a
> lot of the tag attributes like "color" and "size" are not surrounded
> by quotes.

Are you sure it's xml? It sounds to me like "old" HTML

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


Re: Authenticating clients and servers

2007-04-15 Thread Thomas Krüger
Chaz Ginger schrieb:
> I am writing a distributed server system using Python. I need to support
> authentication and was wondering what approaches are available under
> Python and what are the best practices.

Well, there are many ways of client authentication. To narrow it down it
would be nice if your tell us something about the protocol you are
planning to use.

Many protocols support an additional SSL/TLS-Layers (e.g. HTTP ->
HTTPS). There you can use SSL certificate authentication. It may
berequired to set up a small CA, but done right it is pretty secure.

Thomas

-- 
sinature: http://nospam.nowire.org/signature_usenet.png
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is laziness a programer's virtue?

2007-04-15 Thread Dan Bensen
Xah Lee wrote:
> Laziness, Perl, and Larry Wall
> When the sorcerer Larry Wall said “The three chief virtues of a
> programmer are: Laziness, Impatience and Hubris”, he used the word
> “laziness” to loosely imply “natural disposition that results in being
> economic”.

Programming by definition is the process of automating repetitive 
actions to reduce the human effort required to perform them.  A good 
programmer faced with a hard problem always looks for ways to make 
his|her job easier by delegating work to a computer.  That's what Larry 
means.  Automation is MUCH more effective than repetition.

-- 
Dan
www.prairienet.org/~dsb/
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Authenticating clients and servers

2007-04-15 Thread Thomas Krüger
Thomas Krüger schrieb:
> Many protocols support an additional SSL/TLS-Layers (e.g. HTTP ->
> HTTPS). There you can use SSL certificate authentication. It may
> berequired to set up a small CA, but done right it is pretty secure.

I missed the best:
The Twisted framework has SSL authentication already implemented:
http://twistedmatrix.com/
But there also more lightweigt implementations like
httplib.HTTPSConnection (for clients) or pyopenssl

Thomas


-- 
sinature: http://nospam.nowire.org/signature_usenet.png
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tuples, index method, Python's design

2007-04-15 Thread Rhamphoryncus
On Apr 15, 8:56 am, Roel Schroeven <[EMAIL PROTECTED]>
wrote:
> Paul Rubin schreef:
>
> > "Rhamphoryncus" <[EMAIL PROTECTED]> writes:
> >> Indexing cost, memory efficiency, and canonical representation: pick
> >> two.  You can't use a canonical representation (scalar values) without
> >> some sort of costly search when indexing (O(log n) probably) or by
> >> expanding to the worst-case size (UTF-32).  Python has taken the
> >> approach of always providing efficient indexing (O(1)), but you can
> >> compile it with either UTF-16 (better memory efficiency) or UTF-32
> >> (canonical representation).
>
> > I still don't get it.  UTF-16 is just a data compression scheme, right?
> > I mean, s[17] isn't the 17th character of the (unicode) string regardless
> > of which memory byte it happens to live at?  It could be that that accessing
> > it takes more than constant time, but that's hidden by the implementation.
>
> > So where does the invariant c==s[s.index(c)] fail, assuming s contains c?
>
> I didn't get it either, but now I understand. Like you, I thought Python
> Unicode strings contain a canonical representation (in interface, not
> necessarily in implementation) but apparently that is not true; see
> Neil's post and the reference manual
> (http://docs.python.org/ref/types.html#l2h-22).
>
> A simple example on my Python installation, apparently compiled to use
> UTF-16 (sys.maxunicode == 65535):
>
>  >>> s = u'\u1d400'

You're confusing \u, which is followed by 4 digits, and \U, which is
followed by eight:
>>> list(u'\u1d400')
[u'\u1d40', u'0']
>>> list(u'\U0001d400')
[u'\U0001d400']  # UTF-32 output, sys.maxunicode == 1114111
[u'\ud835', u'\udc00']  # UTF-16 output, sys.maxunicode == 65535

--
Adam Olsen, aka Rhamphoryncus

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


Re: Authenticating clients and servers

2007-04-15 Thread Chaz Ginger
Thomas Krüger wrote:
> Chaz Ginger schrieb:
>> I am writing a distributed server system using Python. I need to support
>> authentication and was wondering what approaches are available under
>> Python and what are the best practices.
> 
> Well, there are many ways of client authentication. To narrow it down it
> would be nice if your tell us something about the protocol you are
> planning to use.
> 
> Many protocols support an additional SSL/TLS-Layers (e.g. HTTP ->
> HTTPS). There you can use SSL certificate authentication. It may
> berequired to set up a small CA, but done right it is pretty secure.
> 
> Thomas
> 
I am leaning toward using Kerberos via GSS, but I am willing to listen
to other ideas. I've played around with TLS but the problem is that
updating the .PEM files can be a pain. I was also thinking about X509,
and was wondering if anyone has experience with it.

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


Re: Calling private base methods

2007-04-15 Thread Duncan Booth
"Isaac Rodriguez" <[EMAIL PROTECTED]> wrote:

>> The fact that I had
>> to resort to this trick is a big indication of course that genuinely
>> private members (as opposed to a 'keep off' naming convention) are a bad
>> idea in general.
> 
> 
> The fact that you had to resort to this trick is a big indication that
> the library you were using is bad designed; it has nothing to do with
> private members being a bad idea. You were using a library which
> interface was in-complete (provided that you "genuinely" really needed
> to access the private member to do what you wanted to do).

I agree with that to a certain extent, but I've never found any situation 
where I gained any benefit because someone had made part of the 
implementation private, only ever found annoyance because someone had made 
something private which shouldn't have been.

The problem is that when people design interfaces they don't (and 
cannot) know all the situations in which the code is going to be used in 
the future. Clearly separating the published interface from the 
implementation details is a good thing, but physically preventing access to 
those details is IMHO a bad thing.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Method calls and stack consumption

2007-04-15 Thread Martin Manns
On Sun, 15 Apr 2007 07:27:25 +0200
Peter Otten <[EMAIL PROTECTED]> wrote:

> Martin Manns wrote:
> 
> > Calling methods of other object instances seems quite expensive on
> > the stack (see example below). Is there a better way of traversing
> > through methods of instances that are connected in a cyclic graph?
> > (The real program's graph contains multiple successors in lists.)

> a = a.a
> while True:
> a = a()
> 
> That's how you can do it if your real program is similar enough to the
> example...

Thanks for pointing out the oversimplified nature of the original
example.I hope that the following one clarifies the problem.

(I do not know, what has to be stored on the stack, but it should not be
that much, because all recursion calls originate from inside the return
statement.)


from random import randint,seed
import sys
seed()
sys.setrecursionlimit(100)

class Node(object):
def __init__(self):
self.state = abs(randint(1,1000))
def GetDepState(self):
return self.state + max(s.GetDepState() for s in S[self])

class ConditionalBreakNode(Node):
def GetDepState(self):
if randint(1,5) > 1:
return Node.GetDepState(self)
else:
return self.state

S = {}
nodes = [Node()]

def AppendNode(curr_node, depth=1):
global nodes
r = randint(1,30)
if r >= depth:
for i in xrange(randint(1,3)):
newnode = Node()
nodes += [newnode]
try: S[curr_node] += [newnode]
except: S[curr_node] = [newnode]
AppendNode(newnode, depth+1)
else:
newnode = ConditionalBreakNode()
nodes += [newnode]
try: S[curr_node] += [newnode]
except: S[curr_node] = [newnode]
S[newnode] = [nodes[0]]

AppendNode(nodes[0])
print len(nodes)
print nodes[0].GetDepState()

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


Re: combination function in python

2007-04-15 Thread Jussi Piitulainen
Mark Dickinson writes:
> Jussi Piitulainen wrote:
>
> > def choose(n, k):
> >if 0 <= k <= n:
> >ntok = 1
> >ktok = 1
> >for t in xrange(1, min(k, n - k) + 1):
> >   ntok *= n
> >   ktok *= t
> >   n -= 1
> >return ntok // ktok
> >else:
> >return 0
> 
> It might be even better to do the divisions as you go, rather than
> leaving them all to the end.  That way the intermediate results
> stay smaller.  So (leaving out the bounds checking) one just does:
> 
> def choose(n, k):
> ntok = 1
> for t in xrange(min(k, n-k)):
> ntok = ntok*(n-t)//(t+1)
> return ntok

Yes, that's what I once saw done. Thanks. Its correctness is more
subtle, so I prefer to add the parentheses below to emphasise that
the product has to be computed before the division. I also renamed
the variable to p: it's no longer n^k (falling). And I put the
bounds back in.

def choose(n, k):
if 0 <= k <= n:
p = 1
for t in xrange(min(k, n - k)):
p = (p * (n - t)) // (t + 1)
return p
else:
return 0
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting started with python

2007-04-15 Thread Gabriel Genellina
En Sun, 15 Apr 2007 10:46:54 -0300, Army1987 <[EMAIL PROTECTED]> escribió:

> "Paddy" <[EMAIL PROTECTED]> ha scritto nel messaggio
> news:[EMAIL PROTECTED]
>
>> On a different tack, from:
>> http://tickletux.wordpress.com/2007/01/24/using-fizzbuzz-to-find-developers-who-grok-coding/
>> It seems you need to learn how to write a Fizz-Buzz
>> program to get a job now-a-days :-)
>
> Something less idiotic? I took longer to type a program to do that than  
> to
> figure out how to do that.

We've used it as part of a test a few weeks ago. You'd be surprised on how  
many guys couldn't write anything remotely sensible.

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


Re: tuples, index method, Python's design

2007-04-15 Thread Paul Rubin
Roel Schroeven <[EMAIL PROTECTED]> writes:
> In this case s[0] is not the full Unicode scalar, but instead just the
> first part of the surrogate pair consisting of 0x1D40 (in s[0]) and
> 0x (in s[1]).

Agggh.  After much head scratching I think I now understand what
you are saying.  This appears to me to be absolutely nuts.  What is
the purpose of having a unicode string type, if its sequence elements
are not guaranteed to be the unicode characters in the string?  Might
as well use byte strings for everything.

Come to think of it, I don't understand why we have this plethora of
encodings like utf-16.  utf-8 I can sort of understand on pragmatic
grounds, but aside from that I'd think UCS-4 should be used for everything,
and when a space-saving compressed representation is desired, then use
a general purpose data compression algorithm such as gzip.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is laziness a programer's virtue?

2007-04-15 Thread Daniel Gee
You fail to understand the difference between passive laziness and
active laziness. Passive laziness is what most people have. It's
active laziness that is the virtue. It's the desire to go out and /
make sure/ that you can be lazy in the future by spending just a
little time writing a script now. It's thinking about time
economically and acting on it.

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


Re: is laziness a programer's virtue?

2007-04-15 Thread Kay Schluehr
On Apr 15, 6:25 pm, "Xah Lee" <[EMAIL PROTECTED]> wrote:
> Laziness, Perl, and Larry Wall
>
> Xah Lee, 20021124
>
> In the unix community there's quite a large confusion and wishful
> thinking about the word laziness. In this post, i'd like to make some
> clarifications.
>
> American Heritage Dictionary third edition defines laziness as:
> “Resistant to work or exertion; disposed to idleness.”
>
> When the sorcerer Larry Wall said “The three chief virtues of a
> programmer are: Laziness, Impatience and Hubris”, he used the word
> “laziness” to loosely imply “natural disposition that results in being
> economic”. As you can see now, “Resistant to work or exertion” is
> clearly not positive and not a virtue, but “natural disposition that
> results in economy” is a good thing if true.
>
> When Larry Wall said one of programer's virtue is laziness, he wants
> the unix morons to conjure up in their brains the following
> proposition as true: “Resistant to work or exertion is a natural human
> disposition and such disposition actually results behaviors being
> economic”. This statement may be true, which means that human laziness
> may be intuitively understood from evolution. However, this statement
> is a proposition on all human beings, and is not some “virtue” that
> can be applied to a group of people such as programers.
>
> Demagogue Larry Wall is smart in creating a confusion combined with
> wishful thinking. By making subtle statements like this, he semi-
> intentionally confuses average programers to think that it is OK to be
> not thorough, it is OK to be sloppy, it is OK to disparage computer
> science. (like the incompetent unixers and perlers are)
>
> Can you see the evil and its harm in not understanding things clearly?
> This laziness quote by Wall is a tremendous damage to the computing
> industry. It is a source among others that spurs much bad fashion
> trends and fuckups in the industry. It is more damaging than any
> single hack or virus. It is social brain-washing at work, like the
> diamond company De Beers' tremendously successful sales slogan: “A
> Diamond is Forever” or Apple's grammatically fantastic “Think
> Different”.
>
> The most fundamental explanation of why Larry Wall's sophistry are
> damaging to society is simply this: What he said is not true and they
> are widely spread and conceived as worthwhile. This is a form of mis-
> information. This is a manifestation of Love without Knowledge as i
> expounded before, with subtle but disastrous consequences (already).
>
> [DISCLAIMER: all mentions of real persons are opinion only.]
>
> 
> This post is archived 
> at:http://xahlee.org/UnixResource_dir/writ/perl_laziness.html
>
>   Xah
>   [EMAIL PROTECTED]
> ∑http://xahlee.org/

I like Larry Wall, despite being not a Perl programmer, and when he
secretly subverts the american, protestant working ethos I like him
even better :)

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

Re: Calling private base methods

2007-04-15 Thread Paul Rubin
Duncan Booth <[EMAIL PROTECTED]> writes:
> The problem is that when people design interfaces they don't (and 
> cannot) know all the situations in which the code is going to be used in 
> the future. Clearly separating the published interface from the 
> implementation details is a good thing, but physically preventing access to 
> those details is IMHO a bad thing.

The idea is to make the implementation details independent from the
calling program.  For example, I'm using a library now that does
something highly CPU intensive.  To speed up the application, I may
put the library on a completely separate computer, so that the
published API exposed to the caller becomes a wrapper for a network
client, and all those library implementation details are on the other
machine.  That's the ultimate in physical access prevention, there's
good reason to do it, and it completely breaks if the calling program
is using anything except the published API.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: combination function in python

2007-04-15 Thread bearophileHUGS
Mark Dickinson:
> def choose(n, k):
> ntok = 1
> for t in xrange(min(k, n-k)):
> ntok = ntok*(n-t)//(t+1)
> return ntok

With few tests, it seems this is faster than the version by Jussi only
with quite big n,k.

(Another test to be added, is the assert n>0 of my original version
(testing that n,k seem useful too)).

Bye,
bearophile

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


Re: is laziness a programer's virtue?

2007-04-15 Thread John Thingstad
On Sun, 15 Apr 2007 18:25:19 +0200, Xah Lee <[EMAIL PROTECTED]> wrote:

> Laziness, Perl, and Larry Wall
>
> Xah Lee, 20021124
>
> In the unix community there's quite a large confusion and wishful
> thinking about the word laziness. In this post, i'd like to make some
> clarifications.
>
> American Heritage Dictionary third edition defines laziness as:
> “Resistant to work or exertion; disposed to idleness.”
>

In this context I think you can safely take it to mean:
Don't work hard, work smart.

Avoid repetitious work. If somthing seems to elaborate find a more  
efficient way.

In a course I took on verifiable programming I found working with Hoare  
logic
extremely tedious. So I started using rewriting loops as recursive  
procedures and
using induction instead. It took about a quarter of the time as the  
invariant of a loop
fell out rather naturally this way. I failed the course, but when I took  
the course
over again a year later I noticed that the book had been rewritten and now  
half the book
was dedicated to Generator Induction. (Seems the professor noticed I  
failed in a interesting
way and figured out it was not so stupid after all.) Naturally I had no  
problems the second time ;)

This is just one example but it should convey the idea.

-- 
Using Opera's revolutionary e-mail client: http://www.opera.com/mail/
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python Feature Request: (?) Group all file-directory-related stdlib functions in one place

2007-04-15 Thread Nikita the Spider
In article <[EMAIL PROTECTED]>,
 "Martin v. Löwis" <[EMAIL PROTECTED]> wrote:

> > Currently file-directory-related functionality in the Python standard
> > library is scattered among various modules such as shutil, os,
> > dircache etc. So I request that the functions be gathered and
> > consolidated at one place. Some may need renaming to avoid conflicts
> > or for clarification.
> > 
> 
> Please see PEP 355.

Thanks for bringing this to my attention; I was not aware of this PEP. 
The organization of the stdlib's file- and path-related functions gives 
me headaches so I'd like to see it change. But note that GvR has 
pronounced that PEP 355 is dead:

http://mail.python.org/pipermail/python-dev/2006-September/069087.html

-- 
Philip
http://NikitaTheSpider.com/
Whole-site HTML validation, link checking and more
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: reading from sys.stdin

2007-04-15 Thread 7stud
On Apr 15, 10:59 am, Steve Holden <[EMAIL PROTECTED]> wrote:
> 7stud wrote:
> > On Apr 14, 7:43 am, Steve Holden <[EMAIL PROTECTED]> wrote:
> >> 7stud wrote:
> >>> On Apr 13, 6:20 am, Michael Hoffman <[EMAIL PROTECTED]> wrote:
> >> [...]
>
> >>> But if you hit return on a blank line, there is no error.  In other
> >>> words, will stop on a blank line and not return EOFError.
> >>> Anyway, it seems everyone is saying that when you iterate over a file,
> >>> the whole file is first read into memory.  Therefore iterating over
> >>> sys.stdin is consistent: you have to type Ctrl+D to signal EOF before
> >>> the iteration can start.  Is that about right?
> >> No. The file content is usually buffered, but the buffering doesn't
> >> necessarily include the whole content of the file.
>
> >> If you are iterating over the file the correct way to access the next
> >> line is to call the file's  .next() method, as I indicated before.
>
> >> If you are reading lines the appropriate way is to use readline().
>
> >> And, as you have already seen an error message telling you, mixing the
> >> two types is unlikely to give you usable results.
>
> > Does iterating over stdin work the same way?  If one were to type in
> > enough lines to fill the buffer would iteration begin before entering
> > EOF with Ctrl+D?
>
> Why don't you try it and tell me? That's what the interactive
> interpreter is for.
>
> regards
>   Steve
> --
> Steve Holden   +44 150 684 7255  +1 800 494 3119
> Holden Web LLC/Ltd  http://www.holdenweb.com
> Skype: holdenwebhttp://del.icio.us/steve.holden
> Recent Ramblings  http://holdenweb.blogspot.com

I just typed in 700 lines of text, and the iteration hasn't begun
yet.  Should I keep going?

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


Re: is laziness a programer's virtue?

2007-04-15 Thread Xah Lee
Dear Ken,

I want to thank you for your spirit in supporting and leading the lisp
community, in spreading lisp the language both in what you have done
technically as well as evangelization, as well as the love and
knowledge attitude towards newsgroup communities in general, in part
thru your numerous replies to my posts in the past years. (as opposed
to, the motherfucking pack of driveling and fuckface ignoramuses that
are predominate personalities in newsgroups, including some of the
fucking asshole intolerant bigwigs in the lisp newsgroup who think
themselves as the holder of justice and goodness (which has
contributed significantly to the stagnation of lisp).)

Thank you.

For those reading this, i also want to mention, that although i think
Perl is a motherfucking language on earth, and its leader and
“inventor” Larry Wall has done massive damage to the computing world,
but Perl the community is in fact very tolerant in general (which is
to Larry's credit), when compared to the motherfucking Pythoners (who
knew SHIT) as well as many of the self-appointed lisp bigwig
characters.

[disclaimer: my statement about Larry Wall is opinion only.]

With Knowledge, and, Love.

  Xah
  [EMAIL PROTECTED]
∑ http://xahlee.org/

On Apr 15, 10:36 am, Ken Tilton <[EMAIL PROTECTED]> wrote:
> XahLeewrote:
> > Laziness, Perl, and Larry Wall
>
> >XahLee, 20021124
>
> > In the unix community there's quite a large confusion and wishful
> > thinking about the word laziness. In this post, i'd like to make some
> > clarifications.
>
> > American Heritage Dictionary third edition defines laziness as:
> > “Resistant to work or exertion; disposed to idleness.”
>
> > When the sorcerer Larry Wall said “The three chief virtues of a
> > programmer are: Laziness, Impatience and Hubris”, he used the word
> > “laziness” to loosely imply “natural disposition that results in being
> > economic”. As you can see now, “Resistant to work or exertion” is
> > clearly not positive and not a virtue, but “natural disposition that
> > results in economy” is a good thing if true.
>
> > When Larry Wall said one of programer's virtue is laziness, he wants
> > the unix morons to conjure up in their brains the following
> > proposition as true: “Resistant to work or exertion is a natural human
> > disposition and such disposition actually results behaviors being
> > economic”. This statement may be true, which means that human laziness
> > may be intuitively understood from evolution. However, this statement
> > is a proposition on all human beings, and is not some “virtue” that
> > can be applied to a group of people such as programers.
>
> Xah, you are losing your sense of humor. Wall listed the usually
> pejorative "lazy" as a virtue simply to grab the reader, make them
> think, and simply to entertain better. Surely The GreatXahunderstands
> the virtue of flamboyant writing and does not want every word yanked
> from context and slid under the microscope for dissection.
>
> kzo

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

Re: Making a tree out of a 2 column list

2007-04-15 Thread Sebastian Bassi
On 4/15/07, Peter Otten <[EMAIL PROTECTED]> wrote:
> Depending on your input data you may need to add some cycle detection.
> For example, try it with
> tree_path(1, {1:[2], 2:[1]}, [])

I guess this should make the program enter into a endless loop. But
the data won't have such a redundancy, because it was taken from a
philogenetic tree.

Best,
SB.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is laziness a programer's virtue?

2007-04-15 Thread Jim Ford
Xah Lee wrote:
> Laziness, Perl, and Larry Wall
> 
> Xah Lee, 20021124
> 
> In the unix community there's quite a large confusion and wishful
> thinking about the word laziness. In this post, i'd like to make some
> clarifications.

Years ago I used to work with someone who used to say 'I'm a lazy person 
- I like to do things the easy way!'. I guess this is what Larry Wall means.

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


Qt4 in ubuntu

2007-04-15 Thread Marcpp
Is possible install Qt4 pyqt4 under kubuntu?
Few times ago i tried to run pyqt in ubuntu (gnome) but i can't
do it.

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


Re: Python Feature Request: Allow changing base of member indices to 1

2007-04-15 Thread Paddy
On Apr 15, 6:42 pm, "Javier Bezos" <[EMAIL PROTECTED]> wrote:
> > Here is a document giving good reasons for indexing to start at
> > zero, as in Python.
> >http://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html
> > The author has done a bit:
> >http://en.wikipedia.org/wiki/Dijkstra
>
> Dijkstra's argument is obsolete, as it is based on
> how array length was computed many years ago -- if
> we have an array a = b..e, then the lenght of a
> is e-b (half open range). Good at low level
> programming.
>
> But a quarter of a century after we know concepts
> are much better than low level programming and
> explicit computations -- if we have an array
> a = b..e, then the length of a should be a.length()
> (or a.length(b,e)), and it is independent of
> arbitrary ranges, index bases, or even steps
> (eg, {-4, -2, 0, 2, 4}).
>
> Of course, the index base should be always the
> same _by default_ (individual lists could require
> another index base, and that's fine). Otherwise
> it would a mess, as you said.
>
> Javier
> -http://www.texytipografia.com

Hi Javier,
You seem to have missed out array *indexing*
in your argument, or is array indexing obsolete?

- Paddy.

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


Re: combination function in python

2007-04-15 Thread [EMAIL PROTECTED]
On Apr 15, 11:34�am, Anton Vredegoor <[EMAIL PROTECTED]>
wrote:
> Jussi Piitulainen wrote:
> >> There's probably even a really clever way to avoid that final
> >> division, but I suspect that would cost more in time and memory than
> >> it would save.
>
> We're getting closer and closer to something I already posted a few
> times here. This implementation was unfortunate because I consistently
> used an uncommon name for it so people couldn't easily find it

But then, who's looking for it?

> (mea culpa), and maybe also because it uses the despised reduce builtin.
>
> def noverk(n,k):
> � � �return reduce(lambda a,b: a*(n-b)/(b+1),xrange(k),1)
>
> BTW I hereby give up the strange name for this and request a better name
> that everybody will use so there will be no confusion anymore. Maybe
> comb(n,k) ?

No, that name's already used by gmpy. And a single
function doesn't replace all of gmpy's other
functionality, many of which are needed in the
same applications where comb() is used, so there's
really no need for your function.

Your time is better spent applying the tools provided
by gmpy rather than trying to re-invent the wheel.

>
> > Here's one non-clever one for integers n, k that uses n^k / k^k
> > (falling powers) with the smaller of k and n - k as lower index:
>
> > def choose(n, k):
> > � �if 0 <= k <= n:
> > � � � �ntok = 1
> > � � � �ktok = 1
> > � � � �for t in xrange(1, min(k, n - k) + 1):
> > � � � � � ntok *= n
> > � � � � � ktok *= t
> > � � � � � n -= 1
> > � � � �return ntok // ktok
> > � �else:
> > � � � �return 0
>
> Ha, my function uses smaller subproducts :-)
>
> A.


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

Re: reading from sys.stdin

2007-04-15 Thread Gabriel Genellina
En Sun, 15 Apr 2007 16:51:12 -0300, 7stud <[EMAIL PROTECTED]>  
escribió:

> I just typed in 700 lines of text, and the iteration hasn't begun
> yet.  Should I keep going?

How much text each line? Python uses an 8K buffer.

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


Re: is laziness a programer's virtue?

2007-04-15 Thread Claudio Grondi
Xah Lee wrote:
> [SOME FURTHER TROLLING DISTRIBUTED TO MULTIPLE NEWSGROUPS]

For those who are relatively new here in comp.lang.python and not aware 
of the troll:

It seems, that Xah still haven't learned from the impact of past abuse 
reports on his Internet access and tries again to pollute Usenet after a 
longer time of inactivity.

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


Re: Qt4 in ubuntu

2007-04-15 Thread Diez B. Roggisch
Marcpp schrieb:
> Is possible install Qt4 pyqt4 under kubuntu?
> Few times ago i tried to run pyqt in ubuntu (gnome) but i can't
> do it.

It's certainly possible. On ubuntu as well as on kubuntu. You can 
install all KDE and Qt stuff on ubuntu as well.

But unless you are more specific what your actual problems were, you 
can't better help.

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


Re: combination function in python

2007-04-15 Thread Mark Dickinson
On Apr 15, 3:33 pm, [EMAIL PROTECTED] wrote:
> With few tests, it seems this is faster than the version by Jussi only
> with quite big n,k.
>

True---and for large n and k it's difficult to imagine any real-world
applications that wouldn't be better served by using the lngamma
function instead.  That is, the natural log of n choose k can be
computed much more quickly as

lngamma(n+1) - lngamma(k+1) - lngamma(n-k+1)

I assume that lngamma is implemented somewhere in either numpy or
scipy, but right now I can't find it...

Mark

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


Re: split and regexp on textfile

2007-04-15 Thread Gabriel Genellina
En Fri, 13 Apr 2007 07:08:05 -0300, Flyzone <[EMAIL PROTECTED]>  
escribió:

> A little question: the pat.split can split without delete the date?

No, but instead of reading the whole file and splitting on dates, you  
could iterate over the file and detect block endings:

def split_on_dates(ftoparse):
   block = None
   for line in ftoparse:
 if fancy_date_regexp.match(line):
   # a new block begins, yield the previous one
   if block is not None:
 yield current_date, block
   current_date = line
   block = []
 else:
   # accumulate lines for current block
   block.append(line)
   # don't forget the last block
   if block is not None:
 yield current_date, block

for date, block in split_on_dates(ftoparse):
   # process block

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


Re: reading from sys.stdin

2007-04-15 Thread Diez B. Roggisch
>> Steve Holden   +44 150 684 7255  +1 800 494 3119
>> Holden Web LLC/Ltd  http://www.holdenweb.com
>> Skype: holdenwebhttp://del.icio.us/steve.holden
>> Recent Ramblings  http://holdenweb.blogspot.com
> 
> I just typed in 700 lines of text, and the iteration hasn't begun
> yet.  Should I keep going?
> 

Well, I'm not sure how much of a programmer you are if you don't get the 
idea of writing a _program_ to do the typing

 a.py ---
import sys

counter = 0
try:
 while True:
 s = str(counter) + '\n'
 counter += len(s)
 sys.stdout.write(s)
except IOError:
 sys.stderr.write(s)


--- b.py 

import sys

lst = []
for line in sys.stdin:
 lst.append(line)
 break

print lst



-

Besides that, a little bit of logic thinking should make clear that 
having to wait till EOF won't work too much for piping programs that 
produce continously output with possibly terabytes of data. Even under 
modern memory constraints...


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


Re: Python Feature Request: Allow changing base of member indices to 1

2007-04-15 Thread Beliavsky
On Apr 14, 10:55 am, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:



> The FORTRAN family had started as 1-based (F95, and Ada, now allow
> for each array to have its own "base" => x : array (-10..10) of float).

Fortran has allowed a user-specified base since at least the 1977
standard -- see for example 
http://www.umiacs.umd.edu/~jhu/DOCS/SP/docs/essl/essl159.html
.

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


Re: Calling private base methods

2007-04-15 Thread Diez B. Roggisch
Paul Rubin schrieb:
> Duncan Booth <[EMAIL PROTECTED]> writes:
>> The problem is that when people design interfaces they don't (and 
>> cannot) know all the situations in which the code is going to be used in 
>> the future. Clearly separating the published interface from the 
>> implementation details is a good thing, but physically preventing access to 
>> those details is IMHO a bad thing.
> 
> The idea is to make the implementation details independent from the
> calling program.  For example, I'm using a library now that does
> something highly CPU intensive.  To speed up the application, I may
> put the library on a completely separate computer, so that the
> published API exposed to the caller becomes a wrapper for a network
> client, and all those library implementation details are on the other
> machine.  That's the ultimate in physical access prevention, there's
> good reason to do it, and it completely breaks if the calling program
> is using anything except the published API.

So what? This will happen under under circumstances as well. Think of an 
interface returning None in an earlier version, then [] to indicate an 
empty result-set.

the point is that privacy is good to indicate that "you shouldn't mess 
with this unless you know what you do, which includes not to use new 
versions of the library."

I totally agree with Duncan that I've been in plenty situations where 
exploiting inner workings of some 3rd-party-code made my programming 
easier, only of course when nothing else helped.

After all, that's what duck-typing is about. There is no official 
interface declaration, just an implicit protocol. And "private" methods 
or members are part of that protocol as well.

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


Re: combination function in python

2007-04-15 Thread Anton Vredegoor
[EMAIL PROTECTED] wrote:

>> We're getting closer and closer to something I already posted a few
>> times here. This implementation was unfortunate because I consistently
>> used an uncommon name for it so people couldn't easily find it
> 
> But then, who's looking for it?

The OP was trying to find it in the docs, assuming it was some kind of 
builtin function. I can see the logic of that and I can also see the 
logic of including some other smallish functions like for example fac. 
Failing that, the next recourse would be the Internet, or a Usenet 
search but that would imply well named Usenet posts and function names.

>> (mea culpa), and maybe also because it uses the despised reduce builtin.
>>
>> def noverk(n,k):
>> � � �return reduce(lambda a,b: a*(n-b)/(b+1),xrange(k),1)

This is a rather concise function which has the added advantage that it 
returns 0 when k>n.

>> BTW I hereby give up the strange name for this and request a better name
>> that everybody will use so there will be no confusion anymore. Maybe
>> comb(n,k) ?
> 
> No, that name's already used by gmpy. And a single
> function doesn't replace all of gmpy's other
> functionality, many of which are needed in the
> same applications where comb() is used, so there's
> really no need for your function.

Actually, by proposing comb I am *honoring* gmpy and I'm also complying 
with it. In Python we use namespaces to differentiate between such 
things. You might want to read the documentation about it some time.

> Your time is better spent applying the tools provided
> by gmpy rather than trying to re-invent the wheel.

Please let me be the judge of how to spend my time. In this case it 
seems rather unjustified to introduce dependencies on external modules 
when only a few functions are needed. Since I'm also interested in the 
functions themselves -in this case- I'd rather have a few lines of code 
in my source than importing an optimized code library. There *are* 
situations where such things are completely justified, but I don't think 
this is one of them. You could take it up with the gmpy author and 
induce him to get gmpy included in the standard distro if you are so 
inclined.

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

Re: is laziness a programer's virtue?

2007-04-15 Thread James Stroud
Xah Lee wrote:
> Laziness, Perl, and Larry Wall
> 
> Xah Lee, 20021124
> 
> In the unix community there's quite a large confusion and wishful
> thinking about the word laziness. In this post, i'd like to make some
> clarifications.
> 
> American Heritage Dictionary third edition defines laziness as:
> “Resistant to work or exertion; disposed to idleness.”
> 
> When the sorcerer Larry Wall said “The three chief virtues of a
> programmer are: Laziness, Impatience and Hubris”, he used the word
> “laziness” to loosely imply “natural disposition that results in being
> economic”. As you can see now, “Resistant to work or exertion” is
> clearly not positive and not a virtue, but “natural disposition that
> results in economy” is a good thing if true.
> 
> When Larry Wall said one of programer's virtue is laziness, he wants
> the unix morons to conjure up in their brains the following
> proposition as true: “Resistant to work or exertion is a natural human
> disposition and such disposition actually results behaviors being
> economic”. This statement may be true, which means that human laziness
> may be intuitively understood from evolution. However, this statement
> is a proposition on all human beings, and is not some “virtue” that
> can be applied to a group of people such as programers.
> 
> Demagogue Larry Wall is smart in creating a confusion combined with
> wishful thinking. By making subtle statements like this, he semi-
> intentionally confuses average programers to think that it is OK to be
> not thorough, it is OK to be sloppy, it is OK to disparage computer
> science. (like the incompetent unixers and perlers are)
> 
> Can you see the evil and its harm in not understanding things clearly?
> This laziness quote by Wall is a tremendous damage to the computing
> industry. It is a source among others that spurs much bad fashion
> trends and fuckups in the industry. It is more damaging than any
> single hack or virus. It is social brain-washing at work, like the
> diamond company De Beers' tremendously successful sales slogan: “A
> Diamond is Forever” or Apple's grammatically fantastic “Think
> Different”.
> 
> The most fundamental explanation of why Larry Wall's sophistry are
> damaging to society is simply this: What he said is not true and they
> are widely spread and conceived as worthwhile. This is a form of mis-
> information. This is a manifestation of Love without Knowledge as i
> expounded before, with subtle but disastrous consequences (already).
> 
> [DISCLAIMER: all mentions of real persons are opinion only.]
> 
> 
> This post is archived at:
> http://xahlee.org/UnixResource_dir/writ/perl_laziness.html
> 
>   Xah
>   [EMAIL PROTECTED]
> ∑ http://xahlee.org/
> 

Laziness is re-posting something dated 2002.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: how to strip the domain name in python?

2007-04-15 Thread Marko . Cain . 23
On Apr 15, 11:57 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> In <[EMAIL PROTECTED]>, Marko.Cain.23
> wrote:
>
>
>
> > On Apr 14, 10:36 am, [EMAIL PROTECTED] wrote:
> >> On Apr 14, 12:02 am, Michael Bentley <[EMAIL PROTECTED]>
> >> wrote:
>
> >> > On Apr 13, 2007, at 11:49 PM, [EMAIL PROTECTED] wrote:
>
> >> > > Hi,
>
> >> > > I have a list of url names like this, and I am trying to strip out the
> >> > > domain name using the following code:
>
> >> > >http://www.cnn.com
> >> > >www.yahoo.com
> >> > >http://www.ebay.co.uk
>
> >> > > pattern = re.compile("http:(.*)\.(.*)", re.S)
> >> > > match = re.findall(pattern, line)
>
> >> > > if (match):
> >> > > s1, s2 = match[0]
>
> >> > > print s2
>
> >> > > but none of the site matched, can you please tell me what am i
> >> > > missing?
>
> >> > change re.compile("http:(.*)\.(.*)", re.S) to re.compile("http:\/
> >> > \/(.*)\.(.*)", re.S)
>
> >> Thanks. I try this:
>
> >> but when the 'line' ishttp://www.cnn.com, I get 's2' com,
> >> but i want 'cnn.com' (everything after the first '.'), how can I do
> >> that?
>
> >> pattern = re.compile("http:\/\/(.*)\.(.*)", re.S)
>
> >> match = re.findall(pattern, line)
>
> >> if (match):
>
> >> s1, s2 = match[0]
>
> >> print s2
>
> > Can anyone please help me with my problem?  I still can't solve it.
>
> > Basically, I want to strip out the text after the first '.' in url
> > address:
>
> >http://www.cnn.com-> cnn.com
>
> from urlparse import urlsplit
>
> def get_domain(url):
> net_location = urlsplit(url)[1]
> return '.'.join(net_location.rsplit('.', 2)[-2:])
>
> def main():
> print get_domain('http://www.cnn.com')
>
> Ciao,
> Marc 'BlackJack' Rintsch

Thanks for your help.

But if the input string is  "http://www.ebay.co.uk/";,  I only get
"co.uk"

how can I change it so that it works for both www.ebay.co.uk and www.cnn.com?

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


Re: sqlite3 question

2007-04-15 Thread Gabriel Genellina
En Thu, 12 Apr 2007 08:43:49 -0300, Marc 'BlackJack' Rintsch  
<[EMAIL PROTECTED]> escribió:

> In <[EMAIL PROTECTED]>, Jorgen Bodde
> wrote:
>
> r = c.execute('select * from song where id = 1')
> for s in r:
>> ...  print s
>> ...  
>> (1, u'Spikedrivers Blues', u'Mississippi John Hurt')

> This should not work because `r` should not be a `Cursor` object.  The
> `execute()`-Method returns an integer with the number of "affected rows".

Actually DBAPI 2.0 says the return value is undefined.

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


Re: Any Pythonistas in Mexico?

2007-04-15 Thread Gabriel Genellina
En Thu, 12 Apr 2007 10:56:32 -0300, Marcpp <[EMAIL PROTECTED]> escribió:

> On 12 abr, 09:41, Hugo González Monteverde <[EMAIL PROTECTED]> wrote:
>> Leí este mail viejísimo en una lista. Yo uso Python y también quería
>> saber quién pythoneaba en México. Todavía estás por ahí?
>
> Yo vivo en España.

Yo en Argentina. Hay un grupo comp.lang.python.general.castellano y su  
correspondiente lista, no se si habrá alguien de Mexico ahi.

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


Re: combination function in python

2007-04-15 Thread Steven D'Aprano
On Sun, 15 Apr 2007 13:58:38 -0700, Mark Dickinson wrote:

> ... for large n and k it's difficult to imagine any real-world
> applications that wouldn't be better served by using the lngamma
> function instead.  That is, the natural log of n choose k can be
> computed much more quickly as
> 
> lngamma(n+1) - lngamma(k+1) - lngamma(n-k+1)

Yes, but if you actually want the number of combinations, not the log of
the number of combinations, you then have to raise e to that power to get
the answer you want -- and that takes time. Is it still faster? How about
round-off error due to floating point? Should you be truncating or
rounding? What about overflow error for large enough n, k?

What exactly are we doing with a five hundred digit long integer anyway?

Exact (long) integer maths still is useful.


> I assume that lngamma is implemented somewhere in either numpy or
> scipy, but right now I can't find it...

You know what they say about what happens when you ASS_U_ME :-)


-- 
Steven.

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


Re: Standardizing XML

2007-04-15 Thread ZeeGeek
On Apr 15, 1:13 pm, Jonathan Ballet <[EMAIL PROTECTED]> wrote:
> Le 15 Apr 2007 11:02:20 -0700,
> "ZeeGeek" <[EMAIL PROTECTED]> a écrit :
>
> > Thanks for correcting me.  I worded it inproperly.  For example, in
> > the code returned by Live Space, they use  instead of  so
> > that Blogger will complain that this tag is not valid because it
> > doesn't have a closing tag.  Another example is that the contents of a
> > lot of the tag attributes like "color" and "size" are not surrounded
> > by quotes.
>
> Maybe you can try BeautifulSoup module which aims to handle things like
> that :http://www.crummy.com/software/BeautifulSoup/

Wow, this tool is fantastic.  Thank you very much.

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


Re: Standardizing XML

2007-04-15 Thread ZeeGeek
On Apr 15, 1:13 pm, ZeD <[EMAIL PROTECTED]> wrote:
> ZeeGeek wrote:
> > in the code returned by Live Space, they use  instead of  so
> > that Blogger will complain that this tag is not valid because it
> > doesn't have a closing tag.  Another example is that the contents of a
> > lot of the tag attributes like "color" and "size" are not surrounded
> > by quotes.
>
> Are you sure it's xml? It sounds to me like "old" HTML

Yeah, I realized this after I read the first reply to my post. That
was a big mistake to word it XML.

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


Re: Making a tree out of a 2 column list

2007-04-15 Thread bearophileHUGS
Sebastian Bassi:
> I guess this should make the program enter into a endless loop. But
> the data won't have such a redundancy, because it was taken from a
> philogenetic tree.

But errors and bugs do happen, inside data too; so often it's better
to be on safe side if the safe code is fast enough.

Bye,
bearophile

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


Re: Making a tree out of a 2 column list

2007-04-15 Thread Paul Rubin
[EMAIL PROTECTED] writes:
> > I guess this should make the program enter into a endless loop. But
> > the data won't have such a redundancy, because it was taken from a
> > philogenetic tree.
> 
> But errors and bugs do happen, inside data too; so often it's better
> to be on safe side if the safe code is fast enough.

If you think the data may be wrong it's probably better to use a 
traditional graph algorithm to check it for cycles, than rely on some
arbitrary recursion depth limit.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: optparse -- anyway to find if the user entered an option?

2007-04-15 Thread Michael Hoffman
James Stroud wrote:
> Karthik Gurusamy wrote:
>> Hi,
>>
>> I see that I can provide a default value for an option. But I couldn't
>> find out any way if the user really entered the option or the option
>> took that value because of default. A simple check for value with
>> default may not always work as the user might have manually
>> entered the same default value.
>>
>> Let's assume I want to take in the ip-address using -i .
>> If user didn't give it explicitly, I am going to use socket interface
>> to figure out this host's IP address.
>>
>> ip_addr_default  = '100.100.100.100'
>>
>> parser.add_option("-i", "--ip-address", dest="ip",
>> default=ip_addr_default,
>>metavar="IP-ADDRESS", help="IP address. default:" +
>>ip_addr_default + "e.g. --i=1.1.1.1"
>>)
>>
>> (options, args) = parser.parse_args()
>>
>> Now if options.ip == ip_addr_default, I still can't be 100% sure that
>> the user did not type -i 100.100.100.100.
>> Any way to figure out from options that the user typed it or not?
>>
>> (The reason I want to know this is if user did not mention -i, I can
>> compute IP later
>> using socket module)
>>
>> I could think of a hack of using None as default and since no user can
>> ever
>> enter a None value, I can be sure that the user didn't provide -i.
>> I'm wondering if there is a cleaner approach -- something like
>> parser.opt_seen("-i")
>>
>> Thanks,
>> Karthik
>>
> 
> Using None wouldn't be a hack, it would rather be a common and 
> straightforward python idiom.

I agree. Also, remember that in optparse the default default (if you 
will) is None.
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is laziness a programer's virtue?

2007-04-15 Thread dbenson
Of course, for functional languages, 'lazy' means something rather
different...

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


Re: Portably generating infinity and NaN

2007-04-15 Thread Michael Hoffman
[EMAIL PROTECTED] wrote:
> Michael> If you're going to change CPython to do this, I think adopting
> Michael> PEP 754, and using the fpconst module would be better than
> Michael> changing how float() works when called on string literals. 
> 
> But PEP 754 will only work for architectures supporting IEEE 754.  I realize
> that's the vast majority of systems, but aren't there still a few Crays and
> VMS machines out there?  (Do those architectures support NaN and Inf?)

Will float("NaN") work on these systems? (I don't know.) I guess it 
probably works on some system that isn't IEEE 754.
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Making a tree out of a 2 column list

2007-04-15 Thread Sebastian Bassi
On 15 Apr 2007 15:44:47 -0700, [EMAIL PROTECTED]
<[EMAIL PROTECTED]> wrote:
> But errors and bugs do happen, inside data too; so often it's better
> to be on safe side if the safe code is fast enough.

Yes, I agree since I've seen lot of errors in data. But this data
comes from a taxonomy tree made by the NCBI, that is why I assume the
data is right.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Feature Request: Allow changing base of member indices to 1

2007-04-15 Thread Beliavsky
On Apr 14, 10:12 pm, "Paddy" <[EMAIL PROTECTED]> wrote:



> So the running count is:
>   Ayes to the left:   VB compatibility.
>   Nays to the right:  QuadIO, Perl, Dijkstra paper.
>
> The nays have it!

One-based indexing would also Python more compatible with Fortran,
Matlab/Octave/Scilab, and S (the language of S-Plus and R). It appears
that engineers, scientists, and statisticians, as opposed to
professional programmers, like 1-based indexing. An obvious argument
for 1-based indexing in the FORmula TRANslation programming language
is that formulas involving arrays in textbooks almost always use 1-
based indexing.

Since Python has always had 0-based indexing and since a user-defined
base can cause problems, as has been discussed, I think Python and
extensions such as NumPy should be left as is.

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


Re: Portably generating infinity and NaN

2007-04-15 Thread Paul Rubin
[EMAIL PROTECTED] writes:
> But PEP 754 will only work for architectures supporting IEEE 754.  I realize
> that's the vast majority of systems, but aren't there still a few Crays and
> VMS machines out there?  (Do those architectures support NaN and Inf?)

I wouldn't worry about it.  There are Python subsystems (like threads) that
don't work on certain OS's, fine, total portability means not being able to
rely on them, and that's ok.  I doubt any Crays are still running, or at least
running any numerical code written in Python.  Same for VMS.
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >