Re: XP rich text cut-n-paste

2006-03-05 Thread Neil Hodgson
Paddy:

 Scintilla does indeed have the feature, and googling for the term copy
 as RTF lead me to http://www.pnotepad.org/ which also has the feature.

Its actually implemented in SciTE rather than Scintilla by the ugly 
technique of writing out an RTF file and then copying that to the 
clipboard. It only works on Windows due to the simpler clipboard API 
compared to X and since RTF is a common format on Windows. Other 
projects sometimes include code from SciTE even though the code isn't 
really written for reuse.

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


raw strings and \

2006-03-05 Thread plahey
I thought I understood raw strings, then I got bitten by this:

x=r'c:\blah\'

which is illegal!  I thought that \ had no special meanning in a raw
string so why can't it be the last character?

making me do:

x=r'c:\blah' '\\'

is just silly...

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


django and mod_python

2006-03-05 Thread bapolis
Hi,

I read the mod_python documentation on the Django site but I'm getting
this error:

EnvironmentError: Could not import DJANGO_SETTINGS_MODULE
'accesshiphop.settings' (is it on sys.path?): No module named
accesshiphop.settings

Here's my httpd.conf:

Location /public_html/myproject/
PythonPath [r'c:/apache/public_html/myproject/']+sys.path
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE myproject.settings
PythonDebug On
/Location

Also, the Django site says Also, if you've manually altered your
PYTHONPATH to put your Django project on it, you'll need to tell
mod_python:

I don't recall adding my project to my PYTHONPATH. Should I have done
this? How do I do this?

Thanks.

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


Re: raw strings and \

2006-03-05 Thread Duncan Booth
 wrote:

 I thought I understood raw strings, then I got bitten by this:
 
 x=r'c:\blah\'
 
 which is illegal!  I thought that \ had no special meanning in a raw
 string so why can't it be the last character?

No, the backslash is still special in terms of parsing the string, it 
is simply that once the string has been parsed escape sequences are not 
interpreted.

 
 making me do:
 
 x=r'c:\blah' '\\'
 
 is just silly...
 
 
Yes, that is silly. You could alternatively do:

x = 'c:/blah/'

or

x = 'c:\\blah\\'

But why would you want to end your path with a literal backslash anyway? 
Get into the habit of using the os.path module for all manipulations of 
file paths and you never need to worry about this sort of thing again.

This sort of thing should work well enough:

folder = 'c:/blah'

for line in open(os.path.join(folder, 'data.txt')):
   print line
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: XP rich text cut-n-paste

2006-03-05 Thread Duncan Booth
Paddy wrote:

 Is their a colourized editor/shell that allows you to cut and paste the
 colourized text?
 
 Idle, SPE, Eclipse, and pythonwin all seem to nicely colourize both
 command line input as well as editor windows but when I cut and paste
 (in this case, into OpenOffice Writer), even the paste-special menu
 just allows the pasting of un-adorned text.
 
 i have a work-around: gvim coourizes and allows export as html, but it
 is long-winded.

Epsilon (www.lugaru.com) has a 'copy-formatting-as-html' command (new in 
the version currently in beta). Unfortunately is isn't a free editor 
(although you can download a time limited beta of the next version for free 
if you want to try it out).
-- 
http://mail.python.org/mailman/listinfo/python-list


is there such a built-in funciton, similar to filter

2006-03-05 Thread wcc
Hello,

Beginner learning Python here.  I know filter(lambda x: x  3, [1, 2,
5, -3, 4, 8]) will give me a list [5, 4, 8].  What if I only need to
find the first item in the list that returns Ture when applying the
filter function.  In this case, I only want to get the 5, and its index
2.  Is there a built-in function, or function from a module for that?
I think it is not hard to write a function for this.  But knowing
Python is battery included, I thought I'd like to ask.  Thanks for
your help. 

- wcc

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


Re: django and mod_python

2006-03-05 Thread Robin Becker
[EMAIL PROTECTED] wrote:
 Hi,
 
 I read the mod_python documentation on the Django site but I'm getting
 this error:
 
 EnvironmentError: Could not import DJANGO_SETTINGS_MODULE
 'accesshiphop.settings' (is it on sys.path?): No module named
 accesshiphop.settings
 
 Here's my httpd.conf:
 
 Location /public_html/myproject/
 PythonPath [r'c:/apache/public_html/myproject/']+sys.path
 SetHandler python-program
 PythonHandler django.core.handlers.modpython
 SetEnv DJANGO_SETTINGS_MODULE myproject.settings
 PythonDebug On
 /Location
 
 Also, the Django site says Also, if you've manually altered your
 PYTHONPATH to put your Django project on it, you'll need to tell
 mod_python:
.
in my setup the PythonPath statement puts the folder containing 
myproject onto the PythonPath in your case that might be

PythonPath [r'c:/apache/public_html']+sys.path

also I place the SetEnv DJANGO_SETTINGS_MODULE  .
before specifying the PythonHandler, but I am unsure if that is required 
(I guess it depends on exactly how apache sets up the location), but 
it's what I would do in a batch file for example.

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


Re: is there such a built-in funciton, similar to filter

2006-03-05 Thread Michael Hoffman
wcc wrote:

 Beginner learning Python here.  I know filter(lambda x: x  3, [1, 2,
 5, -3, 4, 8]) will give me a list [5, 4, 8].  What if I only need to
 find the first item in the list that returns Ture when applying the
 filter function.  In this case, I only want to get the 5, and its index
 2.  Is there a built-in function, or function from a module for that?
 I think it is not hard to write a function for this.  But knowing
 Python is battery included, I thought I'd like to ask.  Thanks for
 your help. 

You can use a generator expression like this:

  items = [1, 2, 5, -3, 4, 8]
  ((index, item) for index, item in enumerate(items) if item  3).next()
(2, 5)
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Passing a method indirectly

2006-03-05 Thread swisscheese
Thanks - that worked! 
Thanks to the other replies also.

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


lists: += vs. .append() oddness with scope of variables

2006-03-05 Thread Sandro Dentella
I'd like to understand why += operator raises an error while .append() does
not. My wild guess is the parses treats them differently but I cannot
understand why this depends on scope of the variables (global or class
variables):


a = [0]

class foo(object): 

def __init__(self):
print a: , a
# += does not work if 'a' is global
#a += [1]
a.append(2)
print a= , a

class bar(object): 

b = [0]

def __init__(self):
print b: , self.b
# += *does* work if 'a' is class var
self.b += [1]
self.b.append(2)
print b= , self.b


if __name__ == '__main__':
x = foo()
y = bar()

a:  [0]
a=  [0, 2]
b:  [0]
b=  [0, 1, 2]

uncommenting 'a += [1]' would raise:

a:
Traceback (most recent call last):
  File c1.py, line 26, in ?
x = foo()
  File c1.py, line 7, in __init__
print a: , a
UnboundLocalError: local variable 'a' referenced before assignment

TIA
sandro
*:-)


-- 
Sandro Dentella  *:-)
e-mail: [EMAIL PROTECTED] 
http://www.tksql.orgTkSQL Home page - My GPL work
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: lists: += vs. .append() oddness with scope of variables

2006-03-05 Thread Felipe Almeida Lessa
Em Dom, 2006-03-05 às 11:49 +, Sandro Dentella escreveu:
 class foo(object): 
 
 def __init__(self):
 print a: , a
 # += does not work if 'a' is global
 #a += [1]
 a.append(2)
 print a= , a 

Try with:
a = [0]

class foo(object): 
def __init__(self):
global a
print a: , a
a += [1]
a.append(2)
print a= , a

foo()

-- 
Quem excele em empregar a força militar subjulga os exércitos dos
outros povos sem travar batalha, toma cidades fortificadas dos outros
povos sem as atacar e destrói os estados dos outros povos sem lutas
prolongadas. Deve lutar sob o Céu com o propósito primordial da
'preservação'. Desse modo suas armas não se embotarão, e os ganhos
poderão ser preservados. Essa é a estratégia para planejar ofensivas.

  -- Sun Tzu, em A arte da guerra

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

Re: lists: += vs. .append() oddness with scope of variables

2006-03-05 Thread Duncan Booth
Sandro Dentella wrote:

 I'd like to understand why += operator raises an error while .append()
 does not. My wild guess is the parses treats them differently but I
 cannot understand why this depends on scope of the variables (global
 or class variables):
 
 
 a = [0]
 
 class foo(object): 
 
 def __init__(self):
 print a: , a
 # += does not work if 'a' is global
 #a += [1]
 a.append(2)
 print a= , a
 

Any assignment to a variable within a function means that the name to which 
you are assigning is regarded as a local variable (unless you use the 
'global' statement to override that). += is a form of assignment, calling 
the append method is not an assignment.

The solution here is simply to use 'global a' to tell the compiler that you 
meant to assign the the global variable rather than creating a new local 
variable.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Random Prime Generator/Modular Arithmetic

2006-03-05 Thread Astan Chee
thanks for the webpage info,
however theres a small error I found when trying to generate a prime 
number with more than 300 decimal digits. It comes up with

File prime.py, line 84, in mod_square_pow
return x*mod_square_pow(((a**2)%n),t,n,p*2)
  File prime.py, line 84, in mod_square_pow
return x*mod_square_pow(((a**2)%n),t,n,p*2)
  File prime.py, line 73, in mod_square_pow
if(p*2t):
RuntimeError: maximum recursion depth exceeded in cmp

Have you considered this? otherwise the algorithm is rather quick for 
generating large random prime numbers.
Thanks for your help

Tuvas wrote:

Okay, I don't know if your farmiliar with the miller-rabin primality
test, but it's what's called a probabalistic test. Meaning that trying
it out once can give fake results. For instance, if you use the number
31 to test if 561 is prime, you will see the results say that it isn't.
Mathematically, the most possible wrong answers is 1/4th of the
numbers. Thus, one should try at least 10 times (A very standard value)
in order to ensure that the number is not a psuedoprime, but indeed a
real prime number. That was the intent of the loop of 10 without using
the number.

If this test fails, it will chose another random number to test.

I could easily test with several small numbers, at least primes up to
20 would greatly reduce the number of miller-rabin tests to perform,
and would speed up the process considerably. Might as well toss it in.

Thanks for the tip on the urandom. I knew there had to be a better
random number generator somewhere. I saw lots of stuff for os specific,
but I'm trying to develop this as os independent.

  

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


disabling the line buffer somehow

2006-03-05 Thread Can Burak Cilingir
Hi,

I'm trying to proxy all keys typed by the user to a process spawned via
popen2. Unfortunately, I figured out that I can't control really
interactive applications such as mc or aptitude.

All user input seems to be line buffered.
http://pexpect.sourceforge.net/ has some words about the situation: Q:
Why not just use a pipe (popen())?

So, I understand that I cannot write a simple python code to
transperantly proxy everything between any process and user typing from
stdin without handling the raw terminal.

Would it work if I read from the controlling tty of the python
interpreter and write to the controlling tty of spawned process byte by
byte (or /dev/stdin  /dev/stdout)

Thanks..

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


Re: how to overload sqrt in a module?

2006-03-05 Thread Kent Johnson
Michael McNeil Forbes wrote:
 Is there anything really bad about the 
 following?  It works exactly as I would like, but I don't want to get in 
 trouble down the road:
 
 module_f
 
 import math as my_math
 
 def set_math(custom_math):
 globals()['my_math'] = custom_math

This seems clearer to me:
def set_math(custom_math):
 global my_math
 my_math = custom_math

 Or, if one wants to use the from __ import * form:
 
 from math import *
 
 def set_math(custom_math):
 globals().update(custom_math.__dict__)

This will cause interesting trouble if custom_math doesn't implement all 
the functions you use from math.

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


Argument Precedence (possible bug?)

2006-03-05 Thread vbgunz
Hello all,

I am just learning Python and have come across something I feel might
be a bug. Please enlightenment me... The following code presents a
challenge. How in the world do you provide an argument for *arg4?

## 
def argPrecedence(par1, par2=0, par3=0, *par4, **par5):
print 'par1 =', par1, ' # positional argument'
print 'par2 =', par2, ' # keyword argument'
print 'par3 =', par3, ' # keyword argument'
print 'par4 =', par4, ' # argument converted to tuple'
print 'par5 =', par5, ' # argument converted to dictionary'


argPrecedence('arg1', arg3='arg3', arg2='arg2', arg5='arg5')

# argPrecedence Results:
par1 = arg1  # positional argument
par2 = arg2  # keyword argument
par3 = arg3  # keyword argument
par4 = ()  # argument converted to tuple
par5 = {'arg5': 'arg5'}  # argument converted to dictionary
## 

The code above is verbose with comments because I am just learning
Python and am creating my own examples and reference materials... Can
you solve the problem? If so, can you share the solution? If not, is
this a bug, limitation or is it a feature?

Thank you for your time on this one!

PS. I could be far off with this codes purpose; to try and create an
example that will house all the different possible parameters
(positional, keyword, * and **) in one single def statement.

--  
Best Regards
Victor B. Gonzalez

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


Argument Precedence (possible bug?)

2006-03-05 Thread vbgunz
Hello all,

I am just learning Python and have come across something I feel might
be a bug. Please enlightenment me... The following code presents a
challenge. How in the world do you provide an argument for *arg4?

## 
def argPrecedence(par1, par2=0, par3=0, *par4, **par5):
print 'par1 =', par1, ' # positional argument'
print 'par2 =', par2, ' # keyword argument'
print 'par3 =', par3, ' # keyword argument'
print 'par4 =', par4, ' # argument converted to tuple'
print 'par5 =', par5, ' # argument converted to dictionary'


argPrecedence('arg1', par3='arg3', par2='arg2', par5='arg5')

# argPrecedence Results:
par1 = arg1  # positional argument
par2 = arg2  # keyword argument
par3 = arg3  # keyword argument
par4 = ()  # argument converted to tuple
par5 = {'arg5': 'arg5'}  # argument converted to dictionary
## 

The code above is verbose with comments because I am just learning
Python and am creating my own examples and reference materials... Can
you solve the problem? If so, can you share the solution? If not, is
this a bug, limitation or is it a feature?

Thank you for your time on this one!

PS. I could be far off with this codes purpose; to try and create an
example that will house all the different possible parameters
(positional, keyword, * and **) in one single def statement.

--  
Best Regards
Victor B. Gonzalez

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


Re: Argument Precedence (possible bug?)

2006-03-05 Thread vbgunz
Please forgive my call()

Change this:
argPrecedence('arg1', arg3='arg3', arg2='arg2', arg5='arg5')

to this:
argPrecedence('arg1', par3='arg3', par2='arg2', arg5='arg5')

Thanks!

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


Re: Argument Precedence (possible bug?)

2006-03-05 Thread vbgunz
Hello all,

I am just learning Python and have come across something I feel might
be a bug. Please enlightenment me... The following code presents a
challenge. How in the world do you provide an argument for *arg4?

## 
def argPrecedence(par1, par2=0, par3=0, *par4, **par5):
print 'par1 =', par1, ' # positional argument'
print 'par2 =', par2, ' # keyword argument'
print 'par3 =', par3, ' # keyword argument'
print 'par4 =', par4, ' # argument converted to tuple'
print 'par5 =', par5, ' # argument converted to dictionary'

argPrecedence('arg1', par3='arg3', par2='arg2', arg5='arg5')

# argPrecedence Results:
par1 = arg1  # positional argument
par2 = arg2  # keyword argument
par3 = arg3  # keyword argument
par4 = ()  # argument converted to tuple
par5 = {'arg5': 'arg5'}  # argument converted to dictionary
## 

The code above is verbose with comments because I am just learning
Python and am creating my own examples and reference materials... Can
you solve the problem? If so, can you share the solution? If not, is
this a bug, limitation or is it a feature?

Thank you for your time on this one!

PS. I could be far off with this codes purpose; to try and create an
example that will house all the different possible parameters
(positional, keyword, * and **) in one single def statement.

--  
Best Regards
Victor B. Gonzalez

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


Re: Argument Precedence (possible bug?)

2006-03-05 Thread Fredrik Lundh
vbgunz wrote:

 I am just learning Python and have come across something I feel might
 be a bug. Please enlightenment me... The following code presents a
 challenge. How in the world do you provide an argument for *arg4?

 ## 
 def argPrecedence(par1, par2=0, par3=0, *par4, **par5):
 print 'par1 =', par1, ' # positional argument'
 print 'par2 =', par2, ' # keyword argument'
 print 'par3 =', par3, ' # keyword argument'
 print 'par4 =', par4, ' # argument converted to tuple'
 print 'par5 =', par5, ' # argument converted to dictionary'

 argPrecedence('arg1', arg3='arg3', arg2='arg2', arg5='arg5')

 # argPrecedence Results:
 par1 = arg1  # positional argument
 par2 = arg2  # keyword argument
 par3 = arg3  # keyword argument
 par4 = ()  # argument converted to tuple
 par5 = {'arg5': 'arg5'}  # argument converted to dictionary
 ## 

 The code above is verbose with comments because I am just learning
 Python and am creating my own examples and reference materials... Can
 you solve the problem? If so, can you share the solution? If not, is
 this a bug, limitation or is it a feature?

not sure what you think the bug is, but I suspect that you've completely
missed the point of what * and ** do, and how they're used in real code.

/F



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


Question re client/server and blocking

2006-03-05 Thread Frank Millman
Hi all

I am developing a multi-user business/accounting application. It is
coming along nicely :-), though rather slowly :-(

I have hit an issue which will require a lot of changes to the code I
have written so far, together with an increase in complexity and all
the bad things that follow from that. Before I go ahead and make the
changes, I thought I would bounce it off the group and see if there is
a simpler approach.

It is a bit tricky to explain (yes I have read the Zen of Python) but
here goes.

There is a server component and a client component. All the business
logic is performed on the server. The client communicates with the
server via a socket. The server is multi-threaded - one thread per
connection.

The server receives messages from the client, and responds as quickly
as possible. Sometimes it must respond by asking the client a question.
It must not block while waiting for an answer, so this is how I handle
it (pseudo code) -

def handleMessage(self):
mainloop.askQuestion(questionText,self.answerYes,self.answerNo)

def answerYes(self):
handle Yes answer

def answerNo(self):
handle No answer

The main loop stores the function references, and sends the question to
the client. When it gets a reply, it calls the appropriate function. It
works well.

The server performs field-by-field validation - it does not wait for
the entire form to be submitted, but validates the data as soon as it
has been entered. Depending on the context, the validation may have to
pass a number of checks, which may pass through a number of layers,
eventually returning True or False. e.g. -

def validate(self,data):
if not check1:
return False
if not check2:
return False
if not self.check3(data):
return False
if not self.check4(data):
return False
if not check5:
return False
return True

check3(self,data):
if not check3a:
return False
return True

check4(self,data):
if not check4a:
return False
if not self.check4b(data):
return False
return True

Effectively the entire chain blocks until a result is returned, but
provided each element performs its check quickly, this will not be
noticeable.

Now I have decided that, in some circumstances, I want the server to
ask the client a question before returning True or False - it could be
as simple as Are you sure?. This throws a large spanner into the
above scheme. Each caller cannot be sure whether the callee (?) will
return quickly or not, so it cannot afford to wait for a reply,
otherwise it may block. The only solution I can think of looks like
this -

def validate(self,data,checkOk,checkNotOk):
# checkOk and checkNotOk are functions passed by the caller
self.data = data
self.checkOk = checkOk
self.checkNotOk = checkNotOk
if not check1:
self.checkNotOk()
if not check2:
self.checkNotOk()
self.check3(self.data,self.check3Ok,self.checkNotOk)

def check3Ok(self):
self.check4(self.data,self.check4Ok,self.checkNotOk)

def check4Ok(self):
if not check5:
checkNotOk()
self.checkOk()

The callee must then look like this -

def check3(self,data,checkOk,checkNotOk):
if check ok:
checkOk()
else:
checkNotOk()

Then on the odd occasion that the callee needs to ask a question, it
can do this -

def check4(self,data,checkOk,checkNotOk):
mainloop.askQuestion(questionText,checkOk,checkNotOk)

This is similar to Twisted's approach of deferreds and callbacks.
However, I do not think that using Twisted would simplify any of this -
I would still have to split my logic chain up into multiple callback
functions.

I believe that I can get this to work, that it will add a powerful
layer of functionality to my app, and that I could eventually refactor
it enough so that it is actually understandable. On the other hand, it
is much more complex than what I have got at present, and to change my
entire app to use this mechanism will be quite a task.

Have I explained myself adequately? Has anyone come across a similar
situation before? Any advice will be much appreciated.

Thanks

Frank Millman

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


Re: how to overload sqrt in a module?

2006-03-05 Thread Steven D'Aprano
On Sat, 04 Mar 2006 23:07:12 -0800, Michael McNeil Forbes wrote:

 On Fri, 3 Mar 2006, Steven D'Aprano wrote:
 
 ... you can do this:

 import my_module
 my_module.set_environment(math) # or cmath, or numeric, or whatever

 Your my_module will be like this:

 # Warning: untested code.
 ENVIRON = None  # global variables sometimes have their uses

 def f(x):
if ENVIRON is None:
raise ValueError(Uninitialised module!)
# or use a custom exception
return ENVIRON.sqrt(x)

 def set_environment(name):
global ENVIRON
ENVIRON = __import__(name)


 Does this help?
 
 Yes.  However, this raises a question: Is this any different than 
 directly modifying the globals, or is it just syntactic sugar.

The keyword global instructs Python to make all references to the
following name come from the global namespace. It is the correct way to
do it (but not necessarily the *only* correct way, or *always* the
correct way). In something as tiny as your example:

 def set_environment(name):
  globals()['ENVIRON'] = __import__(name)

it may not make any practical difference which method you use. But in
larger, more complex code, you are creating a rod for your own back. Try
running these three functions, and explain the difference in their
behaviour.

def f1():
global parrot
parrot = 3
parrot += 1
print parrot is %d % parrot

def f2():
globals()[parrot] = 3
globals()[parrot] += 1
print parrot is %d % parrot

def f3():
globals()[parrot] = 3
parrot += 1
print parrot is %d % parrot


Directly modifying the globals is playing around with Python's internals.
You are allowed to do that, and sometimes it is the right thing to do,
otherwise Guido wouldn't have made globals() writable. 

E.g. you have code where you want -- heaven knows why -- a name to refer
to both a local and a global variable. This will work:

def func():
x = 5  # x is local
globals()['x'] = 3  # but this x is global


I don't know whether writing to globals() is guaranteed to work for all
variants of Python (CPython, Jython, PyPy, IronPython ... ) or if it is
likely to change in Python 3. But even if modifying globals() is
officially allowed, it still has a whiff of the sort of code-smell that
Joel Spolsky talks about:

http://www.joelonsoftware.com/articles/Wrong.html

In my opinion, manipulating globals() is one of those things that ring
warning bells in my head. It might not be *wrong*, exactly, but I'll want
to pay extra attention to any function that does that.


-- 
Steven.

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


Re: is there such a built-in funciton, similar to filter

2006-03-05 Thread wcc
Thanks a lot Michael.

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


Re: Argument Precedence (possible bug?)

2006-03-05 Thread Peter Hansen
vbgunz wrote:
 I am just learning Python and have come across something I feel might
 be a bug. Please enlightenment me... The following code presents a
 challenge. How in the world do you provide an argument for *arg4?

Maybe by putting that in the list of arguments?  ...

You don't even *have* an arg4 in the list, so how are we supposed to 
know what you are asking without guessing?  Please consider rephrasing 
the question.

-Peter

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


Re: Python advocacy in scientific computation

2006-03-05 Thread Brian Blais
Robert Kern wrote:
 
 That said, we have an excellent array object far superior to Matlab's.
 
   http://numeric.scipy.org/
 

I'd like to ask, being new to python, in which ways is this array object far 
superior
to Matlab's?  (I'm not being sarcastic, I really would like to know!)

I've heard similar things about matplotlib, about how it surpasses Matlab's 
graphics.
  I haven't personally experienced this, but I'd like to know in which ways it 
is.



bb



-- 
-

 [EMAIL PROTECTED]
 http://web.bryant.edu/~bblais

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


Re: Argument Precedence (possible bug?)

2006-03-05 Thread Steven D'Aprano
On Sun, 05 Mar 2006 04:45:05 -0800, vbgunz wrote:

 Hello all,
 
 I am just learning Python and have come across something I feel might
 be a bug. Please enlightenment me... The following code presents a
 challenge. How in the world do you provide an argument for *arg4?
 
 ## 
 def argPrecedence(par1, par2=0, par3=0, *par4, **par5):
 print 'par1 =', par1, ' # positional argument'
 print 'par2 =', par2, ' # keyword argument'
 print 'par3 =', par3, ' # keyword argument'
 print 'par4 =', par4, ' # argument converted to tuple'
 print 'par5 =', par5, ' # argument converted to dictionary'

No, you are confused about * and ** arguments. They don't convert
arguments, they collect them.

def f(a, b=0, *args, **kwargs):
print a =, a
print b =, b
print args =, args
print kwargs =, kwargs

Now call the function different ways, and see which will work and which
won't. 

f(1)
f(1, 2)
f(1, b=2)
f(a=1, b=2)
f(b=2, a=1)

Notice that this does not work:

f(b=3)

Do you understand why not?

Now look at these calls:

f(1, 2, 3)
f(1, 2, 3, 4, 5, 6)
f(1, 2, 3, 4, 5, 6, foo=7, bar=8)

In the function definition f(a, b=0, *args, **kwargs), a must be supplied,
b has a default value so it can be left out. Both a and b can be provided
as positional arguments like f(2, 3) or as keyword arguments.

Any _extra_ positional arguments are collected into a tuple called args,
and any _extra_ keyword arguments are collected into a dictionary called
kwargs. Of course you can use any names you like.

Hope this helps,



-- 
Steven.

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


Re: Argument Precedence (possible bug?)

2006-03-05 Thread Steven D'Aprano
On Sun, 05 Mar 2006 04:45:05 -0800, vbgunz wrote:

 PS. I could be far off with this codes purpose; to try and create an
 example that will house all the different possible parameters
 (positional, keyword, * and **) in one single def statement.

This is usually a bad idea, not because Python can't cope with it, but
because it is usually better to learn new things in small pieces, not one
giant enormous piece.

Try creating a number of small functions that do different things:

def f(a, b, c):
print a =, a, b =, b, c =, c

def g(a=0, b=0, c=0):
print a =, a, b =, b, c =, c

Now call them different ways, and see what happens:

f()
f(1)
f(1,2)
f(1,2,3)
f(b=2)

Can you see a pattern?

g()
g(1)
g(1,2)
g(1,2,3)
g(b=2)

Then move on to argument collectors:

def h(a, b, c=0, *d, **e):
print a =, a, b =, b, c =, c
print d =, d, e =, e



Also, remember that positional arguments and keyword arguments aren't
defined differently, they are given when you call the function. For
example, suppose you have this:

def function(x, y):
print x + y

Now you call it with positional arguments: function(3, 7)
Now you call it with keyword arguments: function(x=3, y=7)
Now you call it with both: function(3, y=7)

All from the same definition. An argument is positional or keyword
according to how it is given, not how it is defined.


-- 
Steven.

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


Re: How to except the unexpected?

2006-03-05 Thread Rene Pijlman
Steven D'Aprano:
The OP is doing it because catching all exceptions masks bugs. There are
certain exceptions which should be allowed through, as they indicate a bug
in the OP's code. Normally the tactic is to catch only the exceptions you
are interested in, and let everything else through, but the OP needs to
catch all exceptions because there are rare exceptions which he can't
predict in advance.

To add to that explanation: this is in a multithreaded ZODB-application.
When an unexpected exception occurs and remains uncaught, a thread
terminates, causing the thread pool to wait forever since some thread is
not consuming its termination request from the queue, causing the app to
not terminate, causing the ZODB to remain locked, causing other apps to
fail, causing havoc on my server.

I don't mind this when it's caused by a bug in my code, since that creates
the sense of urgency required to fix the bug. But it's annoying when it
happens because of an I/O exception caused by some other guys bug on the
other side of the planet :-)

-- 
René Pijlman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Argument Precedence (possible bug?)

2006-03-05 Thread vbgunz
I am sorry I hung you up on a typo Peter Hansen. On line 5 *arg4 should
have been *par4. I hope it makes complete sense now. Sorry.

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


Re: Argument Precedence (possible bug?)

2006-03-05 Thread vbgunz
Please allow me some time to look at your examples. I get hung up over
the smallest details because in my mind, my approach should have just
worked... I learned about these parameters reading O'reilly Learning
Python 2nd Edition. On page 217 of the paperback or Chapter 13.5.6 in
the ebook, topic: 'Argument matching: The Gritty Details' mentions the
following in verbatim...

...'''
Moreover, Python internally carries out the following steps to match
arguments before assignment:
1. Assign non-keyword arguments by position.
2. Assign keyword arguments by matching names.
3. Assign extra non-keyword arguments to *name tuple.
4. Assign extra keyword arguments to **name dictionary.
5. Assign default values to unassigned arguments in header.
'''...

As you can probably tell, I tried to follow the steps exactly, except
step 5 got me lost so I tried not to question it. Anyhow, thank you
very much for your time and examples. I will get back to you as soon as
I am done putting your response to trial. Thank you!

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


Inline assignments

2006-03-05 Thread Fredrik Tolf
Hi list!

I'm relatively new to Python, and one thing I can't seem to get over is
the lack of in-expression assignments, as present in many other
languages. I'd really like to know how Python regulars solve the
problems posed by that.

For example, I recently wanted to do this:

if callable(f = getattr(self, cmd_ + name)):
# Do something with f
elif callable(f = getattr(self, cmdv_ + name)):
# Do something else with f

However, since I can't do that in Python, I ended up using an extra
local variable instead, like this:

f = getattr(self, cmd_ + name)
f2 = getattr(self, cmdv_ + name)
if callable(f):
# Do something with f
elif callable(f2):
# Do something with f2

Another common problem for me are while loops. I would often like to do
this:
while (pos = somestring.find(/)) != -1:
part = somestring[:pos]
somestring = somestring[pos + 1:]
# Handle part

However, that, too, is impossible, and I end up doing something like
this:
while True:
pos = somestring.find(/)
if pos == -1: break
# ...

Which is quite ugly. This might have been a bad example, since
somestring.split() could be used instead, but it's still valid for other
situations.

How would you go about these situations?

Thanks for your time!

Fredrik Tolf


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


Re: generators shared among threads

2006-03-05 Thread Alan Kennedy
[EMAIL PROTECTED]
 def f()
 i = 0
 while True:
 yield i
 i += 1
 g=f()

 If I pass g around to various threads and I want them to always be
 yielded a unique value, will I have a race condition?

Yes.

Generators can be shared between threads, but they cannot be resumed
from two threads at the same time.

You should wrap it in a lock to ensure that only one thread at a time
can resume the generator.

Read this thread from a couple of years back about the same topic.

Suggested generator to add to threading module.
http://groups.google.com/group/comp.lang.python/browse_frm/thread/76aa2afa913fe4df/a2ede21f7dd78f34#a2ede21f7dd78f34

Also contained in that thread is an implementation of Queue.Queue which
supplies values from a generator, and which does not require a separate
thread to generate values.

HTH,

--
alan kennedy
--
email alan:  http://xhaus.com/contact/alan

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


Re: Random Prime Generator/Modular Arithmetic

2006-03-05 Thread Tuvas
H. Well, I don't know what else I could do, except for to write a
function that doesn't require recursion. Still, 300 digits isn't too
bad... I have also realized that if you try is_prime(3) it will return
false. I'll have to work on it... Thanks for the help!

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


Re: Random Prime Generator/Modular Arithmetic

2006-03-05 Thread Astan Chee
Also you last code which looked like:

def cran_rand(min,max):
if(minmax):
x=max
max=min
min=x
range=round(log(max-min)/log(256))
if range==0:
range=1
num=max+1
while(nummax):
num=min+s2num(urandom(range))
return num


what does s2num do? im assuming it changes string chars to ascii 
decimal? Is that correct?
and  i thought is_prime would work better if you listed all small primes 
(2) and check if they are divisible by those.
Aside from that Im really interested in your cran_rand function as I 
havent fully tested it out yet.
Cheers


Tuvas wrote:

H. Well, I don't know what else I could do, except for to write a
function that doesn't require recursion. Still, 300 digits isn't too
bad... I have also realized that if you try is_prime(3) it will return
false. I'll have to work on it... Thanks for the help!

  

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


Re: Inline assignments

2006-03-05 Thread Peter Hansen
Fredrik Tolf wrote:
 I'm relatively new to Python, and one thing I can't seem to get over is
 the lack of in-expression assignments, as present in many other
 languages. I'd really like to know how Python regulars solve the
 problems posed by that.
 
 For example, I recently wanted to do this:
 
 if callable(f = getattr(self, cmd_ + name)):
   # Do something with f
 elif callable(f = getattr(self, cmdv_ + name)):
   # Do something else with f

for prefix in ('cmd_', 'cmdv_'):
 f = getattr(self, prefix + name)
 if callable(f):
 # do something with f

(and note that the if callable(f) test is probably not required 
anyway, though that depends on the specific case)

If the do something and do something else parts are really doing 
different things, then you should put that code into other methods and 
include references to those methods in the list along with the prefixes, 
so you can keep the code free of the extra layer of logic.  A more real 
example would be useful in continuing the discussion down that path. 
(At the moment, the answer to that looks like it would be since you are 
already looking up a callable, just call it.)

 Another common problem for me are while loops. I would often like to do
 this:
 while (pos = somestring.find(/)) != -1:
   part = somestring[:pos]
   somestring = somestring[pos + 1:]
   # Handle part
 
 However, that, too, is impossible, and I end up doing something like
 this:
 while True:
   pos = somestring.find(/)
   if pos == -1: break
   # ...
 
 Which is quite ugly. 

Ugly is very much in the eye of the beholder.  In this case, with an eye 
to readability and maintainability, I find the latter much more direct 
than the former, which blends a search, and assignment, a comparison, 
and a conditional control structure all into a single line, making it 
very hard to just scan the code quickly and know for sure what is happening.

  This might have been a bad example, since
 somestring.split() could be used instead, but it's still valid for other
 situations.

And each of those other situations usually has an equally 
straightforward solution. :-)

-Peter

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


Re: Random Prime Generator/Modular Arithmetic

2006-03-05 Thread Tuvas
Yep, you guessed correctly about the s2num function, I knew I should
have put a bit more.. It just converts an ascii string to a number,
however many numbers that are nessicary. I could indeed check for all
primes below a certain number, however, it still seems to run quite
fast, at least to a 400 digit number. It's not something I'm going to
use a ton, so optimizing it might not be worth it much more than it is.
Perhaps I'll try all primes at least up to 100, that wouldn't be too
bad... Maybe I'll have to modify my old prime string to output the
python command to check all of them, it's a bit of a pain the whole if
0 in (n%2, n%3) stuff, and I can't think of a better way to do it
without writing a new function to do so.
I'm going to post the new code in just a minute, it's running quite
nicely. I'm also posting my RSA function, which I believe should be
secure enough. I'm uploading the code to them now, the HTML page'll be
a few minutes...

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


Re: Inline assignments

2006-03-05 Thread Duncan Booth
Fredrik Tolf wrote:
 However, since I can't do that in Python, I ended up using an extra
 local variable instead, like this:
 
 f = getattr(self, cmd_ + name)
 f2 = getattr(self, cmdv_ + name)
 if callable(f):
  # Do something with f
 elif callable(f2):
  # Do something with f2

If 'do something' is the same thing:

for prefix in ('cmd_', 'cmdv_'):
   f = getattr(self, prefix+name)
   if callable(f):
  # do something with f
  break

If 'do something' is different each time, put each block into a method:

   def do_cmd(self, f): ...
   def do_cmdv(self, f): ...

...
for prefix, action in (('cmd_', self.do_cmd), ('cmdv_', self.do_cmdv)):
   f = getattr(self, prefix+name)
   if callable(f):
  action(f)
  break

 
 Another common problem for me are while loops. I would often like to do
 this:
 while (pos = somestring.find(/)) != -1:
  part = somestring[:pos]
  somestring = somestring[pos + 1:]
  # Handle part

for part in somestring.split(/)[:-1]:
# handle part

Are you sure you didn't want to process the last part of the string as 
well? I would have thought that to be more common, and rather harder to 
write using your original structure.

 
 Which is quite ugly. This might have been a bad example, since
 somestring.split() could be used instead, but it's still valid for other
 situations.
 
Not really. Your original loop refactors quite nicely by calling a method 
or function which returns a sequence of results. The same pattern in will 
always be refactorable in the same way. If the appropriate 'split' function 
doesn't already exist then you can write it.

A very common way to rewrite this sort of loop these days is to write a 
generator. It is usually beneficial to factor out the complex part of the 
loop logic in this way as then you only have to write it once no matter how 
many loops you have with the same structure.
-- 
http://mail.python.org/mailman/listinfo/python-list


Why I chose Python over Ruby

2006-03-05 Thread Francois
I discovered Python a few months ago and soon decided to invest time in
learning it well. While surfing the net for Python, I also saw the hype
over Ruby and tried to find out more about it, before I definitely
embarked on studying and practicing Python. I recently found two
sufficient answers for choosing Python - which is a personal choice and
others may differ, but I'd like to share it anyway :

1) In Ruby there is a risk of Variable/Method Ambiguity when calling
a method with no parameters without using () :

Here is an excerpt from the book Programming Ruby The Pragmatic
Programmer's Guide.

http://www.rubycentral.com/book/language.html

When Ruby sees a name such as ``a'' in an expression, it needs to
determine if it is a local variable reference or a call to a method
with no parameters. To decide which is the case, Ruby uses a heuristic.
As Ruby reads a source file, it keeps track of symbols that have been
assigned to. It assumes that these symbols are variables. When it
subsequently comes across a symbol that might be either a variable or a
method call, it checks to see if it has seen a prior assignment to that
symbol. If so, it treats the symbol as a variable; otherwise it treats
it as a method call. As a somewhat pathological case of this, consider
the following code fragment, submitted by Clemens Hintze.

def a
  print Function 'a' called\n
  99
end

for i in 1..2
  if i == 2
print a=, a, \n
  else
a = 1
print a=, a, \n
  end
end

OUTPUTS 

a=1
Function 'a' called
a=99

During the parse, Ruby sees the use of ``a'' in the first print
statement and, as it hasn't yet seen any assignment to ``a,'' assumes
that it is a method call. By the time it gets to the second print
statement, though, it has seen an assignment, and so treats ``a'' as a
variable.
Note that the assignment does not have to be executed---Ruby just has
to have seen it. This program does not raise an error.

I tried the code above at the interactive Ruby 1.8.2 interpreter :

http://www.ruby.ch/tutorial/

2) Ruby does not have true first-class functions living in the same
namespace as other variables while Python does :

In Python :

def sayHello (name) :
  return Hello  + name
print sayHello(Mr. Bond)
m = sayHello
print m
print m(Miss Moneypenny)

OUTPUTS 

Hello Mr. Bond
function sayHello at 0x0102E870
Hello Miss Moneypenny

In Ruby you need extra syntax that ruins the first-class-ness :

def sayHello (name)
  return Hello  + name
end
puts sayHello(Mr. Bond)
m = Class.method(:sayHello)
puts m
puts m.call(Miss Moneypenny)

OUTPUTS 

Hello Mr. Bond
#Method: Class(Object)#sayHello
Hello Miss Moneypenny

4) Conclusion

Since I did a lot of work in Scheme, rigor and consistency are most
important to me, and Python certainly meets this requirement.

--- Python newbie

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


Re: Papers on Dynamic Languages

2006-03-05 Thread Jay Parlar

On Mar 4, 2006, at 3:00 PM, Paul Boddie wrote:

 I'd have a look at the following Python-related papers:

 Michael Salib's Starkiller paper (and presentation):
 http://www.python.org/pycon/dc2004/papers/1/

 Mark Dufour's ShedSkin paper:
 http://kascade.org/optimizing_python.pdf

 John Aycock's Aggressive Type Inference paper:
 http://www.python.org/workshops/2000-01/proceedings/papers/aycock/ 
 aycock.html

 I also provided a fair number of references in the following thread:

 http://groups.google.co.uk/group/comp.lang.python/browse_thread/ 
 thread/cc98317bdf96efda

 I hope this is of use!

 Paul

All that looks fantastic, and I'd forgotten there was a paper on  
Shedskin.

Thanks a bunch,
Jay P.

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


Re: Inline assignments

2006-03-05 Thread Alex Martelli
Fredrik Tolf [EMAIL PROTECTED] wrote:
   ...
 I'm relatively new to Python, and one thing I can't seem to get over is
 the lack of in-expression assignments, as present in many other
 languages. I'd really like to know how Python regulars solve the
 problems posed by that.

In general, we've learned to do without and structure our code
differently -- less compactly, more airy. Python is not about
maximally compact code -- other languages of roughly equivalent power,
such as Perl, are more suitable if that's your goal; in Python, we aim
for less compactness and more readability (and maintainability).  E.g.:

 if callable(f = getattr(self, cmd_ + name)):
   # Do something with f
 elif callable(f = getattr(self, cmdv_ + name)):
   # Do something else with f

might become:

f = getattr(self, cmd_ + name)
if callable(f):
# Do something with f
else:
f = getattr(self, cmdv_ + name)
if callable(f):
# Do something else with f

7 lines instead of 4 (if the comments stand for one line each), but
exactly the same semantics.


 Another common problem for me are while loops. I would often like to do

That's part of why Python often prefers for loops -- with a generator to
handle the looping logic part, if needed.  For example, 

 while (pos = somestring.find(/)) != -1:
   part = somestring[:pos]
   somestring = somestring[pos + 1:]
   # Handle part

might often become a simple:

for part in somestring.split('/'):
# handle part

but that has slightly different semantics (handles the part after the
last occurrence of / too, doesn't explicitly record pos, ...) which
might be adjusted if needed (e.g. with a [:-1] after the call to split
and before the colon to omit the last part). If the adjustment is
major, e.g. you do need every variable to be set just like so in the
body, then a generator can help -- with the focus being on a separation
between the business logic (the handle part processing) and the
plumbing (generate all 'parts' in sequence), and the latter going in the
generator, not distracting from the handling as may happen when you mix
the two things.  The business-logic part will always look like:

for pos, part in splitter(somestring, '/'):
# handle part, using pos as well

and the splitter generator is written elsewhere, a la

def splitter(somestring, separ):
while True:
pos = somestring.find(separ)
if pos == -1: break
yield pos, somestring[:pos]
somestring = somestring[pos+1:]

with the big advantage that you may change the implementation to be more
efficient, if and when needed, without touching the business logic part
which remains nestled in the nice, simple, readable for loop.

for example:

def splitter(somestring, separ):
pos = 0
while True:
nextpos = somestring.find(separ, pos)
if nextpos == -1: break
yield nextpos-pos, somestring[pos:nextpos]
pos = nextpos+1

Same semantics, less busywork, so presumably faster (the timeit module
exists to let you check the speed of code fragments, of course).


All this being said, I do sometimes find myself coding a first version
of some algorithm by following as closely as possible some published
reference code or pseudocode, before enhancing it to be clearer, more
efficient, more Pythonic, or whatever. When that happens, some syntax
sugar to assign and test in the same expression does come in handy, to
enable coding of a first version that's closer in spirit to the
non-Python reference version.

It was, of course, no trouble at all to make myself an assign and test
in the same expression snippet, and I (again, of course) published it
in the Python Cookbook (both online and printed editions) for others'
benefit. For example:

class Holder(object):
def set(self, value):
self.value = value
return value
data = Holder()

Now, with this tiny piece of plumbing adapter, you can code, e.g.:

while data.set(somestring.find(/)) != -1:
part = somestring[:data.value]
somestring = somestring[data.value + 1:]
# Handle part

Another use case for this Holder class is when you're using Python to
prototype something that you already know will need to be recoded in
another given language once it's ready -- the motivation is similar to
the one for the main use case of code as close as possible to a
published reference implementation, namely enabling Python code that is
closer to what's idiomatic in some other language than to idiomatic
Python itself.

Therein, of course, lies the danger -- over-relying on this adapter may
mean you never really learn to think the Python way and thus to code
idiomatic Python, even when that would be most appropriate (i.e., in
most cases). Still, Python _is_ a consenting adults language, so I
think it's appropriate to show how its power can easily let you keep
using idioms coming from different languages... even when that usage is
not the optimal choice that you could and should make, it's up to you.



Re: Random Prime Generator/Modular Arithmetic

2006-03-05 Thread Astan Chee
Also I think the snippet code [p for p in range(2,N) if 0 not in 
[pow(w,p-1,p)==1 for w in [2, 3, 5, 7, 11] if pw]] is probably nicer to 
generate a list of primes for up to N (instead of hard coded)
Aside from that looks nice.
Thanks

Tuvas wrote:

Yep, you guessed correctly about the s2num function, I knew I should
have put a bit more.. It just converts an ascii string to a number,
however many numbers that are nessicary. I could indeed check for all
primes below a certain number, however, it still seems to run quite
fast, at least to a 400 digit number. It's not something I'm going to
use a ton, so optimizing it might not be worth it much more than it is.
Perhaps I'll try all primes at least up to 100, that wouldn't be too
bad... Maybe I'll have to modify my old prime string to output the
python command to check all of them, it's a bit of a pain the whole if
0 in (n%2, n%3) stuff, and I can't think of a better way to do it
without writing a new function to do so.
I'm going to post the new code in just a minute, it's running quite
nicely. I'm also posting my RSA function, which I believe should be
secure enough. I'm uploading the code to them now, the HTML page'll be
a few minutes...

  

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


dual CPU-mode in python

2006-03-05 Thread Astan Chee
Hi,
I have a python script which i convert to an executeable (using py2exe) 
and on a dual-cpu machine seems to be taking only 50% (1cpu) only. I was 
wondering if there is a way to maximize CPU usage without forking the 
function?
Thanks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why I chose Python over Ruby

2006-03-05 Thread Sybren Stüvel
Francois wrote:

 I discovered Python a few months ago and soon decided to invest time
 in learning it well. While surfing the net for Python, I also saw
 the hype over Ruby and tried to find out more about it, before I
 definitely embarked on studying and practicing Python. I recently
 found two sufficient answers for choosing Python - which is a
 personal choice and others may differ, but I'd like to share it
 anyway

Thanks for sharing that. I had a gut feeling Python would be better
than Ruby, but I never took the time to study Ruby. Now I do have some
nice stones to throw at Ruby-fanatics ;-)

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


Re: Random Prime Generator/Modular Arithmetic

2006-03-05 Thread Tuvas
Actually, it wasn't very nice, it returned composites instead of
primes... There was alot of little bugs, I'm glad I checked it again.
The new code once again is uploaded, the previews are on their way... I
did set up a system to check for primality up to 1000, I think any more
than that and it will become conter-productive.

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


Re: Why I chose Python over Ruby

2006-03-05 Thread Alex Martelli
Francois [EMAIL PROTECTED] wrote:

 Since I did a lot of work in Scheme, rigor and consistency are most
 important to me, and Python certainly meets this requirement.

It does pretty well, with some tempering of pragmatism -- but, to play
devil's advocate, Ruby isn't far in this respect. In either case, you
will find more rigor and consistency in good languages of a more
academic bent, such as Haskell, but will surely find a lot in either
Ruby or Python.

The trick about distinguishing a name's exact nature based on whether
the compiler sees an assignment to that name in some part of code is
found in both languages, albeit in different ways. In Ruby, as you've
pointed out, it's the heuristic used to disambiguate local variable
access from zero-argument method calls, and the part of code is the
function up to the point of access. In Python, it's used to disambiguate
local from global or free variables, and the part of code is the body
of the whole function (Ruby does not need to make this latter
distinction because it strops global names with a leading sigil -- $a is
always the global variable a, just like @a is always the instance
attribute a, which we'd write self.a in Python). Another subtle case in
Ruby is whether an assignment such as a=23 _within a block_ is meant to
be local to the block or meant to rebind local name 'a' within the
enclosing function; again, the heuristic is similar, depending only on
whether the compiler had seen another assignment to a before it saw the
block (Python forbids the rebinding of variables coming from an
enclosing but non-global scope, to avoid facing this issue).

All in all, Python is more likely with these heuristics to respect the
principles (from the zen of python, import this at an interactive
prompt): in face of ambiguity, refuse the temptation to guess; errors
should not pass silently, unless explicitly silenced. I.e., any Python
code which accidentally runs afoul of these heuristics is likely to
raise an exception, alerting you to the situation. Ruby strives rather
for a do what I mean ethos, and obviously some people prefer that.

I also share your preference for a single namespace for callable and
non-callable values, as in Python (and Scheme, Lisp, C++, ...), rather
than disjoint namespaces as in Ruby (and Smalltalk), but I do not see it
as a question of rigor and consistency at all -- e.g., I do not perceive
Smalltalk as less rigorous or consistent than C++, on the contrary.

So, I agree with your choice, and I think I understand your motivations,
but I do not entirely share your motivations, personally speaking.


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


Re: Random Prime Generator/Modular Arithmetic

2006-03-05 Thread Tuvas
Although, I have to brag quickly, adding in this simple prime check
speed up the algorithm to the point that it's actually faster to find a
prime number with my program than to verify a number prime with
GP/PARI, so, I feel good.

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


Re: Inline assignments

2006-03-05 Thread Steven D'Aprano
On Sun, 05 Mar 2006 15:09:28 +0100, Fredrik Tolf wrote:

 Hi list!
 
 I'm relatively new to Python, and one thing I can't seem to get over is
 the lack of in-expression assignments, as present in many other
 languages. I'd really like to know how Python regulars solve the
 problems posed by that.

It is true that there is a whole class of bugs which Python code can't
duplicate because of the lack of in-expression assignments. Somehow
Python programmers manage to muddle along.


 For example, I recently wanted to do this:
 
 if callable(f = getattr(self, cmd_ + name)):
   # Do something with f
 elif callable(f = getattr(self, cmdv_ + name)):
   # Do something else with f
 
 However, since I can't do that in Python, I ended up using an extra
 local variable instead, like this:
 
 f = getattr(self, cmd_ + name)
 f2 = getattr(self, cmdv_ + name)
 if callable(f):
   # Do something with f
 elif callable(f2):
   # Do something with f2

Here is one way:

f = getattr(self, cmd_ + name)
if callable(f):
# Do something with f
else:
f = getattr(self, cmdv_ + name)
if callable(f):
# do something with f


Here is another:

def handle_func(*fs):
Do something with the first callable argument.
for f in fs:
if callable(f):
# do something with f
break

L = [getattr(self, s + name) for s in (cmd_, cmdv_)]
handle_func(L)


Here is a third:

L = map(lambda s, name=name: s+name, (cmd_, cmdv_))
L = map(lambda s, me=self: getattr(me, s), L)
L = filter(callable, L)
# do something with L[0]


Or if you are really nuts, you can convert that last one to a one-liner:

# do something with:-
filter(callable, map(lambda s, me=self: getattr(me, s), map(lambda s,
name=name: s+name, (cmd_, cmdv_[0]


Or possibly think about using a different algorithm, maybe something like
this:

class Dispatcher:
def f1(self): pass
def f2(self): pass

def __init__(self):
self.fmap = {cmd_name: self.f1, cmdv_name: self.f2}

def handle_func(self, s=name):
try:
f = self.fmap[cmd_+s]
except KeyError:
f = self.fmap[cmdv_+s]
f()  # or do something with f

Remember that functions and methods are first class objects, you may not
need to pass strings around, then convert the string to a function. Just
pass the function directly.


 
 Another common problem for me are while loops. I would often like to do
 this:
 while (pos = somestring.find(/)) != -1:
   part = somestring[:pos]
   somestring = somestring[pos + 1:]
   # Handle part


If you are splitting pathnames, you may be able to use os.path instead of
reinventing the wheel.

 
 However, that, too, is impossible, and I end up doing something like
 this:
 while True:
   pos = somestring.find(/)
   if pos == -1: break
   # ...
 
 Which is quite ugly. This might have been a bad example, since
 somestring.split() could be used instead, but it's still valid for other
 situations.

Such as?

Here is another way:

pos = somestring.find(/)
while pos != -1:
part = somestring[:pos]
somestring = somestring[pos + 1:]
# handle part

And another:

while True:
try:
pos = somestring.index(/)
except ValueError:
break
part = somestring[:pos]
somestring = somestring[pos + 1:]
# handle part


And a third:

start = 0
while True:
try:
pos = somestring.index(/, start)
except ValueError:
break
# handle somestring[start:pos]
start = pos + 1


If you are coming from a Java background, you may consider exceptions to
be a lot of work. In Python, setting up a try...except block is very
lightweight, so long as exceptions are rare. Hitting the except clause is
more work, so you should avoid that idiom if you expect the try to raise
an exception most of the time.



-- 
Steven.

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


Re: How to except the unexpected?

2006-03-05 Thread Scott David Daniels
Rene Pijlman wrote:
 Steven D'Aprano:
 The OP is doing it because catching all exceptions masks bugs. There are
 certain exceptions which should be allowed through, as they indicate a bug
 in the OP's code. Normally the tactic is to catch only the exceptions you
 are interested in, and let everything else through, but the OP needs to
 catch all exceptions because there are rare exceptions which he can't
 predict in advance.
 
 ... This is in a multithreaded ZODB-application
 When an unexpected exception occurs and remains uncaught, a thread
 terminates, 

At the base of the thread code, you could put

 import sys, threading, logging

 class MyThread(threading.Thread):
 def run(self):
 try:
 threading.Thread.run(self)  # or whatever
 except:
 etype, error, traceback = sys.exc_info()
 logging.warning('Exception %s: %s seen at %s' %
  (etype.__name__, error, _someformat_(traceback)))
 _try_to_rescue_or remove_this_thread_

If the condition is infrequent enough.  If not (if you run a real
risk of multiple threads accessing the log simultaneously), have
a queue of log messages that you feed to a single logging thread.

-- 
-Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: raw strings and \

2006-03-05 Thread plahey
Hi Duncan,

thanks for the reply.  I figured that this was a technical problem
associated with the parser.

This one is going on my Python gotchas list.  It is really silly from
an end user perspective to have \ not special in raw strings _except_
if it is the last character.

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


Re: lists: += vs. .append() oddness with scope of variables

2006-03-05 Thread Scott David Daniels
Duncan Booth wrote:
 Sandro Dentella wrote:
 
 I'd like to understand why += operator raises an error while .append()
 does not. My wild guess is the parses treats them differently but I
 cannot understand why this depends on scope of the variables (global
 or class variables):

 
 Any assignment to a variable within a function means that the name to which 
 you are assigning is regarded as a local variable (unless you use the 
 'global' statement to override that). += is a form of assignment, calling 
 the append method is not an assignment.
 
 The solution here is simply to use 'global a' to tell the compiler that you 
 meant to assign the the global variable rather than creating a new local 
 variable.

As Duncan knows but forgot to mention, eric.append(spam) doesn't write
the variable eric, it simply manipulates the object that eric names.

-- 
-Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


testing for existence of compilers/executables

2006-03-05 Thread John
I am working with my build system using scons. I would like
to test the existence of 'doxygen' or any other compiler/executable
in the path (like gcc/icc/...)

What is the most efficient way to find this out using python? using
scons?
Is there a way to list all C/C++/fortran compilers available on a
machine
using python so that I can give my user an option to select one?

Thanks a lot for your help,
--j

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


Re: Papers on Dynamic Languages

2006-03-05 Thread gene tani

Jay Parlar wrote:

 All that looks fantastic, and I'd forgotten there was a paper on
 Shedskin.

 Thanks a bunch,
 Jay P.

lots of spirited discussion at artima

http://www.artima.com/forums/flat.jsp?forum=106thread=7590
http://c2.com/cgi/wiki?DuckTyping
http://lambda-the-ultimate.org/node/1319

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


Re: dual CPU-mode in python

2006-03-05 Thread Steve Holden
Astan Chee wrote:
 Hi,
 I have a python script which i convert to an executeable (using py2exe) 
 and on a dual-cpu machine seems to be taking only 50% (1cpu) only. I was 
 wondering if there is a way to maximize CPU usage without forking the 
 function?
 Thanks

Python has a global interpreter lock (GIL) that inhibits parallelism. 
Certain extensions will clear the lock, but generally speaking you will 
need to generate multiple processes to take full advantage of parallel 
hardware.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd www.holdenweb.com
Love me, love my blog holdenweb.blogspot.com

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


Re: raw strings and \

2006-03-05 Thread Alex Martelli
[EMAIL PROTECTED] wrote:

 Hi Duncan,
 
 thanks for the reply.  I figured that this was a technical problem
 associated with the parser.
 
 This one is going on my Python gotchas list.  It is really silly from
 an end user perspective to have \ not special in raw strings _except_
 if it is the last character.

The alternative would have been to offer no way at all for a rawstring
to include its quoting-character. Since rawstrings were designed to
support regular expressions (which never need to end with a backslash),
that was considered a higher cost -- there is no real advantage to
supporting backslash-using Dos/Windows path literals, even though many
Windowsers use rawstrings for those.


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


Re: Random Prime Generator/Modular Arithmetic

2006-03-05 Thread Bryan Olson
Tuvas wrote:
 Okay, I don't know if your farmiliar with the miller-rabin primality
 test,

Paul is familiar with it. When he referred to your Miller-Rabin
test, he meant all the rounds.

  but it's what's called a probabalistic test. Meaning that trying
 it out once can give fake results.

In the sense that some composites will pass as prime for some
bases.


  For instance, if you use the number
 31 to test if 561 is prime, you will see the results say that it isn't.

That's not an instance of a fake result; Miller-Rabin has that
one right. When Miller-Rabin says a number is composite, it is
always correct.


Your current Miller-Rabin test, in

   http://www.geocities.com/brp13/Python/modular.html

in method Mod.is_strong_pseudo_prime(), looks buggy. Obviously
you want cut() not cut, and if 1: cannot fail. In my opinion,
the Mod class is not such a good idea; just use functions.


Note that Python has modular exponentiation built in.

pow(base, power, modulus)

with positive integer arguments will return base**power % modulus.


Finally, though most introductory crypto courses don't cover it,
RSA requires padding of the plaintext data. Google RSA + Padding
for more. Or ask on sci.crypt.


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


Re: raw strings and \

2006-03-05 Thread Blackbird
[EMAIL PROTECTED] wrote:
 Hi Duncan,

 thanks for the reply.  I figured that this was a technical problem
 associated with the parser.

 This one is going on my Python gotchas list.  It is really silly from
 an end user perspective to have \ not special in raw strings _except_
 if it is the last character.

But at the parsing stage, it *is* somewhat special, even if it is not the
last charater.  E.g,

a = r'check \' this'
print a

The second quote is not regarded as ending the string literal.




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


Re: raw strings and \

2006-03-05 Thread Steven D'Aprano
On Sun, 05 Mar 2006 08:27:31 -0800, plahey wrote:

 Hi Duncan,
 
 thanks for the reply.  I figured that this was a technical problem
 associated with the parser.
 
 This one is going on my Python gotchas list.  It is really silly from
 an end user perspective to have \ not special in raw strings _except_
 if it is the last character.

I don't deny that this is a gotcha, but you misunderstand the purpose of
raw strings. They weren't designed so that Windows users could enter
pathnames with backslashes. Raw strings are designed to enter regular
expressions, and for regular expressions, not being able to end a string
with a backslash is not a bug but a feature.

See http://www.ferg.org/projects/python_gotchas.html#contents_item_2

(and try not to choke on the oh-so-saccharine-sweet cutesy introduction.
Red Ridinghood indeed *wink*)


-- 
Steven.

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


Re: How to except the unexpected?

2006-03-05 Thread plahey
Yes, and that's the Right Thing(tm) to do. Source code don't lie. Source
  code don't get out of sync. So source code *is* the best documentation
(or at least the most accurate).

I could not disagree more strongly with this.  Not just no, but hell
no!

Yes, and that's the Right Thing(tm) to do.

No, it is a horrible thing to do.  But since the documentation of some
modules is just plain horrible we sometimes have no choice.

 Source code don't lie.  Source code don't get out of sync.

True but implementation details change from release to release.

 So source code *is* the best documentation (or at least the most accurate).

No, source code is the *worst possible* documentation because it makes
no distinction between implementation detail and method contract.  If
the implementer considers the implementation to be the documentation
then his/her refactoring options are significantly reduced.  Typically
implementers are not aware of this and they refactor anyway, breaking
client code left and right.

The C++ FAQ has a nice discussion of this issue.  Minimally acceptable
documentation consists of the following (I think this is language
independent):

PURPOSE: What does this method/function do
REQUIRE: pre-conditions - What must have happened before calling this
method (or restrictions on the domain of the inputs)
PROMISE: post-conditions - What can you expect upon return or what
exceptions can be thrown

I consider the above to be the minimal amount of documentation that is
acceptable.  If you have less than that, I consider the method to be
undocumented.  Needless to say, I consider lots of code that I see to
be undocumented.

If you don't have the above, you get the problems that OP was hitting
(or worse, see the C++ FAQ).  I am not a huge fan of Java's ubiquitous
use of checked exceptions or even of static typing but it does help
supply some of the above documentation (although in a suboptimal way)
that must be supplied by hand in Python.  This is the dirty little
secret of dynamically typed languages.  It makes proper documentation
even more important because method signatures supply less information.

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


Re: dual CPU-mode in python

2006-03-05 Thread Fredrik Lundh
Astan Chee wrote:

 I have a python script which i convert to an executeable (using py2exe)
 and on a dual-cpu machine seems to be taking only 50% (1cpu) only. I was
 wondering if there is a way to maximize CPU usage without forking the
 function?

it depends on what your script is doing.  the GIL makes it impossible to
use more than one CPU per process for byte code intensive code:

http://docs.python.org/api/threads.html

but code that uses I/O or C-level crunching can get around this, if the
C-level code is properly written.

/F



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


Re: raw strings and \

2006-03-05 Thread plahey
Hi,

thanks for the reply.  I was not aware of this in raw strings (and
frankly, don't like it... but who cares about that :-) )

When I needed embedded quotes in a raw string I went the triple quote
route:

a = r'''check \' this'''

which makes more sense to me.

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


Re: raw strings and \

2006-03-05 Thread plahey
Hi Alex,

thanks for the reply.  I can see that there is a choice that needed to
be made.  Before I was aware of the \ issue I just used (yes it has
come up, but the example is at work) triple quotes to work around the
embedded quote issue:

x=r'''It's like this c:\blah\ ok?'''
print x
It's like this c:\blah\ ok?

Am I missing something?

I guess my point is that it is quite surprising that r'\' is not a
legal way to represent a backslash.  I look for consistency in the
tools that I work with and this except-for-the-last-character exception
is annoying (I admit it might be a silly use-case but consistency is
consistency).

Again, thanks for taking the time to reply.

Now get back to work on your new Nutshell book :-)

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


Re: raw strings and \

2006-03-05 Thread plahey
Hi Steven,

thanks for the reply.  I was/am aware that raw strings are mainly used
for regular expressions (and franky that was I usually use them for).
I was not aware that they still have special powers in raw strings
(thanks for the link!).

This one bit me when I was doing some quick and dirty hacking and a 5
minute task ended up being a much longer adventure becuase of this
(Note to self:  don't post when annoyed).

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


Re: Why I chose Python over Ruby

2006-03-05 Thread Francois
Alex Martelli wrote:

 I also share your preference for a single namespace for callable and
 non-callable values, as in Python (and Scheme, Lisp, C++, ...), rather
 than disjoint namespaces as in Ruby (and Smalltalk), but I do not see it
 as a question of rigor and consistency at all -- e.g., I do not perceive
 Smalltalk as less rigorous or consistent than C++, on the contrary.

 So, I agree with your choice, and I think I understand your motivations,
 but I do not entirely share your motivations, personally speaking.


Thanks Alex for your excellent explanations. I have the Python Cookbook
2nd Ed., and I highly appreciate your knowledge and experience.

I guess my choice of words rigor and consistency was not very good.
In this context rigor meant enforcing rules (for example having to
use parentheses to call a method) to prevent ambiguity rather than
depending on heuristics. Also consistency meant doing things as
uniformly as possible (for example always call a method with the same
syntax, whether the variable referencing it is the original name or an
alias).

-- Francois

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


Re: Why I chose Python over Ruby

2006-03-05 Thread [EMAIL PROTECTED]

Francois wrote:
 I discovered Python a few months ago and soon decided to invest time in
 learning it well. While surfing the net for Python, I also saw the hype
 over Ruby and tried to find out more about it, before I definitely
 embarked on studying and practicing Python. I recently found two
 sufficient answers for choosing Python - which is a personal choice and
 others may differ, but I'd like to share it anyway :

 1) In Ruby there is a risk of Variable/Method Ambiguity when calling
 a method with no parameters without using () :
snip

 2) Ruby does not have true first-class functions living in the same
 namespace as other variables while Python does :
snip

 4) Conclusion
snip

 Since I did a lot of work in Scheme, rigor and consistency are most
 important to me,

What happened to 3)?

and Python certainly meets this requirement.
 
 --- Python newbie

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


Re: Why I chose Python over Ruby

2006-03-05 Thread Francois
[EMAIL PROTECTED] wrote:
 What happened to 3)?

4) should have read 3). I found the typo after I posted. I guess I
lack rigor myself !

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


Re: dual CPU-mode in python

2006-03-05 Thread Rene Pijlman
Astan Chee:
I was wondering if there is a way to maximize CPU usage

Fork a Java app :-)

-- 
René Pijlman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python advocacy in scientific computation

2006-03-05 Thread sturlamolden

Robert Kern wrote:

 1. Write grant proposals.

 2. Advise and teach students.

Sorry I forgot the part about writing grant applications. As for
teaching students, I have thankfully not been bothered with that too
much.



 Yes, and this is why you will keep saying, My simulation is running too
 slowly, and My simulation is running out of memory. All the vectorization 
 you
 do won't make a quadratic algorithm run in O(n log(n)) time. Knowing the right
 algorithm and the right data structures to use will save you programming time
 and execution time. Time is money, remember, and every hour you spend tweaking
 Matlab code to get an extra 5% of speed is just so much grant money down the 
 drain.

Yes, and that is why I use C (that is ISO C99, not ANSI C98) instead of
Matlab for everything except trivial tasks. The design of Matlab's
language is fundamentally flawed. I once wrote a tutorial on how to
implement things like lists and trees in Matlab (using functional
programming, e.g. using functions to represent list nodes), but it's
just a toy. And as Matlab's run-time does reference counting insted of
proper garbage collection, any datastructure more complex than arrays
are sure to leak memory (I believe Python also suffered from this as
some point). Matlab is not useful for anything except plotting data
quickly. And as for the expensive license, I am not sure its worth it.
I have been considering a move to Scilab for some time, but it too
carries the burden of working with a flawed language.

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


Python version of XMLUnit?

2006-03-05 Thread Kent Johnson
I have found XMLUnit to be very helpful for testing Java and Jython code 
that generates XML. At its heart XMLUnit is an XML-aware diff - it 
parses expected and actual XML and pinpoints any differences. It is 
smart enough to ignore things like attribute order, different quoting 
and escaping styles, and insignificant whitespace.

Now I am working on a CPython project and have a similar need. Is there 
any comparable tool for Python? Basically I'm looking for a tool to 
compare XML and show diffs in an intelligible fashion that is usable 
from Python unit tests (using py.test, if it matters).

Thanks,
Kent

http://xmlunit.sourceforge.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python advocacy in scientific computation

2006-03-05 Thread sturlamolden

David Treadwell wrote:

 My ability to think  of data structures was stunted BECAUSE of
 Fortran and BASIC. It's very difficult for me to give up my bottom-up
 programming style, even though I write better, clearer and more
 useful code when I write top-down.


That is also the case with Matlab, anything mor complex than an array
is beyond reach.

I think it was Paul Graham (the LISP guru) once claimed he did not miss
recursive functions while working with Fortran 77. The limitations of a
language does stunt your mind. To that extent I am happy I learned to
program with Pascal and not Fortran or Matlab.

S.M.

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


Re: is there such a built-in funciton, similar to filter

2006-03-05 Thread Terry Reedy

Michael Hoffman [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 wcc wrote:

 Beginner learning Python here.  I know filter(lambda x: x  3, [1, 2,
 5, -3, 4, 8]) will give me a list [5, 4, 8].  What if I only need to
 find the first item in the list that returns Ture when applying the
 filter function.  In this case, I only want to get the 5, and its index

You have made two important changes to the function return value.
Filter returns a list of items.  You want an item and index.
What if there is no first item?

 2.  Is there a built-in function, or function from a module for that?
 I think it is not hard to write a function for this.  But knowing
 Python is battery included, I thought I'd like to ask.

A 'battery' is something like the email, html, xml modules that assist 
major application areas.  Not every easily written 3-line function ;-)

 You can use a generator expression like this:

  items = [1, 2, 5, -3, 4, 8]
  ((index, item) for index, item in enumerate(items) if item  
  3).next()
 (2, 5)

 items = [0,1,2,3]
 ((index, item) for index, item in enumerate(items) if item  3).next()

Traceback (most recent call last):
  File pyshell#82, line 1, in -toplevel-
((index, item) for index, item in enumerate(items) if item  3).next()
StopIteration

I believe ifilter from the itertools module will act the same.

Terry Jan Reedy




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


Re: Random Prime Generator/Modular Arithmetic

2006-03-05 Thread Tuvas
Bryan Olson wrote:
 Tuvas wrote:
  Okay, I don't know if your farmiliar with the miller-rabin primality
  test,

 Paul is familiar with it. When he referred to your Miller-Rabin
 test, he meant all the rounds.

   but it's what's called a probabalistic test. Meaning that trying
  it out once can give fake results.

 In the sense that some composites will pass as prime for some
 bases.


   For instance, if you use the number
  31 to test if 561 is prime, you will see the results say that it isn't.

 That's not an instance of a fake result; Miller-Rabin has that
 one right. When Miller-Rabin says a number is composite, it is
 always correct.

I mis-stated. If you try 31 in the Miller-Rabin test.

Mod(31,561).is_strong_pseudo_prime()
True

However, 561 is not prime, it is divisible by 3, 11, and 17.

Actually, I did another test, and realized that it was indeed a bug in
the code. Yikes. Oh well, thanks for the help in identifying it!

An example that would be alot easier is this:
Mod(16,561).is_strong_pseudo_prime()
True



 Your current Miller-Rabin test, in

http://www.geocities.com/brp13/Python/modular.html

 in method Mod.is_strong_pseudo_prime(), looks buggy. Obviously
 you want cut() not cut, and if 1: cannot fail. In my opinion,
 the Mod class is not such a good idea; just use functions.


The reason for the modulos class, well, was more of a practice than
anything else.

I could indeed just use functions, but I needed the Mod class for a few
other things, and figured it was just easier to program it once and use
it for anything rather than anything else.


 Note that Python has modular exponentiation built in.

 pow(base, power, modulus)


Nice to see that Python supports modular exponentiation. I'll have to
remember that one. Probably the next time I do an update to the code,
I'll just use it instead, it's probably faster than mine.


 with positive integer arguments will return base**power % modulus.


 Finally, though most introductory crypto courses don't cover it,
 RSA requires padding of the plaintext data. Google RSA + Padding
 for more. Or ask on sci.crypt.


 --
 --Bryan

Overall, I guess another update is coming soon. Thanks for the help in
debuging again!

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


Re: Why I chose Python over Ruby

2006-03-05 Thread Francois
Alex Martelli wrote:

 I also share your preference for a single namespace for callable and
 non-callable values, as in Python (and Scheme, Lisp, C++, ...), rather
 than disjoint namespaces as in Ruby (and Smalltalk), but I do not see it
 as a question of rigor and consistency at all -- e.g., I do not perceive
 Smalltalk as less rigorous or consistent than C++, on the contrary.

 So, I agree with your choice, and I think I understand your motivations,
 but I do not entirely share your motivations, personally speaking.


Thanks Alex for your excellent explanations. I have the Python Cookbook
2nd Ed., and I highly appreciate your knowledge and experience.

I guess my choice of words rigor and consistency was not very good.
In this context rigor meant enforcing rules (for example having to
use parentheses to call a function) to prevent ambiguity rather than
depending on heuristics. Also consistency meant doing things as
uniformly as possible (for example always call a function with the same
syntax, whether the variable referencing it is the original name or an
alias).

-- Francois

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


Re: Python advocacy in scientific computation

2006-03-05 Thread Michael Tobis
   $ rm `find . -name *.pyc`

Ouch. Is that a true story?

While we're remeniscing about bad typos and DEC, I should tell the
story about the guy who clobberred his work because his English wasn't
very strong.

Under RT-11, all file management was handled by a program called PIP.
For example to get a list of files in the current working directory you
would enter PIP *.* /LI . Well this fellow, from one of those countries
where our long e sound is their i sound, mournfully announced

I vanted a deerectory so I typed 'PIP *.* /DE' 

That one is true.

mt

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


what am I missing (syntax error)

2006-03-05 Thread orangeDinosaur
Here's  a section of code:

for x in occupants:
if x not in uniqueUsers and not in staff: 
uniqueUsers.append(x)
elif x in staff and not in uniqueStaff: 
uniqueStaff.append(x)

When I try to import the module with the function definition that
contains this code, I get a syntax error pointing to the 'in' after the
'and not in staff'.  I can't figure out why this is bad syntax.  Both
'uniqueUsers' and 'staff' are lists.  

thanks for your help!

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


Re: lists: += vs. .append() oddness with scope of variables

2006-03-05 Thread Terry Reedy

Sandro Dentella [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 I'd like to understand why += operator raises an error while .append() 
 does
 not.

Your mistake is thinking of '+=' as an operator.  In Python terms it is 
not, any more than '=' is.  In Python, neither 'a=b' nor 'a+=b' is an 
expression.  Both symbols are statement symbols that define assigment 
statements (augmented in the former case).  a.append(b) is an expression 
with side effects used as a statement.

 Traceback (most recent call last):
  File c1.py, line 26, in ?
x = foo()
  File c1.py, line 7, in __init__
print a: , a
 UnboundLocalError: local variable 'a' referenced before assignment

This is the clue that you did not get.  It tells you that the parser thinks 
'a' is local, which means you rebound the name 'a' *somewhere* in the 
function, even if not as obviously as a simple assignment a = whatever. 
It turns out that augmented assignment statements are assignments 
statements ;-).

Terry Jan Reedy



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


Re: raw strings and \

2006-03-05 Thread Alex Martelli
[EMAIL PROTECTED] wrote:

 thanks for the reply.  I can see that there is a choice that needed to
 be made.  Before I was aware of the \ issue I just used (yes it has
 come up, but the example is at work) triple quotes to work around the
 embedded quote issue:
 
 x=r'''It's like this c:\blah\ ok?'''
 print x
 It's like this c:\blah\ ok?
 
 Am I missing something?

No, triplequotes are perfectly valid.

 I guess my point is that it is quite surprising that r'\' is not a
 legal way to represent a backslash.  I look for consistency in the
 tools that I work with and this except-for-the-last-character exception
 is annoying (I admit it might be a silly use-case but consistency is
 consistency).

Alas, somebody will now quote Emerson at you, I fear;-).  Me, I
appreciate consistency and regularity more than most (without making a
fetish of it), but the rule a rawstring cannot end with an odd number
of backslashes is perfectly regular and consistent, so I'm not
perturbed by it (it's NOT about the last character, as r'\\' is just
fine even though its last character is a \ -- it's about the parity of
the length of the terminating sequence of backslashes: even is OK [0 is
of course even;-)] and odd is not).

 Again, thanks for taking the time to reply.
 
 Now get back to work on your new Nutshell book :-)

Yep, good point!-)


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


Re: Why I chose Python over Ruby

2006-03-05 Thread Alex Martelli
Francois [EMAIL PROTECTED] wrote:
   ...
 I guess my choice of words rigor and consistency was not very good.
 In this context rigor meant enforcing rules (for example having to
 use parentheses to call a method) to prevent ambiguity rather than
 depending on heuristics. Also consistency meant doing things as
 uniformly as possible (for example always call a method with the same
 syntax, whether the variable referencing it is the original name or an
 alias).

Ah yes, these are definitely valid nuances for the terms you've used, I
admit that.  Python's yearning for only one obvious way to do
something, even though it's a goal to aim for rather than a reality in
every case, surely does play towards these preferences, while Ruby (not
quite as much as Perl, but still) has a more exhuberant approach, where
having multiple obvious ways to do the same thing is seen as a plus, not
a minus (a classic tiny example is the ability to get the number of
items of an array a by EITHER a.size or a.length, just like for a C++
std::string, with no difference whatsoever among the two synonyms).

So, I'm NOT saying your word choice was not very good: you used words
who do mean what you intend (among other meanings, but then, that's the
curse AND blessing of natural language;-).  But anyway, thanks for the
clarification!  Maybe uniformity (though it, too, may suggest
different and not accurate things) could be usefully added to help
communicate your intended meaning (or maybe, for most people, if they
hear all of rigor, consistency, uniformity, would think of some Nazi
language woefully constraining their expression...?-)


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


Re: Why I chose Python over Ruby

2006-03-05 Thread Alex Martelli
[EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
   ...
  1) In Ruby there is a risk of Variable/Method Ambiguity when calling
   ...
  2) Ruby does not have true first-class functions living in the same
   ...
  4) Conclusion
   ...
 What happened to 3)?

I thought the OP was counting up by powers of 2 to indicate the
exponential nature of the issues...;-)


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


Re: Python advocacy in scientific computation

2006-03-05 Thread Robert Kern
Michael Tobis wrote:
  $ rm `find . -name *.pyc`
 
 Ouch. Is that a true story?

Yup. Fortunately, it was a small, purely personal project, so it was no huge
loss. It was enough for me to start using CVS on my small, purely personal
projects, though!

-- 
Robert Kern
[EMAIL PROTECTED]

I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth.
  -- Umberto Eco

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


Re: what am I missing (syntax error)

2006-03-05 Thread James Thiele
Try:
for x in occupants:
if x not in uniqueUsers and x not in staff:
uniqueUsers.append(x)
elif x in staff and x not in uniqueStaff:
uniqueStaff.append(x)

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


Re: what am I missing (syntax error)

2006-03-05 Thread Alex Martelli
orangeDinosaur [EMAIL PROTECTED] wrote:

 Here's  a section of code:
 
 for x in occupants:
   if x not in uniqueUsers and not in staff: uniqueUsers.append(x)
   elif x in staff and not in uniqueStaff: uniqueStaff.append(x)
 
 When I try to import the module with the function definition that
 contains this code, I get a syntax error pointing to the 'in' after the
 'and not in staff'.  I can't figure out why this is bad syntax.  Both
 'uniqueUsers' and 'staff' are lists.  

say ...'and x not in staff' -- you need the x between 'and' and 'not',
and similarly for the elif (and don't use tabs -- they make a mess of a
display on many newsreaders etc -- fixed to spaces above).


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


Re: what am I missing (syntax error)

2006-03-05 Thread Gerard Flanagan

orangeDinosaur wrote:
 Here's  a section of code:

 for x in occupants:
   if x not in uniqueUsers and not in staff: 
 uniqueUsers.append(x)
   elif x in staff and not in uniqueStaff: 
 uniqueStaff.append(x)

 When I try to import the module with the function definition that
 contains this code, I get a syntax error pointing to the 'in' after the
 'and not in staff'.  I can't figure out why this is bad syntax.  Both
 'uniqueUsers' and 'staff' are lists.

 thanks for your help!

I think you're missing an 'x':

for x in occupants:
if x not in Users and x not in Staff:
Users.append(x)

Gerard

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


Re: what am I missing (syntax error)

2006-03-05 Thread Jorge Godoy
orangeDinosaur [EMAIL PROTECTED] writes:

 Here's  a section of code:

 for x in occupants:
   if x not in uniqueUsers and not in staff: 
 uniqueUsers.append(x)
   elif x in staff and not in uniqueStaff: 
 uniqueStaff.append(x)

 When I try to import the module with the function definition that
 contains this code, I get a syntax error pointing to the 'in' after the
 'and not in staff'.  I can't figure out why this is bad syntax.  Both
 'uniqueUsers' and 'staff' are lists.  

The question is: what's not in XXX?  x?  Something else?  You hve to
remember that the computer does only what you tell it to do:

if x not in uniqueUsers and x not in staff: ...

I also prefer using parenthesis to make things more clear and avoid precedence
surprises. 

-- 
Jorge Godoy  [EMAIL PROTECTED]

Quidquid latine dictum sit, altum sonatur.
- Qualquer coisa dita em latim soa profundo.
- Anything said in Latin sounds smart.
-- 
http://mail.python.org/mailman/listinfo/python-list


beginner question on dinamin buiding of arg list

2006-03-05 Thread Sandro Dentella

I need to build-up an arg list to pass to a function. 

Suppose I have a dictionary:

  opts = { 'user' : 'jack', 'addr' : 'Green Str.'}

and I want to build a cmd line like this:

  select( user='jack', addr='Green Str.' )

I'm clueless...

TIA
sandro
*:-)


-- 
Sandro Dentella  *:-)
http://www.tksql.orgTkSQL Home page - My GPL work
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python advocacy in scientific computation

2006-03-05 Thread Alex Martelli
sturlamolden [EMAIL PROTECTED] wrote:

 just a toy. And as Matlab's run-time does reference counting insted of
 proper garbage collection, any datastructure more complex than arrays
 are sure to leak memory (I believe Python also suffered from this as
 some point).

Yes, that was fixed in the move from 1.5.2 to 2.0 (I don't recall if the
intermediate short-lived 1.6 also fixed it, but nobody used that
anyway;-).

 Matlab is not useful for anything except plotting data
 quickly. And as for the expensive license, I am not sure its worth it.
 I have been considering a move to Scilab for some time, but it too
 carries the burden of working with a flawed language.

There was a pyscilab once, still around at
http://pdilib.sourceforge.net/, but I don't think it ever matured
beyond a proof of concept release 0.1 or something.


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


Re: beginner question on dinamin buiding of arg list

2006-03-05 Thread Alex Martelli
Sandro Dentella [EMAIL PROTECTED] wrote:

 I need to build-up an arg list to pass to a function. 
 
 Suppose I have a dictionary:
 
   opts = { 'user' : 'jack', 'addr' : 'Green Str.'}
 
 and I want to build a cmd line like this:
 
   select( user='jack', addr='Green Str.' )

select(**opts)

should fit the bill.  (it.comp.lang.python is the Italian newsgroup
about Python, by the way;-).


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


Re: what am I missing (syntax error)

2006-03-05 Thread orangeDinosaur
OK, thanks!

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


Re: Python advocacy in scientific computation

2006-03-05 Thread Robert Kern
Brian Blais wrote:
 Robert Kern wrote:
 
That said, we have an excellent array object far superior to Matlab's.

  http://numeric.scipy.org/
 
 I'd like to ask, being new to python, in which ways is this array object far 
 superior
 to Matlab's?  (I'm not being sarcastic, I really would like to know!)

Matlab takes the view that everything is a rank-2 matrix of floating point 
values.

Our arrays have been N-dimensional since day one. They really are arrays, not
matrices. You have complete control over the types.

-- 
Robert Kern
[EMAIL PROTECTED]

I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth.
  -- Umberto Eco

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


Separating elements from a list according to preceding element

2006-03-05 Thread Rob Cowie
I'm having a bit of trouble with this so any help would be gratefully
recieved...

After splitting up a url I have a string of the form
'tag1+tag2+tag3-tag4', or '-tag1-tag2' etc. The first tag will only be
preceeded by an operator if it is a '-', if it is preceded by nothing,
'+' is to be assumed.

Using re.split, I can generate a list that looks thus:
['tag1', '+', 'tag2', '+', 'tag3', '-', 'tag4']

I wish to derive two lists - each containing either tags to be
included, or tags to be excluded. My idea was to take an element,
examine what element precedes it and accordingly, insert it into the
relevant list. However, I have not been successful.

Is there a better way that I have not considered? If this method is
suitable, how might I implement it?

Thanks all,

Rob Cowie

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


Re: Python advocacy in scientific computation

2006-03-05 Thread Robert Kern
sturlamolden wrote:
 Robert Kern wrote:

Yes, and this is why you will keep saying, My simulation is running too
slowly, and My simulation is running out of memory. All the vectorization 
you
do won't make a quadratic algorithm run in O(n log(n)) time. Knowing the right
algorithm and the right data structures to use will save you programming time
and execution time. Time is money, remember, and every hour you spend tweaking
Matlab code to get an extra 5% of speed is just so much grant money down the 
drain.
 
 Yes, and that is why I use C (that is ISO C99, not ANSI C98) instead of
 Matlab for everything except trivial tasks. The design of Matlab's
 language is fundamentally flawed. I once wrote a tutorial on how to
 implement things like lists and trees in Matlab (using functional
 programming, e.g. using functions to represent list nodes), but it's
 just a toy. And as Matlab's run-time does reference counting insted of
 proper garbage collection, any datastructure more complex than arrays
 are sure to leak memory (I believe Python also suffered from this as
 some point).

Python still uses reference counting and has several very good data structures
more complex than arrays. And yet, most programs don't leak memory.

 Matlab is not useful for anything except plotting data
 quickly. And as for the expensive license, I am not sure its worth it.
 I have been considering a move to Scilab for some time, but it too
 carries the burden of working with a flawed language.

And you need to ask why Python is a better Matlab than Matlab?

-- 
Robert Kern
[EMAIL PROTECTED]

I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth.
  -- Umberto Eco

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


Re: django and mod_python

2006-03-05 Thread tgone
your suggestions worked. thanks.

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


Re: Separating elements from a list according to preceding element

2006-03-05 Thread Gerard Flanagan

Rob Cowie wrote:
 I'm having a bit of trouble with this so any help would be gratefully
 recieved...

 After splitting up a url I have a string of the form
 'tag1+tag2+tag3-tag4', or '-tag1-tag2' etc. The first tag will only be
 preceeded by an operator if it is a '-', if it is preceded by nothing,
 '+' is to be assumed.

 Using re.split, I can generate a list that looks thus:
 ['tag1', '+', 'tag2', '+', 'tag3', '-', 'tag4']

 I wish to derive two lists - each containing either tags to be
 included, or tags to be excluded. My idea was to take an element,
 examine what element precedes it and accordingly, insert it into the
 relevant list. However, I have not been successful.

 Is there a better way that I have not considered? If this method is
 suitable, how might I implement it?

 Thanks all,

 Rob Cowie

a = [ '+', 'tag1', '+', 'tag2', '-', 'tag3', '+', 'tag4' ]

import itertools

b = list(itertools.islice(a,0,8,2))
c = list(itertools.islice(a,1,8,2))

result1 = [x[1] for x in itertools.izip(b,c) if x[0] == '+']
result2 = [x[1] for x in itertools.izip(b,c) if x[0] == '-']

print
print result1
print result2


Gerard

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


Re: Separating elements from a list according to preceding element

2006-03-05 Thread Ben Cartwright
Rob Cowie wrote:
 I wish to derive two lists - each containing either tags to be
 included, or tags to be excluded. My idea was to take an element,
 examine what element precedes it and accordingly, insert it into the
 relevant list. However, I have not been successful.

 Is there a better way that I have not considered?

Maybe.  You could write a couple regexes, one to find the included
tags, and one for the excluded, then run re.findall on them both.

But there's nothing fundamentally wrong with your method.

 If this method is
 suitable, how might I implement it?

  tags = ['tag1', '+', 'tag2', '+', 'tag3', '-', 'tag4']

  include, exclude = [], []
  op = '+'
  for cur in tags:
  if cur in '+-':
  op = cur
  else:
  if op == '+':
  include.append(cur)
  else:
  exclude.append(cur)

--Ben

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


Re: Separating elements from a list according to preceding element

2006-03-05 Thread Gerard Flanagan

Gerard Flanagan wrote:
 Rob Cowie wrote:
  I'm having a bit of trouble with this so any help would be gratefully
  recieved...
 
  After splitting up a url I have a string of the form
  'tag1+tag2+tag3-tag4', or '-tag1-tag2' etc. The first tag will only be
  preceeded by an operator if it is a '-', if it is preceded by nothing,
  '+' is to be assumed.
 
  Using re.split, I can generate a list that looks thus:
  ['tag1', '+', 'tag2', '+', 'tag3', '-', 'tag4']
 
  I wish to derive two lists - each containing either tags to be
  included, or tags to be excluded. My idea was to take an element,
  examine what element precedes it and accordingly, insert it into the
  relevant list. However, I have not been successful.
 
  Is there a better way that I have not considered? If this method is
  suitable, how might I implement it?
 
  Thanks all,
 
  Rob Cowie

 a = [ '+', 'tag1', '+', 'tag2', '-', 'tag3', '+', 'tag4' ]

 import itertools

 b = list(itertools.islice(a,0,8,2))
 c = list(itertools.islice(a,1,8,2))

 result1 = [x[1] for x in itertools.izip(b,c) if x[0] == '+']
 result2 = [x[1] for x in itertools.izip(b,c) if x[0] == '-']

 print
 print result1
 print result2
 
 
 Gerard

  '8' is the length of 'a'  (len(a))

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


Re: Python advocacy in scientific computation

2006-03-05 Thread sturlamolden
Robert Kern wrote:

 And you need to ask why Python is a better Matlab than Matlab?


First there are a few things I don't like:

1. Intendation as a part of the syntax, really annoying.

2. The self.something syntax is really tedious (look to ruby)!

4. Multithreading and parallel execution is impossible AFAIK because of
the so-called GIL (global interpreter lock). Matlab is perhaps even
worse in this respect.

5. I don't like numpy's array slicing. Array operations should be a
part of the language, as in Matlab, Fortran 90, Ada 95, D, Octave.


And there is a couple of questions I need answered:

1. Can python do pass by reference? Are datastructures represented by
references as in Java (I don't know yet).

2. How good is matplotlib/pylab? I tried to install it but only get
error messages so I haven't tested it. But plotting capabilities is
really major issue.

3. Speed. I haven't seen any performance benchmarks that actually deals
with things that are important for scientific programs.

4. Are there easy to use libraries containing other stuff important
for scientific programs, e.q. linear algebra (LU, SVD, Cholesky),
Fourier transforms, etc. E.g. in Matlab I can just type,

   [u,s,v] = svd(x) % which calls LAPACK linked to ATLAS or
vendor-optimized BLAS

Even though the language itself is very limited this type of library
functionality more than makes up for it.


I have looked for alternatives to Matlab for quite a while, mainly due
to the cost, the åpoor speed and poor memory management. I am not sure
it is Python but so far I have not found anything mor promising either.

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


Re: Separating elements from a list according to preceding element

2006-03-05 Thread James Stroud
Rob Cowie wrote:
 I'm having a bit of trouble with this so any help would be gratefully
 recieved...
 
 After splitting up a url I have a string of the form
 'tag1+tag2+tag3-tag4', or '-tag1-tag2' etc. The first tag will only be
 preceeded by an operator if it is a '-', if it is preceded by nothing,
 '+' is to be assumed.
 
 Using re.split, I can generate a list that looks thus:
 ['tag1', '+', 'tag2', '+', 'tag3', '-', 'tag4']
 
 I wish to derive two lists - each containing either tags to be
 included, or tags to be excluded. My idea was to take an element,
 examine what element precedes it and accordingly, insert it into the
 relevant list. However, I have not been successful.
 
 Is there a better way that I have not considered? If this method is
 suitable, how might I implement it?
 
 Thanks all,
 
 Rob Cowie
 

Unclever way:

alist = ['tag1', '+', 'tag2', '+', 'tag3', '-', 'tag4']
include, disinclude = [], []
aniter = iter(alist)
if len(alist) % 2:
   include.append(aniter.next())
for asign in aniter:
   if asign == '+':
 include.append(aniter.next())
   else:
 disinclude.append(aniter.next())

A cleverer way will probably use list comprehension and logic shortcutting.

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


Re: Separating elements from a list according to preceding element

2006-03-05 Thread James Stroud
Gerard Flanagan wrote:
 Rob Cowie wrote:
 
I'm having a bit of trouble with this so any help would be gratefully
recieved...

After splitting up a url I have a string of the form
'tag1+tag2+tag3-tag4', or '-tag1-tag2' etc. The first tag will only be
preceeded by an operator if it is a '-', if it is preceded by nothing,
'+' is to be assumed.

Using re.split, I can generate a list that looks thus:
['tag1', '+', 'tag2', '+', 'tag3', '-', 'tag4']

I wish to derive two lists - each containing either tags to be
included, or tags to be excluded. My idea was to take an element,
examine what element precedes it and accordingly, insert it into the
relevant list. However, I have not been successful.

Is there a better way that I have not considered? If this method is
suitable, how might I implement it?

Thanks all,

Rob Cowie
 
 
 a = [ '+', 'tag1', '+', 'tag2', '-', 'tag3', '+', 'tag4' ]
 
 import itertools
 
 b = list(itertools.islice(a,0,8,2))
 c = list(itertools.islice(a,1,8,2))
 
 result1 = [x[1] for x in itertools.izip(b,c) if x[0] == '+']
 result2 = [x[1] for x in itertools.izip(b,c) if x[0] == '-']
 
 print
 print result1
 print result2
 
 
 Gerard
 

Unfortunately this does not address the complete specification:

  a = [ 'tag1', '+', 'tag2', '-', 'tag3', '+', 'tag4' ]
 
  import itertools
 
  b = list(itertools.islice(a,0,len(a),2))
  c = list(itertools.islice(a,1,len(a),2))
 
  result1 = [x[1] for x in itertools.izip(b,c) if x[0] == '+']
  result2 = [x[1] for x in itertools.izip(b,c) if x[0] == '-']
 
  print

  print result1
[]
  print result2
[]

Need to check for the absence of that first op.

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


Re: Separating elements from a list according to preceding element

2006-03-05 Thread Bruno Desthuilliers
Rob Cowie a écrit :
 I'm having a bit of trouble with this so any help would be gratefully
 recieved...
 
 After splitting up a url I have a string of the form
 'tag1+tag2+tag3-tag4', or '-tag1-tag2' etc. The first tag will only be
 preceeded by an operator if it is a '-', if it is preceded by nothing,
 '+' is to be assumed.
 
 Using re.split, I can generate a list that looks thus:
 ['tag1', '+', 'tag2', '+', 'tag3', '-', 'tag4']
 
 I wish to derive two lists - each containing either tags to be
 included, or tags to be excluded. My idea was to take an element,
 examine what element precedes it and accordingly, insert it into the
 relevant list. However, I have not been successful.
 
 Is there a better way that I have not considered? 

If you're responsible for the original URL, you may consider rewriting 
it this way:
scheme://domain.tld/resource?tag1=1tag2=1tag3=1tag4=0

Else - and after you've finished cursing the guy that came out with such 
an innovative way to use url parameters - I think the first thing to do 
would be to fix the implicit-first-operator-mess, so you have something 
consistent:

if the_list[0] != -:
   the_list.insert(0, +)

Then a possible solution could be:

todo = {'+' : [], '-' : []}
for op, tag in zip(the_list[::2], the_list[1::2]):
   todo[op].append(tag)

But there's surely something better...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Separating elements from a list according to preceding element

2006-03-05 Thread James Stroud
Bruno Desthuilliers wrote:
 Rob Cowie a écrit :
 
 I'm having a bit of trouble with this so any help would be gratefully
 recieved...

 After splitting up a url I have a string of the form
 'tag1+tag2+tag3-tag4', or '-tag1-tag2' etc. The first tag will only be
 preceeded by an operator if it is a '-', if it is preceded by nothing,
 '+' is to be assumed.

 Using re.split, I can generate a list that looks thus:
 ['tag1', '+', 'tag2', '+', 'tag3', '-', 'tag4']

 I wish to derive two lists - each containing either tags to be
 included, or tags to be excluded. My idea was to take an element,
 examine what element precedes it and accordingly, insert it into the
 relevant list. However, I have not been successful.

 Is there a better way that I have not considered? 
 
 
 If you're responsible for the original URL, you may consider rewriting 
 it this way:
 scheme://domain.tld/resource?tag1=1tag2=1tag3=1tag4=0
 
 Else - and after you've finished cursing the guy that came out with such 
 an innovative way to use url parameters - I think the first thing to do 
 would be to fix the implicit-first-operator-mess, so you have something 
 consistent:
 
 if the_list[0] != -:
   the_list.insert(0, +)
 
 Then a possible solution could be:
 
 todo = {'+' : [], '-' : []}
 for op, tag in zip(the_list[::2], the_list[1::2]):
   todo[op].append(tag)
 
 But there's surely something better...

Fabulous. Here is a fix:

the_list = ['+'] * (len(the_list) % 2) + the_list
todo = {'+' : [], '-' : []}
for op, tag in zip(the_list[::2], the_list[1::2]):
   todo[op].append(tag)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python advocacy in scientific computation

2006-03-05 Thread Duncan Booth
sturlamolden wrote:

 First there are a few things I don't like:
 
 1. Intendation as a part of the syntax, really annoying.

Each to his own. I find having the compiler enforce indentation rules is a 
real benefit. There's nothing quite so annoying as having 'coding 
standards' you are supposed to be following which aren't enforced (so 
nobody else working on the code followed them either). C code which never 
executes a for loop because of a spurious ';' can be pretty annoying too.

 
 2. The self.something syntax is really tedious (look to ruby)!

I find it really useful to use a similar style when programming in other 
languages such as Java or C#. In particular it means that you can 
instantly see when you are referring to a member variable (without 
having to prefix them all with m_ or some other abomination) and when you 
have method arguments which get assigned to member variables you don't have 
to think of different names for each.

 
 4. Multithreading and parallel execution is impossible AFAIK because of
 the so-called GIL (global interpreter lock). Matlab is perhaps even
 worse in this respect.

Multithreading and parallel execution work fine. The only problem is that 
you don't get the full benefit when you have multiple processors. This one 
will become more of an annoyance in the future though as more systems have 
hyperthreading and multi-core processors.

 
 And there is a couple of questions I need answered:
 
 1. Can python do pass by reference? Are datastructures represented by
 references as in Java (I don't know yet).
 
Python only does pass by reference, although it is more normally referred 
to as pass by object reference to distinguish it from language where the 
references refer to variables rather than objects.

What it doesn't do is let you rebind a variable in the caller's scope which 
is what many people expect as a consequence of pass by reference. If you 
pass an object to a function (and in Python *every* value is an object) 
then when you mutate the object the changes are visible to everything else 
using the same object. Of course, some objects aren't mutable so it isn't 
that easy to tell that they are always passed by reference.
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >