PyGame migrating to JavaScript

2010-04-02 Thread Peter Billam
Startling news from http://pygame.org/news.html :

  pygame rewritten for javascript - Apr 1, 2010
  Javascript in recent years has been getting better and better, and
  now is a way better language than python. So to keep up with the
  times pygame has been rewritten for javascript. Please prepare
  your codebase with the py2js tool, which tries to automatically
  convert your python code into javascript.

  Hopefully with a few years everyone will have upgraded their
  code, and it will be wonderful. I hope you all will enjoy
  this change to javascript. Further news, and release binaries
  to be announced *very* soon.

I'm sure anyone who's spent time writing JavaScript will agree
completely with the fact that this fascinating news item was
released just yesterday (today being the second of April).
It's exciting that release binaries will be available
- er, to be more precise, will be announced - very soon.
Perhaps even in 364 days time?  Don't be left behind !

Peter

-- 
Peter Billam www.pjb.com.auwww.pjb.com.au/comp/contact.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyGame migrating to JavaScript

2010-04-02 Thread Xavier Ho
 Javascript in recent years has been getting better and better, and

>  now is a way better language than python. So to keep up with the
>  times pygame has been rewritten for javascript.
>

*shudders*

Can someone convince me why that is a good idea at all? Any rationales?

Cheers,
-Xav
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyGame migrating to JavaScript

2010-04-02 Thread Gary Herron

Xavier Ho wrote:

 Javascript in recent years has been getting better and better, and

 now is a way better language than python. So to keep up with the
 times pygame has been rewritten for javascript.


*shudders*

Can someone convince me why that is a good idea at all? Any rationales?

Cheers,
-Xav


It's a joke -- see http://en.wikipedia.org/wiki/April_Fools%27_Day

--
Gary Herron, PhD.
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

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


Re: PyGame migrating to JavaScript

2010-04-02 Thread Xavier Ho
On Fri, Apr 2, 2010 at 6:19 PM, Gary Herron  wrote:

> It's a joke -- see 
> http://en.wikipedia.org/wiki/April_Fools%27_Da


D'oh!

Can't believe that got me.

(It's already 2nd of April... you're not supposed to make that joke now! =p)

Cheers,
Xav
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: folks, what's wrong with this?

2010-04-02 Thread Bruno Desthuilliers

Ani a écrit :

Hi All:

I am just a beginner in python. Can anyone please tell me what is
wrong with this piece of code?


Robert already addressed your problem, so I'll just comment on a couple 
other points:



import copy
class BaseDummyObject(object):

def __init__(self):
pass


This initializer is at best useless.


def __getattr__(self, item):


The second parameter to __getattr__ is the name that is looked for, so 
better to name it "name" or "attrname" or...



try:
return self.__dict__.__getitem__(item)


__getitem__ - like most __magicmethods__ - provides support for the 
"subscript" operator, and as such is not supposed to be explicitely 
called (except for a couple corner cases). This should just be:


  return self.__dict__[item]



except KeyError:
print "Attribute Error: attr %s of class %s non-existent!"
%(item,  self.__class__.__name__)


The canonical AttributeError message is "'' object has no 
attribute ''"  - ok, doesn't matter much, but being consistent 
with the core language is usually a good idea IMHO !-)


And now for the most import point: __getattr__ is only called as a 
*last* resort. That is, after the attribute lookup mechanism will have 
tried *and failed* to find the name in the instance's __dict__.



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


Python and read archives?

2010-04-02 Thread durumdara



Hi!I want to make a multios (Win/Lin) Python based media catalog program, but I have a little problem with reading archives.Ok, Python supports zip and tar, but the world have more archives, like "rar", "7z", "tar.gz", "gz", etc.First I was happy with 7z.exe, because it is knows many formats, and 7z L "filename" command can retreive the list of files.Great! - I thought...But later I realized that password protection is halt the the 7z with password prompt. And I cannot ignore this with options as I see.So:I search for a solution to read archives (only filenames) if possible. I saw that 7z have callable dll, but I don't know, how to use it from python.Do you knows about a tool, or a code to read these archives, or or or...?Thanks for your help:   dd
-- Az Opera forradalmian új levelezőjét használva: http://www.opera.com/mail/-- 
http://mail.python.org/mailman/listinfo/python-list


idle 2.x and unicode literals

2010-04-02 Thread Joe P. Cool
Hi,

I'm working with Python 2.6.4 on Ubuntu 9.10 and noticed a difference
between IDLE and command line python. If I enter an é  (accented e,
LATIN SMALL LETTER E WITH ACUTE) as a unicode string in command line
python I get this:

>>> u'é'
u'\xe9'

In IDLE 2.6.4 I get this:

>>> u'é'
u'\xc3\xa9'

IDLE is set to UTF-8 and console environment has LANG = en_US.UTF-8.
This is a bit annyoing because ord(u'é') works on the command line but
raises an exception in IDLE:

>>> ord(u'é')
Traceback (most recent call last):
  File "", line 1, in 
ord(u'é')
TypeError: ord() expected a character, but string of length 2 found

Is this a bug? IDLE 3.1.1 works.

Cheers,
Joe
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: (a==b) ? 'Yes' : 'No'

2010-04-02 Thread Steven D'Aprano
On Thu, 01 Apr 2010 21:16:18 -0700, Steve Howell wrote:

> The ironic thing about the ternary operator is that it is not really
> ternary; it's binary.  Even just making an expression from a binary
> operator inevitably leads to syntax hell.
> 
> There is a principle of programming that I would like to coin, which is
> the "Tyranny of Three."
> 
> It is impossible to code for any expression that has three possible
> values in any kind of elegant way.  It's just impossible.  Try to code
> the bowling game without tearing out your teeth--three conditions:
> strike, spare, or normal.
> 
> The tyranny of three is that 3 is too small for an elegant N-based
> solution and too large for a simple condition.


I'm afraid I don't understand any of that. Can you explain further?

How is the ternary operator "not really ternary, it's binary"? It 
requires three arguments, not two, which makes it ternary. In Python 
syntax:

value1 if flag else value2

or in C:

flag ? value1 : value2

You say that "Even just making an expression from a binary operator 
inevitably leads to syntax hell."

I don't understand what you mean. What is so hellish about any of these?

a + b  # infix
a b +  # postfix, familiar to anyone who has programmed HP calculators
add(a, b)  # prefix function notation
+ a b  # prefix
add a to b  # verbose English-like


Well, perhaps the infix notation counts as "unusual", and the last as 
"too verbose", but hellish?


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


pynotify for python 3.1.. Help Please..

2010-04-02 Thread Jebagnana Das
Hello all,

 I'm trying to display system notifications in ubuntu.. I've tested
pynotify in python 2.6 and it's working fine.. I want to know if i can do
the same with python 3? I tried but there is no module named pynotify error
is displayed.. Any of your help would be much appreciated..
-- 
http://mail.python.org/mailman/listinfo/python-list


Splitting a string

2010-04-02 Thread Thomas Heller
Maybe I'm just lazy, but what is the fastest way to convert a string
into a tuple containing character sequences and integer numbers, like this:


'si_pos_99_rep_1_0.ita'  -> ('si_pos_', 99, '_rep_', 1, '_', 0, '.ita')

Thanks for ideas,
Thomas

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


Re: pynotify for python 3.1.. Help Please..

2010-04-02 Thread Xavier Ho
Hi Jebamnana,

You'll probably have to copy the pynotify contents to the Python 3.1 folder.
(under Libs\site-packages). You should be able to find the folder in the
Python 2.6 paths.

Once you do that, you can try to use it. But I don't know if pynotify will
be able to run with Python 3.1. For instance, you might have to look into
the source code and make some changes.

Better to consult with the author(s) of pynotify and consult them about the
difficulty to port to Py3.

Cheers,
Xav

On Fri, Apr 2, 2010 at 8:05 PM, Jebagnana Das wrote:

> Hello all,
>
>  I'm trying to display system notifications in ubuntu.. I've tested
> pynotify in python 2.6 and it's working fine.. I want to know if i can do
> the same with python 3? I tried but there is no module named pynotify error
> is displayed.. Any of your help would be much appreciated..
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pynotify for python 3.1.. Help Please..

2010-04-02 Thread Xavier Ho
On Fri, Apr 2, 2010 at 8:13 PM, Xavier Ho  wrote:

> Hi Jebamnana,
>

Jebagnana*

Sorry.

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


Hey Sci.Math, Musatov here. I know I've posted a lot of weird stuff trying to figure things out, but I really think I am onto something here and need some bright minds to have a look at this, comput

2010-04-02 Thread A Serious Moment
SPARSE COMPLETE SETS FOR NP:
SOLUTION OF A CONJECTURE
BY MARTIN MICHAEL MUSATOV *

for llP:

Sparse Comp1ete Sets
Solution of a Conjecture

In this paper we show if NP has a sparse complete
set under many-one reductions, then ? NP.

The result is extended to show NP is sparse reducible, then P =
ip.

The main technicues:technical cues and techniques of this paper
generalize the :;P 'recognizer' for the compliment of a sparse
complete set with census function to the case where the census
function is not
1'? own (c.f. [1? ii]) than a many-one reduction of tI: gives us the
language to the sparse set permits a polynomial time bounded
tree search as in [ti, [F], or [?:P].

Even without actual knowledge of the census, the algorithm utilizes
the properties of the true census to decide membership in SAT in
polynomial time.

Sparse Complete Sets for `LP:
Solution of a Conjecture
by Martin Michael Musatov

1. Computer Science

L. ? nan and J. 1? at?:i is [tH] under the assumption P? i?.

P all llP-complete sets are iso-morphic; i.e. there are polynomial
time, bijective reductions with polynomial time inverse reductions
between any two NP-cot-:complete sets.

A consequence of this conjecture is all NP-complete sets have
equivalent density; in particular, no sparse set could be i-complete
unless PP.

13e ? an EB] give a partial solution to the problem: by showing if a
subset of an SL i? language is NP-co:complete (a for ti or i, sparse),
then P = 1;P.

This result is strengthened by Fortune [F] showing if co-NP has a
sparse complete set, then P = 1p?

It is necessary to assume the satisfiable formulas reduce to a sparse
set since the proof uses the conjunctive self-reducibility of non-
satisfiable for:formulas and the sparse set to realize a polynomial
time algorithm.

N and P at e[?2] show similar results.

ll a rttq a n is and f[E14] extends the results of Fortune and NP at e
by showing if l IP has a sparse complete set with an easily computable
census function, then NP = co-I?P; P = tT.

P follows by Fortune 1s the or e?.

The question of how easy it is to compute census functions for l?-
complete sets is left open.

In light of Fortune's observation about co-I r 1 the original
conjecture by ten? a n and ll at i?a n is on reducing `?` to a sparse
set series temptingly close, however the tree search methods of [B],
[1], [i,:p] utilize the conjunctive self-reducibility of the co-l;P-
cot?NP-complete problem SAT0.

In this paper we settle the conjecture by showing if an L'P-complete
set is ? any-one reducible to a sparse set, then P = i?.

Thus determining the existence of a sparse co-??:complete set for l;p
is equivalent to solving the P = NP? problem.

We also show the census function of a sparse NP-co?i:complete set is
cota:computable in P.

Section 2 contains definitions an outline of the tree search time
method for showing sparse sets for co-NP i? implies P = ??1.

Section 3 contains the ? a in results; it assumes n familiarity with
the tree search methods.

?. Preliminaries

We will consider languages over an alphabet ? with two or or e sy?-
symbols.

We assume fa?:familiarity with NP--Hcor?:complete sets (cf. Ec], [K]
or
EAHU)).

All the reductions in this paper will be polynomial time many-one
reductions.

Definition: A subset 5 of is sparse if there is a polynomial so the
number of strings in 5 of size at most n is at most p.

We restate the following theorem (cf. [r] or [iP]) and s'etch: sketch
the proof.

Theorem 1.1. If SATc is reducible to a sparse set, then p = NP.

Proof.

Let f:SAT --> 5 be a reduction to & sparse set, 5, and let F be a
formula whose satisfiability is to be decided.

We search a binary tree formed from self-reductions of F as follows: F
is at the root; a for??:formula C with variables X1, ... , X occurring
in the tree will n have sons G0 a n? G1 where `: is replaced by false
and true, respectively, and trivial si?:simplifications are performed
( e.g. true or = true).

If the for i:?formula F has n variables, then the tree will have 2n?1
nodes. ? i e perform a depth-first search of the tree utilizing the
sparse set to prune the search.

At each node Ft encounters we compute
c
a label f(F').

We infer certain labels correspond to SAT by the following:

When a node with formula false is found, its label is assigned 1.

t'false."

ii. t

Then two sons of a node have ?:labels assigned V?: false, ?1 then the
label of the node is also assigned t'false."

(This is tl-ie:time conjunctive self-reducibility of non-?:satisfiable
for?:formulas.)

We prune the search by stopping if a leaf has for n?:l a true in which
case F is satisfiable by the as:s i2 n?:assistant on the p at?: part
to the leaf; and by not searching below a node whose label has already
been assigned ?false."

?1e follow? j in g:following le r2a establishes poly-not:polynomial
running time of the algorithn.

Lemna 1.2.

Let F be a for?:formula with n variables.

Let p(.) be bound

Let the density of 5 and let q(.) be a poly-no?:pol

subprocess.Popen objects: how to ensure that stdin is closed

2010-04-02 Thread Harishankar
I am writing a small app which requires input using stdin to the 
subprocess.

I use the following technique:

proc = subprocess.Popen (cmdargs, stdin=subprocess.PIPE)

proc.stdin.write ("Something")
proc.stdin.flush ()
...
proc.stdin.write ("something else")
proc.stdin.flush ()
...

and so on. I cannot use communicate() because it waits till program 
termination and so obviously can be used once only.

The problem is that I want to close the process and it's not responding 
either to proc.stdin.close() or even proc.terminate() which is in 
Python 2.6 (not in 2.5.x)

So I am left with a mangled terminal.

Is subprocess behaving funny or am I doing something wrong? I am not even 
sure if the proc.stdin.close () is respected because even without it, I 
am getting the same mangled state. I just want to control the commands 
using stdin.write and then close the process when done.


-- 
Harishankar (http://harishankar.org http://literaryforums.org)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Splitting a string

2010-04-02 Thread Shashwat Anand
>>> s = 'si_pos_99_rep_1_0.ita'
>>> res = tuple(re.split(r'(\d+)', s))
>>> res
('si_pos_', '99', '_rep_', '1', '_', '0', '.ita')
>>>


On Fri, Apr 2, 2010 at 3:42 PM, Thomas Heller  wrote:

> Maybe I'm just lazy, but what is the fastest way to convert a string
> into a tuple containing character sequences and integer numbers, like this:
>
>
> 'si_pos_99_rep_1_0.ita'  -> ('si_pos_', 99, '_rep_', 1, '_', 0, '.ita')
>
> Thanks for ideas,
> Thomas
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Splitting a string

2010-04-02 Thread Xavier Ho
Best I can come up with:

>>> def split_number(string):
... output = [string[0]]
... for character in string[1:]:
... if character.isdigit() != output[-1].isdigit():
... output.append('')
... output[-1] += character
... return tuple(output)
...
>>> split_number('si_pos_99_rep_1_0.ita')
('si_pos_', '99', '_rep_', '1', '_', '0', '.ita')

Cheers,
Xav

On Fri, Apr 2, 2010 at 8:12 PM, Thomas Heller  wrote:

> Maybe I'm just lazy, but what is the fastest way to convert a string
> into a tuple containing character sequences and integer numbers, like this:
>
>
> 'si_pos_99_rep_1_0.ita'  -> ('si_pos_', 99, '_rep_', 1, '_', 0, '.ita')
>
> Thanks for ideas,
> Thomas
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess.Popen objects: how to ensure that stdin is closed

2010-04-02 Thread Harishankar
On Fri, 02 Apr 2010 10:17:55 +, Harishankar wrote:

> I am writing a small app which requires input using stdin to the
> subprocess.
> 
> I use the following technique:
> 
> proc = subprocess.Popen (cmdargs, stdin=subprocess.PIPE)
> 
> proc.stdin.write ("Something")
> proc.stdin.flush ()
> ...
> proc.stdin.write ("something else")
> proc.stdin.flush ()
> ...
> 
> and so on. I cannot use communicate() because it waits till program
> termination and so obviously can be used once only.
> 
> The problem is that I want to close the process and it's not responding
> either to proc.stdin.close() or even proc.terminate() which is in Python
> 2.6 (not in 2.5.x)
> 
> So I am left with a mangled terminal.
> 
> Is subprocess behaving funny or am I doing something wrong? I am not
> even sure if the proc.stdin.close () is respected because even without
> it, I am getting the same mangled state. I just want to control the
> commands using stdin.write and then close the process when done.

Hmm...

just two minutes after I posted this. I just added this

proc.wait ()

after closing stdin and it works fine now. Still not sure whether I need 
the proc.stdin.close () though.





-- 
Harishankar (http://harishankar.org http://literaryforums.org)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Hey Sci.Math, Musatov here. I know I've posted a lot of weird stuff trying to figure things out, but I really think I am onto something here and need some bright minds to have a look at this, co

2010-04-02 Thread Xavier Ho
On Fri, Apr 2, 2010 at 8:14 PM, A Serious Moment wrote:

> SPARSE COMPLETE SETS FOR NP:
> SOLUTION OF A CONJECTURE
> BY MARTIN MICHAEL MUSATOV *
>
> for llP:
>
> Sparse Comp1ete Sets
> Solution of a Conjecture
>

Hi,

If you're serious about this posting, could you please:

1) Provide a link to a PDF/Latex or some other well-formatted text page
2) Comp1ete != Complete

Because I find your email impossible to read.

Cheers,
Xav
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Splitting a string

2010-04-02 Thread Xavier Ho
Oops, minor update:

>>> def split_number(string):
... output = [string[0]]
... for character in string[1:]:
... if character.isdigit() != output[-1].isdigit():
... if output[-1].isdigit() is True:
... output[-1] = int(output[-1])
... output.append('')
... output[-1] += character
... return tuple(output)
...
>>> split_number('si_pos_99_rep_1_0.ita')
('si_pos_', 99, '_rep_', 1, '_', 0, '.ita')


Cheers,
Xav

On Fri, Apr 2, 2010 at 8:26 PM, Xavier Ho  wrote:

> Best I can come up with:
>
> >>> def split_number(string):
> ... output = [string[0]]
> ... for character in string[1:]:
> ... if character.isdigit() != output[-1].isdigit():
> ... output.append('')
> ... output[-1] += character
> ... return tuple(output)
> ...
> >>> split_number('si_pos_99_rep_1_0.ita')
>
> ('si_pos_', '99', '_rep_', '1', '_', '0', '.ita')
>
> Cheers,
> Xav
>
>
> On Fri, Apr 2, 2010 at 8:12 PM, Thomas Heller  wrote:
>
>> Maybe I'm just lazy, but what is the fastest way to convert a string
>> into a tuple containing character sequences and integer numbers, like
>> this:
>>
>>
>> 'si_pos_99_rep_1_0.ita'  -> ('si_pos_', 99, '_rep_', 1, '_', 0, '.ita')
>>
>> Thanks for ideas,
>> Thomas
>>
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pynotify for python 3.1.. Help Please..

2010-04-02 Thread Shashwat Anand
I guess it is a 3rd party module. Run setup.py with python3.1, however it
can happen that the module is not python3 compatible. In that case try using
2to3 if you can.

On Fri, Apr 2, 2010 at 3:43 PM, Xavier Ho  wrote:

> On Fri, Apr 2, 2010 at 8:13 PM, Xavier Ho  wrote:
>
>> Hi Jebamnana,
>>
>
> Jebagnana*
>
> Sorry.
>
> -Xav
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Splitting a string

2010-04-02 Thread Alex Willmer
On Apr 2, 11:12 am, Thomas Heller  wrote:
> Maybe I'm just lazy, but what is the fastest way to convert a string
> into a tuple containing character sequences and integer numbers, like this:
>
> 'si_pos_99_rep_1_0.ita'  -> ('si_pos_', 99, '_rep_', 1, '_', 0, '.ita')
>

This is very probably not the fastest execution wise, it was the
fastest development time wise:

import re

def maybe_int(x):
try:
return int(x)
except ValueError:
return x

def strings_n_ints(s):
return tuple(maybe_int(x) for x in re.findall('(\d+|\D+)', s))

>>> strings_n_ints('si_pos_99_rep_1_0.ita')
('si_pos_', 99, '_rep_', 1, '_', 0, '.ita')

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


Re: (a==b) ? 'Yes' : 'No'

2010-04-02 Thread Duncan Booth
Steven D'Aprano  wrote:

> Yes, I agree, we should be using the previously well known syntax:
> 
> condition -> value_if_true, value_if_false
> 
> which was introduced by BCPL in 1966.
> 
What, not this?

VALOF TEST condition THEN RESULTIS value_if_true ELSE RESULTIS 
value_if_false

which was also introduced by BCPL in 1966.

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


Re: Splitting a string

2010-04-02 Thread Peter Otten
Thomas Heller wrote:

> Maybe I'm just lazy, but what is the fastest way to convert a string
> into a tuple containing character sequences and integer numbers, like
> this:
> 
> 
> 'si_pos_99_rep_1_0.ita'  -> ('si_pos_', 99, '_rep_', 1, '_', 0, '.ita')

>>> parts = re.compile("([+-]?\d+)").split('si_pos_99_rep_1_0.ita')
>>> parts[1::2] = map(int, parts[1::2])
>>> parts
['si_pos_', 99, '_rep_', 1, '_', 0, '.ita']

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


subclass of object

2010-04-02 Thread Jason Friedman
Hi, what is the difference between:

def MyClass(object):
pass

and

def MyClass():
pass
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pynotify for python 3.1.. Help Please..

2010-04-02 Thread Jebagnana Das
Thank you for your reply. Unfortunately pynotify is not available as a .py
file but as an .so (shared library) file. In both python 2.5 and 2.6
installations it can be found at
/var/lib/python-support/python2.x/gtk-2.0/pynotify/__init__.py ,
_pynotify.so.

  I think it was written in native c or c++ which is then converted
to a shared library to use with python.. Unless the source code in c is
available, we can't port it to python 3.. I can't find the authors name or
any license agreement there..
By luck if any of the authors of pynotify here please answer me..

 When will the .so for python3 will be released?

 or Is there any alternate way of achieving this??

Regards,
Jeba.

Xav : You can simply call me as jeba.


Hi Jebamnana,
>
> You'll probably have to copy the pynotify contents to the Python 3.1
> folder. (under Libs\site-packages). You should be able to find the folder in
> the Python 2.6 paths.
>
> Once you do that, you can try to use it. But I don't know if pynotify will
> be able to run with Python 3.1. For instance, you might have to look into
> the source code and make some changes.
>
> Better to consult with the author(s) of pynotify and consult them about the
> difficulty to port to Py3.
>
> Cheers,
> Xav
>
> Hello all,
>>
>>  I'm trying to display system notifications in ubuntu.. I've
>> tested pynotify in python 2.6 and it's working fine.. I want to know if i
>> can do the same with python 3? I tried but there is no module named pynotify
>> error is displayed.. Any of your help would be much appreciated..
>>
>>
>>
> Hi Jebamnana,
>>
>
> Jebagnana*
>
> Sorry.
>
> -Xav
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subclass of object

2010-04-02 Thread Alf P. Steinbach

* Jason Friedman:

Hi, what is the difference between:

def MyClass(object):
pass

and

def MyClass():
pass


If you really meant 'def', then the first is a routine taking one argument, and 
the second is a routine of no arguments.


If you meant 'class' instead of 'def', then it depends on the Python version.

In Py2 the first then defines a new-style class, while the second defines an 
old-style class. E.g. you can see some difference by checking with 'isinstance'. 
In Py3 there's no difference.



Cheers & hth.,

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


Re: subclass of object

2010-04-02 Thread Steve Holden
Jason Friedman wrote:
> Hi, what is the difference between:
> 
> def MyClass(object):
> pass
> 
> and
> 
> def MyClass():
> pass

In Python 3, nothing. In Python 2, the former gets you a subclass of
object whereas the latter gets you an instance of , for
compatibility with pre-2.2 versions.

For most practical purposes there is no difference, so it doesn't matter
until it matters, so to speak. Unless you are noticing unexpected
behavior in your programs you probably don't need to worry (though you
might want to use the first form to ensure better Python 3 compatibility).

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
See PyCon Talks from Atlanta 2010  http://pycon.blip.tv/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: associative array

2010-04-02 Thread Bernard Czenkusz
On Thu, 01 Apr 2010 11:57:11 +, Harishankar wrote:

> On Wed, 31 Mar 2010 09:40:30 -0700, Javier Montoya wrote:
> 
>> Dear all,
>> 
>> I'm a newbie in python and would be acknowledge if somebody could shed
>> some light on associative arrays.
>> More precisely, I would like to create a multi-dimensional associative
>> array. I have for example a list of students which are identified
>> uniquely by their student IDs. Additionally, for each student I have
>> some information: FirstName, LastName, etc.
>> 
>> The array would have then the following form: [StudentID] =>
>> [FirstName][LastName][Telephone]...[ ... ]
>> 
>> I would like to be able to access a field directly by using a StudentID
>> [StudentID][FirstName]
>> [StudentID][LastName]
>> 
>> How could I manipulate such an array (create the array, add elements,
>> access data)?
>> 
>> Best wishes
> 
> I know this is not a direct answer, but in your case I would probably
> use a database, because it is the easiest and most standardized way to
> access such types of data. If you don't want something heavyweight, use
> sqlite with in-memory databases/persistent file.
> 
> Look at sqlite3 module in python.

You could also look at the September issue of the Python Rag which has a 
couple of articles on storing a membership class using Shelve, which is 
similar to what you are interested in:
http://www.pythonrag.org/

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


Re: subclass of object

2010-04-02 Thread Steve Holden
Alf P. Steinbach wrote:
> * Jason Friedman:
>> Hi, what is the difference between:
>>
>> def MyClass(object):
>> pass
>>
>> and
>>
>> def MyClass():
>> pass
> 
> If you really meant 'def', then the first is a routine taking one
> argument, and the second is a routine of no arguments.
> 
> If you meant 'class' instead of 'def', then it depends on the Python
> version.
> 
> In Py2 the first then defines a new-style class, while the second
> defines an old-style class. E.g. you can see some difference by checking
> with 'isinstance'. In Py3 there's no difference.
> 
Interesting. I actually read "class"  for "def" and replied accordingly.

As can plainly be seen ...

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
See PyCon Talks from Atlanta 2010  http://pycon.blip.tv/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


For Peer Review

2010-04-02 Thread A Serious Moment
AN ESSAY ABOUT RESEARCH (fl) ON SPARSE
NP COMPLETE SETS
By
M. Musatov
The purpose of this paper is to review the origins and motivation for
the conjecture sparse NP complete sets do not exist (unless ? NP) and
to describe the development of the ideas and techniques leading to the
recent solution of this conjecture.
The research in theoretical computer science and computational
complexity theory has been strongly influenced by the study of such
feasibly computable families of languages as P, NP and PTAPE. This
research has revealed deep and unsuspected connections between
different classes of problems and it has provided completely new means
for classifying the computational complexity of problems.
Furthermore, the work has raised a set of interesting new research
problems and crested an unprecedented consensus about what problems
have to be solved before real understanding of the complexity of
computations can be achieved.
In the research on feasible computations the central role has been
played by the families of deterministic and nondeterministic
polynonial time computable languages. P and NP(1) respectively [MIU.
c, cj, K]. In particular(.) the NP complete(?te) languages have been
studied intensively and virtually hundreds of natural NP complete
(rnplete) problems have been found in many different areas of
applications (AHu. cJ).
Though we do not yet know whether P (?) NP(.) we accept today a proof
a problem is NP complete as convincing evidencethe problem may be
polynonial time computable (and feasibly computable); a proof a
problem is complete for PTAPE is viewed as even stronger evidence the
problem is feasibly computable (even though there is no proof that P
(?) NP (?) PTAPE).
As part ot the general study of similarities among NP complete
problems it is conjectured by Berman and Hartmanis(1) for reasons
given in the next section(1) all NP complete problems are (?re)
isomorphic (norphic) under polynomial time mappings and therefore
there may exist (sparse) NP complete sets with considerably fewer
elements than the known classic complete problems (e.g. SAT. CLIQUE(1)
etc. EBH)).
When the conjecture is first formulated in 1975(.) the understanding
of NP complete(-plete) problems was more limited and several energetic
frontal assaults on this problem(-lem) failed (?ailed). As a matter of
fact, the problem looked quite hopeless after a considerable (-erable)
initial effort to solve it. Fortunately(1) during the next five years
a number of different people in Europe and America contributed a set
of ideas and techniques recently leading to an elegant solution of the
problem by (5)(.) Mahaney of Cornell University (M).
The purpose of this paper is to describe the origins of the sparseness
conjecture (-ture) about NP complete sets(1) to relate the information
flow about this problem and to describe the development of the crucial
ideas finally leading to the proof sparse NP complete sets exist(1)
then P = NP (M).
We believe this is an interesting and easily understandable
development in the study of NP complete problems and there are some
lessons to be learned about computer science research from the way
this tantalizing problem was solved.
Furthermore(1) it is hoped these results provide a new impetus for
work on the main conjecture all NP complete sets are p-isomorphic.
(?.) Preliminaries and the Sparseness (narseness)
Let P and NP denote(.) respectively(.) the families of languages
accepted by deterministic (-?inistic) and nondeterministic Turing
machines in polynomial time.
A language C is said to be (?) complete (niete) if C is in NP and if
for any other language 3 in NP there exists a polynomial time
computable function f such x ( 3f(x) c C.
The importance of the family of languages P stems from the fact they
provide (-vide) a reasonable model for the feasibly computable
(nutable) problems. The family NP contains (-tains) many important
practical problems and a large number of problems from different (-
ferent) areas of applications in computer science and mathematics have
been shown to be complete for NP (AHU. C. BJ1 K). Since today it is
widely conjectured P (?) NP(.) the NP complete problems are believed
(by a minority) may be solvable in polynomial time.
Currently one of the most fascinating problems (toblems) in
theoretical computer science is to understand better the structure of
feasibly computable problems and(.) in particular(.) to resolve the p
NP question. For an extensive study of P and NP see EARu. GJ].
A close study of the classic NP complete sets(.) such as SAT(.) the
satisfiable Boolean formulas in conjunctive normal form(.) RAM(.)
graphs with Hamiltonian circuits(.0) or CLIQUE(.) graphs with cliques
of specified size(.) revealed they are very similar (-lar) in a strong
technical sense (BH). Not only may they be reduced to each other(.)
they are actually isomorpbic under polynomial time mappings (nappings)
as defined below:
* *
Two languages A and 3. A ? ? and 3 r . are ?-iso?or?hic:isom

JSONBOT 0.1 released

2010-04-02 Thread Bart Thate
Introducing JSONBOT

JSONBOT is a bot that stores all its data in json format. It runs on
the Google Application Engine and can thus support wave, web and xmpp.
Standalone programms are provided for IRC and console, the goal is to
let both clientside and GAE side communicate through JSON either over
XMPP or HTTP POST.

this bot needs google_appengine installed in your home dir

JSONBOT provides the following programs:
j
sb - console version of jsonbot
jsb-irc - IRC version of jsonbot
jsb-run - run a release in the GAE dev_appserver
jsb-release - create a new release directory
jsb-upload - upload a release to the GAE

JSONBOT 0.1 contains the following plugins:

8b - eight ball
admin - administator related commands
ask - plugin for asking "experts" a question
choice - choice out of a list .. used in pipelines
core - core bot commands
count - count the numbers in a resutl .. used in pipelines
gadget - wave gadget support
gcalc - use google to calculate
gozernet - connect multiple JSONBOTs through xmpp
grep - grep the result .. used in pipelines
hubbub - pubsubhubbub plugin providing subscribe functionality
ipcalc - ipcalculator
irc - IRC related commands
misc - other commands
more - do a more on buffered output
not - negated grep .. used in pipelines
outputcache - show outputcache data
relay - relay to other waves/xmpp account
reload - reloading of plugins
reverse - reverse the result .. also used in pipelines
sort - sort the result .. used in pipelines
tail - tail the result .. used in pipelines
tinyurl - get a tinyurl
uniq - make the result unique .. used in pipelines
user - user management
userstate - userstate management
watcher - watch waves .. get notified in xmpp
wave - wave related commands
welcome - welcome messages shown in the gadget
wikipedia - query wikipedia

To upload your own bot do the following:

you need an account on the Google Application Engine. see
http://appengine.google.com/

1) run jsb-release yourbotname - this will create a uploadable dir
2) run jsb-upload yourbotname

this enables web and xmpp, for wave you need to do the following:

2) go to https://wave.google.com/wave/robot/register and register
your
bot
3) edit ~/regs/yourbotname/ dir and copy the verification token and
secret to the credentials.py file
4) run jsb-release yourbotname
4) run jsb-upload  yourbotname
5) once its uploaded click the "verify" button
6) copy the consumer key and secret to the credentials.py file en run
jsb-upload again
7) done !

Now you should be able to do the following:

1) visit the website at http://yourbotname.appspot.com
2) add the bot as Jabber buddy at yourbotn...@appspot.com
3) the same as wave bot
4) on joining a wave the bot loads a gadget from 
http://yourbotname.appspot.com/gadget.xml
5) manifest to add your bot to the waves newwave menu use
http://yourbotname.appspot.com/feeder.xml

JSONBOT is open source (MIT license) and free to clone when needed,
patches welcomed though ;]

home: http://jsonbot.googlecode.com/
demo: http://jsonbot.appspot.com/
wave/xmpp: json...@appspot.com
contact: bth...@gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subclass of object

2010-04-02 Thread Alf P. Steinbach

* Steve Holden:

Alf P. Steinbach wrote:

* Jason Friedman:

Hi, what is the difference between:

def MyClass(object):
pass

and

def MyClass():
pass

If you really meant 'def', then the first is a routine taking one
argument, and the second is a routine of no arguments.

If you meant 'class' instead of 'def', then it depends on the Python
version.

In Py2 the first then defines a new-style class, while the second
defines an old-style class. E.g. you can see some difference by checking
with 'isinstance'. In Py3 there's no difference.


Interesting. I actually read "class"  for "def" and replied accordingly.

As can plainly be seen ...


Yes, the names act as comments about intent.

Such comments can be misleading about what the code actually does.

Since I think you're very interested in the human aspect of this I suggest you 
try to find information about how master chess players remember chess boards. As 
I recall, they find it really difficult to remember random boards, while boards 
that represent actual chess games are remembered at a glance. Indicating that 
what's remembered is at a much higher level of abstraction than piece positions.



Cheers,

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


plagiarism, no follow-ups please

2010-04-02 Thread Chip Eastham
On Apr 2, 6:14 am, A Serious Moment
 cross-posted
an OCR'd version of a 1980 paper
by SR Mahaney, mutilating the text
further to remove its attribution
and create the false impression of
authorship by the (im)poster.




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


plagiarism, no follow-ups please

2010-04-02 Thread Chip Eastham
On Apr 2, 8:27 am, A Serious Moment
 cross-posted
a 1980 paper by J. Hartmanis and S.R.
Mahaney, falsely taking credit for
their work.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: CGI templating with python

2010-04-02 Thread Aaron Watters
On Apr 1, 11:19 am, KB  wrote:
> > Django will probably get you where you want to go the fastest:
>
> >    http://www.djangoproject.com/
>
> > In particular, its admin interface will probably automatically generate a 
> > usable
> > UI for you without your having to write many templates at all.
>
> Robert,
>
> Thank you very very much. I had a brief peruse of django last night
> and it does indeed look like what I am after! Will take me some
> time :) to delve into it deeper but I wanted to thank you!

You could also look at WHIFF and try out the test drive.

http://whiffdoc.appspot.com/docs/W.intro

  -- Aaron Watters

===
This one goes to 11.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Splitting a string

2010-04-02 Thread Patrick Maupin
On Apr 2, 6:24 am, Peter Otten <__pete...@web.de> wrote:
> Thomas Heller wrote:
> > Maybe I'm just lazy, but what is the fastest way to convert a string
> > into a tuple containing character sequences and integer numbers, like
> > this:
>
> > 'si_pos_99_rep_1_0.ita'  -> ('si_pos_', 99, '_rep_', 1, '_', 0, '.ita')
> >>> parts = re.compile("([+-]?\d+)").split('si_pos_99_rep_1_0.ita')
> >>> parts[1::2] = map(int, parts[1::2])
> >>> parts
>
> ['si_pos_', 99, '_rep_', 1, '_', 0, '.ita']
>
> Peter

You beat me to it.  re.split() seems underappreciated for some
reason.  When I first started using it (even though it was faster for
the tasks I was using it for than other things) I was really annoyed
at the empty strings it was providing between matches.  It is only
within the past couple of years that I have come to appreciate the
elegant solutions that those empty strings allow for.  In short,
re.split() is by far the fastest and most elegant way to use the re
module for a large class of problems.

So, the only thing I have to add to this solution is that, for this
particular regular expression, if the source string starts with or
ends with digits, you will get empty strings at the beginning or end
of the resultant list, so if this is a problem, you will want to check
for and discard those.

Regards,
Pat
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: (a==b) ? 'Yes' : 'No'

2010-04-02 Thread Steve Howell
On Apr 2, 2:04 am, Steven D'Aprano  wrote:
> On Thu, 01 Apr 2010 21:16:18 -0700, Steve Howell wrote:
> > The ironic thing about the ternary operator is that it is not really
> > ternary; it's binary.  Even just making an expression from a binary
> > operator inevitably leads to syntax hell.
>
> > There is a principle of programming that I would like to coin, which is
> > the "Tyranny of Three."
>
> > It is impossible to code for any expression that has three possible
> > values in any kind of elegant way.  It's just impossible.  Try to code
> > the bowling game without tearing out your teeth--three conditions:
> > strike, spare, or normal.
>
> > The tyranny of three is that 3 is too small for an elegant N-based
> > solution and too large for a simple condition.
>
> I'm afraid I don't understand any of that. Can you explain further?
>
> How is the ternary operator "not really ternary, it's binary"? It
> requires three arguments, not two, which makes it ternary. In Python
> syntax:
>

Of course, I understand that the ternary operator has three arguments,
but it only has two possible outcomes.

You asked me to elaborate on the "Tyranny of Three."  Let's say you
have three possible outcomes.

In some languages you would write something like this:

mark = (rolls == 1) && (pins == 10) ? 'strike' :
   (rolls == 2) && (pins == 10) ? 'spare' :
  'normal'

Many people consider the above very ugly, so they write it like so:

  if pins == 10:
 if rolls == 1:
return 'strike'
 else:
return 'spare'
  else:
 return 'normal'

Then the next programmer comes along and "cleans up":

  if pins == 10:
return 'strike' if rolls == 1 else 'spare'
  else:
return 'normal'

Then there is this alternative:

  if rolls == 2:
return 'spare' if pins == 10 else 'normal'
  else:
return 'strike'

And then:

  if rolls == 2:
if pins == 10
  return 'spare'
else
  return 'normal
  else:
return 'strike'

Or even this:

   return 'strike' if rolls == 1 else ('spare' if pins == 10 else
'normal')

The "Tyranny of Three" refers to a problem where there are an infinite
number of valid solutions, but none of them have any essential beauty,
so they lead to endless nitpicking and code churn.

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


Re: off topic but please forgive me me and answer

2010-04-02 Thread Wanderer
On Apr 1, 7:34 pm, Patrick Maupin  wrote:
> On Apr 1, 4:42 pm, Tim Chase  wrote:

> > Uh, did you try it at the python prompt?  


When I try it at the IPython prompt, I get

Object 'how much is one half times one half' not found.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: (a==b) ? 'Yes' : 'No'

2010-04-02 Thread Steve Holden
Steve Howell wrote:
> On Apr 2, 2:04 am, Steven D'Aprano  cybersource.com.au> wrote:
[...]
>> How is the ternary operator "not really ternary, it's binary"? It
>> requires three arguments, not two, which makes it ternary. In Python
>> syntax:
>>
> 
> Of course, I understand that the ternary operator has three arguments,
> but it only has two possible outcomes.
> 
That doesn't make it a binary operator. Otherwise what's long
multiplication, which has an infinite number of possible outcomes?

> You asked me to elaborate on the "Tyranny of Three."  Let's say you
> have three possible outcomes.
> 
> In some languages you would write something like this:
> 
> mark = (rolls == 1) && (pins == 10) ? 'strike' :
>(rolls == 2) && (pins == 10) ? 'spare' :
>   'normal'
> 
> Many people consider the above very ugly, so they write it like so:
> 
>   if pins == 10:
>  if rolls == 1:
> return 'strike'
>  else:
> return 'spare'
>   else:
>  return 'normal'
> 
> Then the next programmer comes along and "cleans up":
> 
>   if pins == 10:
> return 'strike' if rolls == 1 else 'spare'
>   else:
> return 'normal'
> 
> Then there is this alternative:
> 
>   if rolls == 2:
> return 'spare' if pins == 10 else 'normal'
>   else:
> return 'strike'
> 
> And then:
> 
>   if rolls == 2:
> if pins == 10
>   return 'spare'
> else
>   return 'normal
>   else:
> return 'strike'
> 
> Or even this:
> 
>return 'strike' if rolls == 1 else ('spare' if pins == 10 else
> 'normal')
> 
> The "Tyranny of Three" refers to a problem where there are an infinite
> number of valid solutions, but none of them have any essential beauty,
> so they lead to endless nitpicking and code churn.
> 
The Real Programmer (tm) simply chooses one, implements it and moves on.
While philosophical discussions are interesting they don't pay the bills.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
See PyCon Talks from Atlanta 2010  http://pycon.blip.tv/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: (a==b) ? 'Yes' : 'No'

2010-04-02 Thread Steve Howell
On Apr 2, 7:05 am, Steve Howell  wrote:
> On Apr 2, 2:04 am, Steven D'Aprano 
>
>
> cybersource.com.au> wrote:
> > On Thu, 01 Apr 2010 21:16:18 -0700, Steve Howell wrote:
> > > The ironic thing about the ternary operator is that it is not really
> > > ternary; it's binary.  Even just making an expression from a binary
> > > operator inevitably leads to syntax hell.
>
> > > There is a principle of programming that I would like to coin, which is
> > > the "Tyranny of Three."
>
> > > It is impossible to code for any expression that has three possible
> > > values in any kind of elegant way.  It's just impossible.  Try to code
> > > the bowling game without tearing out your teeth--three conditions:
> > > strike, spare, or normal.
>
> > > The tyranny of three is that 3 is too small for an elegant N-based
> > > solution and too large for a simple condition.
>
> > I'm afraid I don't understand any of that. Can you explain further?
>
> > How is the ternary operator "not really ternary, it's binary"? It
> > requires three arguments, not two, which makes it ternary. In Python
> > syntax:
>
> Of course, I understand that the ternary operator has three arguments,
> but it only has two possible outcomes.
>
> You asked me to elaborate on the "Tyranny of Three."  Let's say you
> have three possible outcomes.
>
> In some languages you would write something like this:
>
> mark = (rolls == 1) && (pins == 10) ? 'strike' :
>        (rolls == 2) && (pins == 10) ? 'spare' :
>                                       'normal'
>
> Many people consider the above very ugly, so they write it like so:
>
>   if pins == 10:
>      if rolls == 1:
>         return 'strike'
>      else:
>         return 'spare'
>   else:
>      return 'normal'
>
> Then the next programmer comes along and "cleans up":
>
>   if pins == 10:
>     return 'strike' if rolls == 1 else 'spare'
>   else:
>     return 'normal'
>
> Then there is this alternative:
>
>   if rolls == 2:
>     return 'spare' if pins == 10 else 'normal'
>   else:
>     return 'strike'
>
> And then:
>
>   if rolls == 2:
>     if pins == 10
>       return 'spare'
>     else
>       return 'normal
>   else:
>     return 'strike'
>
> Or even this:
>
>    return 'strike' if rolls == 1 else ('spare' if pins == 10 else
> 'normal')
>
> The "Tyranny of Three" refers to a problem where there are an infinite
> number of valid solutions, but none of them have any essential beauty,
> so they lead to endless nitpicking and code churn.

I forgot this one:

def obfuscated_triager(rolls, pins,
lookup = ['normal'] * 10 + ['strike'] + [None] * 9 + ['spare']
):
return lookup[rolls * pins]

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


Re: (a==b) ? 'Yes' : 'No'

2010-04-02 Thread Steve Howell
On Apr 2, 7:21 am, Steve Holden  wrote:
> Steve Howell wrote:
> > On Apr 2, 2:04 am, Steven D'Aprano  > cybersource.com.au> wrote:
> [...]
> >> How is the ternary operator "not really ternary, it's binary"? It
> >> requires three arguments, not two, which makes it ternary. In Python
> >> syntax:
>
> > Of course, I understand that the ternary operator has three arguments,
> > but it only has two possible outcomes.
>
> That doesn't make it a binary operator. Otherwise what's long
> multiplication, which has an infinite number of possible outcomes?
>

Ok, it's not a binary operator.  I just meant it only really selects
from two possible expressions, so you would think there would be one
good way to express that in code, but of course any variation of the
ternary operator leads to endless debates.

>
>
> > You asked me to elaborate on the "Tyranny of Three."  Let's say you
> > have three possible outcomes.
>
> > In some languages you would write something like this:
>
> > mark = (rolls == 1) && (pins == 10) ? 'strike' :
> >        (rolls == 2) && (pins == 10) ? 'spare' :
> >                                       'normal'
>
> > Many people consider the above very ugly, so they write it like so:
>
> >   if pins == 10:
> >      if rolls == 1:
> >         return 'strike'
> >      else:
> >         return 'spare'
> >   else:
> >      return 'normal'
>
> > Then the next programmer comes along and "cleans up":
>
> >   if pins == 10:
> >     return 'strike' if rolls == 1 else 'spare'
> >   else:
> >     return 'normal'
>
> > Then there is this alternative:
>
> >   if rolls == 2:
> >     return 'spare' if pins == 10 else 'normal'
> >   else:
> >     return 'strike'
>
> > And then:
>
> >   if rolls == 2:
> >     if pins == 10
> >       return 'spare'
> >     else
> >       return 'normal
> >   else:
> >     return 'strike'
>
> > Or even this:
>
> >    return 'strike' if rolls == 1 else ('spare' if pins == 10 else
> > 'normal')
>
> > The "Tyranny of Three" refers to a problem where there are an infinite
> > number of valid solutions, but none of them have any essential beauty,
> > so they lead to endless nitpicking and code churn.
>
> The Real Programmer (tm) simply chooses one, implements it and moves on.
> While philosophical discussions are interesting they don't pay the bills.
>

Agreed.  The nitpicking and code churn tends to come up when you have
multiple programmers with different aesthetics, although sometimes
even the solo programmer can get overly fiddly.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamic Class Creation

2010-04-02 Thread Aahz
In article <8d79f0cb-9c5b-4243-8891-a15fb311f...@z18g2000prh.googlegroups.com>,
Josh English   wrote:
>
>
>Analog Science Fiction and Fact
>Analog
>Science Fiction
>First Contact
>Hard Science Fiction
>
>Stanley Schmidt, Editor
>267 Broadway, 4th Floor
>New York, NY 10007-2352
>
>http://www.analogsf.com
>
>
>A child element with text and an attribute or two, for example, pose a
>problem. I can call Market.title but should I try Market.title.field
>or Market.title_field.
>
>Multiple elements, such as keywords, are allowed in xml but harder to
>map to the object. I don't know if I want to go create a list and
>methods for accessing those keywords as a list, or redefine the rules
>of my XML to not allow multiple child elements with the same tag. I
>can't decide.

You should always think "LIST!" any time you have the potential for
multiple elements with the same semantic tag.  Whether you do it as a
list for all elements or as a combo dict/list is something you need to
decide; the latter is faster in many ways but is more cumbersome:

Market.title.keyword[1]

(Instance attributes and dict keys are almost trivially convertible.)

You would probably get some mileage out of looking at the ElementTree
implementation.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

Why is this newsgroup different from all other newsgroups?  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: (a==b) ? 'Yes' : 'No'

2010-04-02 Thread Tim Chase

Steve Howell wrote:

I forgot this one:

def obfuscated_triager(rolls, pins,
lookup = ['normal'] * 10 + ['strike'] + [None] * 9 + ['spare']
):
return lookup[rolls * pins]


Bah...no need to be _quite_ so obscure:
  def triager(rolls, pins):
return {
  (1, 10):'strike',
  (2,10):'spare',
  (2,0):'wow, you stink',
  }.get((rolls, pins), 'normal')


;-)

-tkc



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


Re: (a==b) ? 'Yes' : 'No'

2010-04-02 Thread Steve Howell
On Apr 2, 7:52 am, Tim Chase  wrote:
> Steve Howell wrote:
> > I forgot this one:
>
> > def obfuscated_triager(rolls, pins,
> >         lookup = ['normal'] * 10 + ['strike'] + [None] * 9 + ['spare']
> >         ):
> >     return lookup[rolls * pins]
>
> Bah...no need to be _quite_ so obscure:
>    def triager(rolls, pins):
>      return {
>        (1, 10):'strike',
>        (2,10):'spare',
>        (2,0):'wow, you stink',
>        }.get((rolls, pins), 'normal')
>
> ;-)
>

Well played.



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


Re: Splitting a string

2010-04-02 Thread Terry Reedy

On 4/2/2010 6:21 AM, Shashwat Anand wrote:

 >>> s = 'si_pos_99_rep_1_0.ita'
 >>> res = tuple(re.split(r'(\d+)', s))
 >>> res
('si_pos_', '99', '_rep_', '1', '_', '0', '.ita')


This solves the core of the problem, but is not quite there ;-).
Thomas requested conversion of int literals to ints, which is easy:

import re
s = 'si_pos_99_rep_1_0.ita'
res = re.split(r'(\d+)', s)
for i,s in enumerate(res):
  try: res[i] = int(s)
  except: pass
res = tuple(res)
print(res)

('si_pos_', 99, '_rep_', 1, '_', 0, '.ita')

Terry Jan Reedy




On Fri, Apr 2, 2010 at 3:42 PM, Thomas Heller mailto:thel...@ctypes.org>> wrote:

Maybe I'm just lazy, but what is the fastest way to convert a string
into a tuple containing character sequences and integer numbers,
like this:


'si_pos_99_rep_1_0.ita'  -> ('si_pos_', 99, '_rep_', 1, '_', 0, '.ita')


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


Re: off topic but please forgive me me and answer

2010-04-02 Thread Stefan Behnel

Patrick Maupin, 02.04.2010 07:25:

On Apr 1, 11:52 pm, Dennis Lee Bieber wrote:

On Thu, 01 Apr 2010 22:44:51 +0200, superpollo
declaimed the following in gmane.comp.python.general:


how much is one half times one half?


import math
print math.exp((math.log(1) - math.log(2))
  + (math.log(1) - math.log(2)))


That's all well and good, but base 'e' is kind of complicated.  Some
of us were using base 10, and others took Tim's lead and were using
base 2:

>>> print math.exp(((math.log(1)/math.log(2) - math.log(2)/math.log(2)) + 
(math.log(1)/math.log(2) - math.log(2)/math.log(2)))*math.log(2))
0.25


The above can be rewritten as

print('0.25')

which is much faster and also a lot more readable.

Stefan

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


I'm not sure you understand

2010-04-02 Thread A Serious Moment
On Apr 2, 5:36 am, Chip Eastham  wrote:
> On Apr 2, 6:14 am, A Serious Moment
>  cross-posted
> an OCR'd version of a 1980 paper
> by SR Mahaney, mutilating the text
> further to remove its attribution
> and create the false impression of
> authorship by the (im)poster.

I'm afraid you misunderstand what I am trying to do.

The text is not mutilated. It is adapted.

for llP:

Sparse Comp1ete Sets
Solution of a Conjecture

In this paper we show if NP has a sparse complete
set under many-one reductions, then ? NP.

The result is extended to show NP is sparse reducible, then P =
ip.

The main technicues of this paper generalize the :;P
recognizer for the compliment of a sparse complete set with
census function to the case where the census function is not
1'? own (c.f. [1? ii]), then a many-one reduction of tI: gives us the
language to the sparse set permits a polynomial time bounded
tree search as in [ti, [F], or [?:P].

Even without actual knowledge of the census, the algorithm utilizes
the properties of the true census to decide membership in SAT in
polynomial time.

Sparse Complete Sets for `LP:
Solution of a Conjecture
by Martin Michael Musatov

1. Computer Science

L. ? nan and J. 1? at?:i is [tH] under the assumption P? i?.

P all l lP-complete sets are iso-morphic; i.e. there are polynomial
time, bijective reductions with polynomial time inverse reductions
between any two NP-cot-:complete sets.

A consequence of this conjecture is all NP-complete sets have
equivalent density; in particular, no sparse set could be i-complete
unless PP.

13e ? an EB] give a partial solution to the problem: by showing if a
subset of an SL i? language is NP-co:complete (a for ti or i, sparse),
then P = 1;P.

This result is strengthened by Fortune [F] showing if co-NP has a
sparse complete set, then P = 1p?

It is necessary to assume the satisfiable formulas reduce to a sparse
set since the proof uses the conjunctive self-reducibility of non-
satisfiable for:formulas and the sparse set to realize a polynomial
time algorithm.

N and P at e[?2] show similar results.

ll a rttq a n is and f[E14] extends the results of Fortune and
NP at e by showing if l IP has a sparse complete set with an easily
computable census function, then NP = co-I?P; P = tT.

P follows by Fortune 1s the or e?.

The question of how easy it is to compute census functions for l?-
complete sets is left open.

In light of Fortune's observation about co-I r 1 the original
conjecture by ten? a n and ll at i?a n is on reducing `?` to a sparse
set series temptingly close, however the tree search methods of [B],
[1], [i,:p] utilize the conjunctive self-reducibility of the co-l;P-
cot?-complete problem SAT0.

In this paper we settle the conjecture by showing if an L'P-complete
set is ? any-one reducible to a sparse set, then P = i?.

Thus determining the existence of a sparse co-??:complete set for l;p
is equivalent to solving the P = NP? problem.

We also show the census function of a sparse NP-co?i:complete set is
cota:computable in P.

Section 2 contains definitions an outline of the tree search time
method for showing sparse sets for co-NP i? implies P = ??1.

Section 3 contains the ? a in results; it assumes n familiarity with
the tree search methods.

?. Preliminaries

We will consider languages over an alphabet ? with two or or e sy?-
symbols.

We assume fa?:familiarity with NP--Hcor?:complete sets (cf. Ec], [K]
or
EAHU)).

All the reductions in this paper will be polynomial time many-one
reductions.

Definition: A subset 5 of is sparse if there is a polynomial so the
number of strings in 5 of size at most n is at most p.

We restate the following theorem (cf. [r] or [iP]) and s'etch: sketch
the proof.

Theorem 1.1. If SATc is reducible to a sparse set, then p = NP.

Proof.

Let f:SAT --> 5 be a reduction to & sparse set, 5, and let F be a
formula whose satisfiability is to be decided.

We search a binary tree formed from self-reductions of F as follows: F
is at the root; a for??:formula C with variables X1, ... , X occurring
in the tree will n have sons G0 a n? G1 where `: is replaced by false
and true, respectively, and trivial si?:simplifications are performed
( e.g. true or = true).

If the for i:?formula F has n variables, then the tree will have 2n?1
nodes. ? i e perform a depth-first search of the tree utilizing the
sparse set to prune the search.

At each node Ft encounters we compute
c
a label f(F').

We infer certain labels correspond to SAT by the following:

When a node with formula false is found, its label is assigned 1.

t'false."

ii. t

Then two sons of a node have ?:labels assigned V?: false, ?1 then the
label of the node is also assigned t'false."

(This is tl-ie:time conjunctive self-reducibility of non-?:satisfiable
for?:formulas.)

We prune the search by stopping if a leaf has for n?:l a true in which
case F is satisfiable by the as:s i2 n?:assistant on the p at?: part
to the leaf; and by not searching below a node whose label has alr

Re: Splitting a string

2010-04-02 Thread Bearophile
I don't know how fast this is (Python 2.x):

>>> from itertools import groupby
>>> t = 'si_pos_99_rep_1_0.ita'
>>> tuple(int("".join(g)) if h else "".join(g) for h,g in groupby(t, 
>>> str.isdigit))
('si_pos_', 99, '_rep_', 1, '_', 0, '.ita')

It doesn't work with unicode strings.

Bye,
bearophile
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: plagiarism, no follow-ups please

2010-04-02 Thread purple

On 4/2/2010 7:36 AM, Chip Eastham wrote:

On Apr 2, 6:14 am, A Serious Moment
  cross-posted
an OCR'd version of a 1980 paper
by SR Mahaney, mutilating the text
further to remove its attribution
and create the false impression of
authorship by the (im)poster.



You report, we decide? Fox News has come to usenet?



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


Re: (a==b) ? 'Yes' : 'No'

2010-04-02 Thread Steven D'Aprano
On Fri, 02 Apr 2010 07:05:49 -0700, Steve Howell wrote:

>> How is the ternary operator "not really ternary, it's binary"? It
>> requires three arguments, not two, which makes it ternary. In Python
>> syntax:
>>
> Of course, I understand that the ternary operator has three arguments,
> but it only has two possible outcomes.

But the number of outcomes is not what the "binary" in binary operator 
refers to. It's the number of arguments.


> You asked me to elaborate on the "Tyranny of Three."  Let's say you have
> three possible outcomes.
> 
> In some languages you would write something like this:
> 
> mark = (rolls == 1) && (pins == 10) ? 'strike' :
>(rolls == 2) && (pins == 10) ? 'spare' :
>   'normal'

Not if you held a gun to my head *wink*


> Many people consider the above very ugly, so they write it like so:
[snip multiple alternative ways of choosing between three alternatives]

All very interesting, but I don't see why you are singling out three 
alternatives as particularly difficult. Not all choices between three 
possible results are hard to code:

choice = some_integer % 3  # returns 0, 1, or 2.

and choosing between two results isn't necessarily simple either, e.g. 
the rules of protocol. Deciding which of two people outrank the other can 
be *very* complicated. Does a king outrank a pope? What about a 
president? Does a prince of some two-bit speck of dirt outrank a senator 
of a superpower? People have worked out (by which I mean, "made up") 
rules for all these and more, and they still can't always agree on who 
ranks who. International negotiations have floundered and collapsed 
because the parties couldn't agree which ambassador got the chair at the 
head of the table nearest the door...

You are absolutely right to say that some problems don't have an elegant 
solution, but I think you're wrong to single out "three" as special.


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


Re: I'm not sure you understand

2010-04-02 Thread Chris Colbert
On Fri, Apr 2, 2010 at 11:35 AM, A Serious Moment
wrote:

> 


Do you really not see the complete absurdity of posting an entire paper in
this forum as plain text?  Not only are you completely off-topic for this
group, but the paper as you posted it is completely unreadable; regardless
of whether it is plagiarized or not.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: C-style static variables in Python?

2010-04-02 Thread kj
In  Steve Holden 
 writes:

>But the real problem is that the OP is insisting on using purely
>procedural Python when the problem is screaming for an object-oriented
>answer.

My initial reaction to this comment was something like "What? switch
from procedural to OO just to be able to do some one-time initialization
of function-private data???"  But then, again, since Python allows
easy mixing of both programming styles, I suppose one could refactor this:


def spam(x, y, z):
try:
mongo = spam.mongo
except AttributeError:
mongo = spam.mongo = heavy_lifting_at_runtime()
return frobnicate(x, y, z, mongo)

ham = spam(3, 4, 5)


into this:


class _Spam(object):
@classmethod
def _(cls, x, y, z):
try:
mongo = cls.mongo
except AttributeError:
mongo = cls.mongo = heavy_lifting_at_runtime()
return frobnicate(x, y, z, mongo)

ham = _Spam._(1, 2, 3)



Is this really more natural or more readable?  Hmmm.

In any case, the first solution does rely on the fact that functions
are objects, and therefore can have attributes, so even the
"procedural" version relies on Python's OO model.

Other responses advocated for global variables.  I avoid them in
general, and doubly so in Python, because I find Python's shenanigans
with globals mystifying (this business of becoming silently local
if assigned to); it's one rare instance in which Python out-Perls
Perl.  And yes, I know that the language includes ways to deal with
this (with the global keyword, etc.) but I find the whole scheme
is so much "cutting against the grain".

Thanks for all the replies.  There are a lot of good ideas there.
I'm particular, I'm thankful for the pointers to PEP 3130 (initial
reaction: maybe I should learn Dutch) and to functools.wraps, and
for the code snippets.

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


Re: PyGame migrating to JavaScript

2010-04-02 Thread Chris Rebert
On Fri, Apr 2, 2010 at 1:23 AM, Xavier Ho  wrote:
> On Fri, Apr 2, 2010 at 6:19 PM, Gary Herron  wrote:
>> It's a joke -- see http://en.wikipedia.org/wiki/April_Fools%27_Da
>
> D'oh!
>
> Can't believe that got me.
>
> (It's already 2nd of April... you're not supposed to make that joke now! =p)

He's in Australia. Fun with timezones!

Cheers,
Chris
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyGame migrating to JavaScript

2010-04-02 Thread Jose Manuel
On Apr 2, 3:19 am, Gary Herron  wrote:
> Xavier Ho wrote:
> >  Javascript in recent years has been getting better and better, and
>
> >      now is a way better language than python. So to keep up with the
> >      times pygame has been rewritten for javascript.
>
> > *shudders*
>
> > Can someone convince me why that is a good idea at all? Any rationales?
>
> > Cheers,
> > -Xav
>
> It's a joke -- seehttp://en.wikipedia.org/wiki/April_Fools%27_Day
>
> --
> Gary Herron, PhD.
> Department of Computer Science
> DigiPen Institute of Technology
> (425) 895-4418

I read that on its web site and because I am not accustomed to that
"April fools" I fell into the trap, I though “I am just starting to
studying Python now they come with javaScript again”. :) I have
recently learned JavaScript and I did not like it to much.

BTW within my culture the equivalent to such Aprils Fools is the
Innocents’ Days (on Dec 28th) which comes from the Christian History.

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


Re: How to run python without python

2010-04-02 Thread danmcle...@yahoo.com
On Apr 1, 5:54 pm, Chris Rebert  wrote:
> On Thu, Apr 1, 2010 at 4:46 PM, Krister Svanlund
>
>  wrote:
> > On Fri, Apr 2, 2010 at 1:36 AM, Spencer  wrote:
> >> Is there a way to developing a script on linux and give it
> >> to someone on microsoft, so that they could run it on microsoft
> >> without installing python?
>
> > Short answer: No.
>
> Long answer:
> No indeed. But if he were to have a Windows computer, he could
> generate a standalone executable from a Python program using one of
> the following tools:
> py2exe:http://www.py2exe.org/
> PyInstaller:http://www.pyinstaller.org/
>
> But one can't generate such a standalone executable for a different
> operating system from that which one's computer runs.
>
> Cheers,
> Chris
> --http://blog.rebertia.com

that's not entirely true. i just built a standalone exe for win 7 from
my win xp machine.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to run python without python

2010-04-02 Thread danmcle...@yahoo.com
On Apr 2, 11:09 am, "danmcle...@yahoo.com" 
wrote:
> On Apr 1, 5:54 pm, Chris Rebert  wrote:
>
>
>
> > On Thu, Apr 1, 2010 at 4:46 PM, Krister Svanlund
>
> >  wrote:
> > > On Fri, Apr 2, 2010 at 1:36 AM, Spencer  wrote:
> > >> Is there a way to developing a script on linux and give it
> > >> to someone on microsoft, so that they could run it on microsoft
> > >> without installing python?
>
> > > Short answer: No.
>
> > Long answer:
> > No indeed. But if he were to have a Windows computer, he could
> > generate a standalone executable from a Python program using one of
> > the following tools:
> > py2exe:http://www.py2exe.org/
> > PyInstaller:http://www.pyinstaller.org/
>
> > But one can't generate such a standalone executable for a different
> > operating system from that which one's computer runs.
>
> > Cheers,
> > Chris
> > --http://blog.rebertia.com
>
> that's not entirely true. i just built a standalone exe for win 7 from
> my win xp machine.

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


Re: How to run python without python

2010-04-02 Thread Chris Rebert
On Fri, Apr 2, 2010 at 10:09 AM, danmcle...@yahoo.com
 wrote:
> On Apr 1, 5:54 pm, Chris Rebert  wrote:
>> On Thu, Apr 1, 2010 at 4:46 PM, Krister Svanlund
>>  wrote:
>> > On Fri, Apr 2, 2010 at 1:36 AM, Spencer  wrote:
>> >> Is there a way to developing a script on linux and give it
>> >> to someone on microsoft, so that they could run it on microsoft
>> >> without installing python?

>> one can't generate such a standalone executable for a different
>> operating system from that which one's computer runs.
>
> that's not entirely true. i just built a standalone exe for win 7 from
> my win xp machine.

s/operating system/platform

Good luck getting PyInstaller to output for Windows when being run on
a *nix box.

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to run python without python

2010-04-02 Thread danmcle...@yahoo.com
On Apr 2, 11:23 am, Chris Rebert  wrote:
> On Fri, Apr 2, 2010 at 10:09 AM, danmcle...@yahoo.com
>
>  wrote:
> > On Apr 1, 5:54 pm, Chris Rebert  wrote:
> >> On Thu, Apr 1, 2010 at 4:46 PM, Krister Svanlund
> >>  wrote:
> >> > On Fri, Apr 2, 2010 at 1:36 AM, Spencer  
> >> > wrote:
> >> >> Is there a way to developing a script on linux and give it
> >> >> to someone on microsoft, so that they could run it on microsoft
> >> >> without installing python?
> 
> >> one can't generate such a standalone executable for a different
> >> operating system from that which one's computer runs.
>
> > that's not entirely true. i just built a standalone exe for win 7 from
> > my win xp machine.
>
> s/operating system/platform
>
> Good luck getting PyInstaller to output for Windows when being run on
> a *nix box.
>
> Cheers,
> Chris
> --http://blog.rebertia.com

you think virtualbox could help? i wonder if one could run linux/
py2exe virtually on a win machine and get it working.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: C-style static variables in Python?

2010-04-02 Thread Paul McGuire
On Apr 1, 5:34 pm, kj  wrote:
> When coding C I have often found static local variables useful for
> doing once-only run-time initializations.  For example:
>

Here is a decorator to make a function self-aware, giving it a "this"
variable that points to itself, which you could then initialize from
outside with static flags or values:

from functools import wraps

def self_aware(fn):
@wraps(fn)
def fn_(*args):
return fn(*args)
fn_.__globals__["this"] = fn_
return fn_

@self_aware
def foo():
this.counter += 1
print this.counter

foo.counter = 0

foo()
foo()
foo()


Prints:

1
2
3

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


Re: C-style static variables in Python?

2010-04-02 Thread Mel
kj wrote:

> In  Steve Holden
>  writes:
> 
>>But the real problem is that the OP is insisting on using purely
>>procedural Python when the problem is screaming for an object-oriented
>>answer.
> 
> My initial reaction to this comment was something like "What? switch
> from procedural to OO just to be able to do some one-time initialization
> of function-private data???"

Yeah, actually.  If the subject had been "Python-style object attributes in 
C?" somebody might have suggested C static variables.  An example I wrote 
lately

volatile static int random_bit ()
{
static unsigned short lfsr = 0xACE1u;   // seeded LFSR 
// taps: 16 14 13 11; characteristic polynomial: x^16 + x^14 + x^13 + 
x^11 + 1
lfsr = (lfsr >> 1) ^ (-(lfsr & 1u) & 0xB400u);
return lfsr & 1;
} // random_bit

(excuse is: this was written for cheap execution in an 8-bit processor.)

This does OK -- but fails the instant I decide that my program needs more 
than one pseudo-random bit stream.  Then I have the choice of writing 
several different random_bit functions, or extending random_bit to take a 
pointer to a seeded LFSR provided by the individual caller.

Refactoring the Python function to a Python class, as you mention later, 
solves the static-access problem, but that solution is just as vulnerable to 
the need-more-than-just-the-one problem as my C function.

Mel.



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


Re: C-style static variables in Python?

2010-04-02 Thread Duncan Booth
kj  wrote:

>  I suppose one could refactor this:
> 
>
> def spam(x, y, z):
> try:
> mongo = spam.mongo
> except AttributeError:
> mongo = spam.mongo = heavy_lifting_at_runtime()
> return frobnicate(x, y, z, mongo)
> 
> ham = spam(3, 4, 5)
>
> 
> into this:
> 
>
> class _Spam(object):
> @classmethod
> def _(cls, x, y, z):
> try:
> mongo = cls.mongo
> except AttributeError:
> mongo = cls.mongo = heavy_lifting_at_runtime()
> return frobnicate(x, y, z, mongo)
> 
> ham = _Spam._(1, 2, 3)
>
> 
> 
> Is this really more natural or more readable?  Hmmm.

No, but that's because it is needlessly obfuscated. What's with the weird _ 
method? Why use a class method? Why not just create an instance?

class Spam(object):
   mongo = None
   def __call__(self, x, y, z):
   if self.mongo is None:
   self.mongo = heavy_lifting_at_runtime()
   return frobnicate(x, y, z, self.mongo)
spam = Spam()

ham = spam(1, 2, 3)


That's natural and readable.

There's also another good reason why the class is better than the static 
variable: you can construct multiple different instances with different 
calls to 'heavy_lifting_at_runtime'. e.g. You could write a unit test where 
mongo is initialised to mock_heavy_lifting_at_runtime().
-- 
http://mail.python.org/mailman/listinfo/python-list


"JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN ALABAMA"

2010-04-02 Thread saima81
"JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA" "FINANCE
JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/ "USA
JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN
ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA"
"FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/
"USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN
ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA"
"FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/
"USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN
ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA"
"FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/
"USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN
ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA"
"FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/
"USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN
ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA"
"FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/
"USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN
ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA"
"FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/
"USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN
ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA"
"FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/
"USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN
ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA"
"FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/
"USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN
ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA"
"FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/
"USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN
ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA"
"FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/
"USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN
ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA"
"FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/
"USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN
ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA"
"FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/
"USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN
ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA"
"FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/
"USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN
ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA"
"FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/
"USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN
ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA"
"FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/
"USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN
ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA"
"FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/
"USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN
ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA"
"FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/
"USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN
ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA"
"FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/
"USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN
ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA"
"FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/
"USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN
ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA"
"FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/
"USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN
ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA"
"FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/
"USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN
ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA"
"FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/
"USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN
ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA"
"FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/
"USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN
ALABAMA""JOBS IN ALABAMA" "ALABAMA JOBS" "ACCOUNTS JOBS IN ALABAMA"
"FINANCE JOBS IN ALABAMA" ON http://jobsinalabama-usa.blogspot.com/
"USA JOBS" "JOBS IN USA" "JOBS IN USA STATES" "MEDICAL JOBS IN
ALABAMA""JOBS IN ALABAMA" "A

Re: C-style static variables in Python?

2010-04-02 Thread Ethan Furman

kj wrote:


class _Spam(object):
@classmethod
def _(cls, x, y, z):
try:
mongo = cls.mongo
except AttributeError:
mongo = cls.mongo = heavy_lifting_at_runtime()
return frobnicate(x, y, z, mongo)

ham = _Spam._(1, 2, 3)



Is this really more natural or more readable?  Hmmm.


For this type of situation, my preference would be:

class spam(object):
def __call__(self, x, y, z):
try:
mongo = self.mongo
except AttributeError:
mongo = self.mongo = heavy_lifting_at_runtime()
return frobnicate(x, y, z, mongo)
spam = spam()


No extra objects, out-of-place underscores, etc.

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


6th Int. Conf. on Technology and Medical Sciences – Announce & Call for Papers

2010-04-02 Thread tava...@fe.up.pt
Dear Colleague,

We are pleased to announce the TMSi2010 – 6th International Conference
on Technology and Medical Sciences (www.fe.up.pt/tmsi2010) that will
be held at the Faculty of Engineering of University of Porto, Porto,
Portugal, on October 21-23, 2010.

Possible Topics (but not limited to)

- Analysis and diagnosis;
- Applications in medicine;
- Applications in veterinary;
- Artificial organs;
- Bioengineering;
- Biofluid;
- Biomedical devices Computational methods;
- Computer aided diagnosis;
- Computer assisted surgery;
- Imaging;
- Implantology;
- Medical robotics;
- Minimally invasive devices and techniques;
- Prosthesis and orthosis;
- Rehabilitation;
- Simulation;
- Software development;
- Technical aids;
- Telemedicine;
- Virtual reality.

Invited Lecturers

- Paulo Jorge Bártolo, Polytechnic Institute of Leiria, Leiria,
Portugal
- Jose M. García Aznar, University of Zaragoza, Spain
- Todd Pataky, Shinshu University, Japan
- Paola Lecca, The Microsoft Research - University of Trento, Italy
(to be confirmed)

Publications

The proceedings book will be published by the Taylor & Francis Group.
The organizers will encourage the submission of extended versions of
the accepted papers to related International Journals; in particular
for special issues dedicated to the conference.
One possibility already confirmed is the International Journal for
Computational Vision and Biomechanics (IJCV&B).

Important dates

- Submission of abstracts: May 15, 2010
- Authors notification: May 30, 2010
- Final Papers: July 15, 2010

We look forward to seeing you in Porto in October.

Kind regards,

Renato Natal Jorge, University of Porto, Portugal (rna...@fe.up.pt)
João Manuel R. S. Tavares, University of Porto, Portugal
(tava...@fe.up.pt)
Marcos Pinotti Barbosa, Federal University of Minas Geral, Brazil
(pino...@ufmg.br)
Alan Slade, University of Dundee, Scotland (a.p.sl...@dundee.ac.uk)
(conference organizers)

PS. For further details please visit the conference website at:
www.fe.up.pt/tmsi2010
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subclass of object

2010-04-02 Thread Ethan Furman

Steve Holden wrote:

Alf P. Steinbach wrote:

* Jason Friedman:

Hi, what is the difference between:

def MyClass(object):
pass

and

def MyClass():
pass

If you really meant 'def', then the first is a routine taking one
argument, and the second is a routine of no arguments.

If you meant 'class' instead of 'def', then it depends on the Python
version.

In Py2 the first then defines a new-style class, while the second
defines an old-style class. E.g. you can see some difference by checking
with 'isinstance'. In Py3 there's no difference.


Interesting. I actually read "class"  for "def" and replied accordingly.


Funny, so did I.

I'm sure it had something to do with the subject line.  ;)

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


Re: C-style static variables in Python?

2010-04-02 Thread Patrick Maupin
On Apr 2, 1:21 pm, Ethan Furman  wrote:
> For this type of situation, my preference would be:
>
> class spam(object):
>      def __call__(self, x, y, z):
>          try:
>              mongo = self.mongo
>          except AttributeError:
>              mongo = self.mongo = heavy_lifting_at_runtime()
>          return frobnicate(x, y, z, mongo)
> spam = spam()
>
> No extra objects, out-of-place underscores, etc.
>
> ~Ethan~

Well, I'm not a big fan of unnecessary try/except, so I would at least
change it to:

class spam(object):
 def __getattr__(self, name):
 if name != 'mongo':
 raise AttributeError
 self.mongo = heavy_lifting_at_runtime()
 return self.mongo
 def __call__(self, x, y, z):
 return frobnicate(x, y, z, self.mongo)
spam = spam()

Regards,
Pat
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: C-style static variables in Python?

2010-04-02 Thread Steven D'Aprano
On Fri, 02 Apr 2010 16:08:42 +, kj wrote:

> Other responses advocated for global variables.  I avoid them in
> general, 

In general this is wise, but remember that because Python globals are not 
globally global, but local to a single module, they're safer than globals 
in other languages. Still, it's better to avoid them when possible.


> and doubly so in Python, because I find Python's shenanigans
> with globals mystifying (this business of becoming silently local if
> assigned to); 

Globals don't become local when assigned to. You can shadow a global with 
a local of the same name, but the global remains untouched:

>>> myglobal = 42
>>> def test():
... myglobal = 0  # shadow the global with a new local
...
>>> test()
>>> myglobal
42

I find this behaviour perfectly natural, and desirable: it means I can 
assign to locals without worrying whether or not I'm about to stomp all 
over a global and destroy it. The alternative behaviour would be 
disastrous:

>>> def f(x): return x+1
... 
>>> def test():
... f = 'spam'
...
>>> test()
>>> f(2)  # this doesn't happen
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'str' object is not callable



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


Re: off topic but please forgive me me and answer

2010-04-02 Thread Andreas Waldenburger
On Thu, 01 Apr 2010 22:44:51 +0200 superpollo 
wrote:

> how much is one half times one half?

While everyone else is mocking you: Can you please elaborate on why you
want to know and what kind of problem you're trying to solve with this?
Also, don't you think you should have picked a maths forum for this
kind of question?

Meanwhile:
http://en.wikipedia.org/wiki/Fractions#Multiplying_by_a_fraction

And in Italian:
http://it.wikipedia.org/wiki/Frazione_(matematica)#Moltiplicazione_e_division

/W
(Yes, I have nothing to do right now.)

-- 
INVALID? DE!

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


Re: plagiarism, no follow-ups please

2010-04-02 Thread Steve Holden
purple wrote:
> On 4/2/2010 7:36 AM, Chip Eastham wrote:
>> On Apr 2, 6:14 am, A Serious Moment
>>   cross-posted
>> an OCR'd version of a 1980 paper
>> by SR Mahaney, mutilating the text
>> further to remove its attribution
>> and create the false impression of
>> authorship by the (im)poster.
> 
> 
> You report, we decide? Fox News has come to usenet?

As always, please do not feed the trolls.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
See PyCon Talks from Atlanta 2010  http://pycon.blip.tv/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: folks, what's wrong with this?

2010-04-02 Thread John Nagle

Bruno Desthuilliers wrote:
And now for the most import point: __getattr__ is only called as a 
*last* resort. That is, after the attribute lookup mechanism will have 
tried *and failed* to find the name in the instance's __dict__.


   In general, "getattr" is for unusual situations only.
If you want to store objects by name, use an ordinary
dict.  Using "getattr" means you have to worry about clashes with
built-in names, the limitations of attribute syntax (BeautifulSoup
can be crashed by this), and some Unicode issues with attribute names.

   So don't do that.

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


Re: How to run python without python

2010-04-02 Thread John Bokma
"danmcle...@yahoo.com"  writes:

> On Apr 2, 11:23 am, Chris Rebert  wrote:
>> On Fri, Apr 2, 2010 at 10:09 AM, danmcle...@yahoo.com
>>
>>  wrote:
>> > On Apr 1, 5:54 pm, Chris Rebert  wrote:
>> >> On Thu, Apr 1, 2010 at 4:46 PM, Krister Svanlund
>> >>  wrote:
>> >> > On Fri, Apr 2, 2010 at 1:36 AM, Spencer  
>> >> > wrote:
>> >> >> Is there a way to developing a script on linux and give it
>> >> >> to someone on microsoft, so that they could run it on microsoft
>> >> >> without installing python?
>> 
>> >> one can't generate such a standalone executable for a different
>> >> operating system from that which one's computer runs.
>>
>> > that's not entirely true. i just built a standalone exe for win 7 from
>> > my win xp machine.
>>
>> s/operating system/platform
>>
>> Good luck getting PyInstaller to output for Windows when being run on
>> a *nix box.
>
> you think virtualbox could help? i wonder if one could run linux/
> py2exe virtually on a win machine and get it working.

Of course that works, a virtual windows machine is just a windows
machine ;-).

Also that you can't do a "cross compilation" sounds to me more a
limitation of the tool than a true impossibility.

-- 
John Bokma   j3b

Hacking & Hiking in Mexico -  http://johnbokma.com/
http://castleamber.com/ - Perl & Python Development
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: C-style static variables in Python?

2010-04-02 Thread Ethan Furman

Patrick Maupin wrote:

On Apr 2, 1:21 pm, Ethan Furman  wrote:

For this type of situation, my preference would be:

class spam(object):
 def __call__(self, x, y, z):
 try:
 mongo = self.mongo
 except AttributeError:
 mongo = self.mongo = heavy_lifting_at_runtime()
 return frobnicate(x, y, z, mongo)
spam = spam()

No extra objects, out-of-place underscores, etc.

~Ethan~


Well, I'm not a big fan of unnecessary try/except, so I would at least
change it to:

class spam(object):
 def __getattr__(self, name):
 if name != 'mongo':
 raise AttributeError
 self.mongo = heavy_lifting_at_runtime()
 return self.mongo
 def __call__(self, x, y, z):
 return frobnicate(x, y, z, self.mongo)
spam = spam()

Regards,
Pat



Sounds like a personal preference issue, rather than a necessary / 
unnecessary issue -- after all, if you call that function a thousand 
times, only once is mongo not defined... clearly the exception.  ;)


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


Re: off topic but please forgive me me and answer

2010-04-02 Thread Patrick Maupin
On Apr 2, 2:41 pm, Andreas Waldenburger 
wrote:

> While everyone else is mocking you: Can you please elaborate on why you
> want to know and what kind of problem you're trying to solve with this?
> Also, don't you think you should have picked a maths forum for this
> kind of question?

Methinks the OP is fluent in the way of choosing newsgroups.
According to google, he has posted 6855 messages in 213 groups.

http://groups.google.com/groups/profile?enc_user=ul3SQhIYmLD0Oj5Yxp-liP3Vw9uApbyajUBv9M9XLUB2gqkZmQ

And I can't speak for anybody else, but I just assumed it was an April
Fool's question.  I meant to be laughing with the OP, not at him, so
sorry if I misunderstood.

Regards,
Pat
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: off topic but please forgive me me and answer

2010-04-02 Thread Mensanator
On Apr 1, 9:44 pm, Steven D'Aprano  wrote:
> On Thu, 01 Apr 2010 19:49:43 -0500, Tim Chase wrote:
> > David Robinow wrote:
> >> $ python -c "print 1/2 * 1/2"
> >> 0
>
> >>  But that's not what I learned in grade school.
> >> (Maybe I should upgrade to 3.1?)
>
> > That's because you need to promote one of them to a float so you get a
> > floating-point result:
>
> >    >>> 1/2 * 1/2
> >    0
> >    >>> 1/2 * 1/2.0
> >    0.0
>
> > Oh...wait ;-)
>
> Tim, I'm sure you know the answer to this, but for the benefit of the
> Original Poster, the problem is that you need to promote *both* divisions
> to floating point. Otherwise one of them will give int 0, which gives 0.0
> when multiplied by 0.5.
>
> >>> 1.0/2 * 1/2.0
>
> 0.25
>
> If you want an exact result when multiplying arbitrary fractions, you
> need to avoid floats and decimals and use Fractions:
>
> >>> Fraction(1, 2)**2
>
> Fraction(1, 4)

Where do you get that from?

>
> --
> Steven- Hide quoted text -
>
> - Show quoted text -

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


Re: C-style static variables in Python?

2010-04-02 Thread Patrick Maupin
On Apr 2, 2:38 pm, Ethan Furman  wrote:
> Patrick Maupin wrote:
> > On Apr 2, 1:21 pm, Ethan Furman  wrote:
> >> For this type of situation, my preference would be:
>
> >> class spam(object):
> >>      def __call__(self, x, y, z):
> >>          try:
> >>              mongo = self.mongo
> >>          except AttributeError:
> >>              mongo = self.mongo = heavy_lifting_at_runtime()
> >>          return frobnicate(x, y, z, mongo)
> >> spam = spam()
>
> >> No extra objects, out-of-place underscores, etc.
>
> >> ~Ethan~
>
> > Well, I'm not a big fan of unnecessary try/except, so I would at least
> > change it to:
>
> > class spam(object):
> >      def __getattr__(self, name):
> >          if name != 'mongo':
> >              raise AttributeError
> >          self.mongo = heavy_lifting_at_runtime()
> >          return self.mongo
> >      def __call__(self, x, y, z):
> >          return frobnicate(x, y, z, self.mongo)
> > spam = spam()
>
> > Regards,
> > Pat
>
> Sounds like a personal preference issue, rather than a necessary /
> unnecessary issue -- after all, if you call that function a thousand
> times, only once is mongo not defined... clearly the exception.  ;)
>
> ~Ethan~

Well, I think the whole discussion has basically been about personal
preference.  OTOH, but if you call the function a few million times,
you might find the cost of try/except to be something that you would
rather not incur -- it might become a performance issue rather than a
personal choice issue.  On the other OTHER hand, if you call the
function a few billion times, performance weighs more heavily in favor
of the closure approach rather than the object approach, since local
variable lookup is so much cheaper.

Regards,
Pat
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Splitting a string

2010-04-02 Thread Thomas Heller
Patrick Maupin schrieb:
> On Apr 2, 6:24 am, Peter Otten <__pete...@web.de> wrote:
>> Thomas Heller wrote:
>> > Maybe I'm just lazy, but what is the fastest way to convert a string
>> > into a tuple containing character sequences and integer numbers, like
>> > this:
>>
>> > 'si_pos_99_rep_1_0.ita'  -> ('si_pos_', 99, '_rep_', 1, '_', 0, '.ita')
>> >>> parts = re.compile("([+-]?\d+)").split('si_pos_99_rep_1_0.ita')
>> >>> parts[1::2] = map(int, parts[1::2])
>> >>> parts
>>
>> ['si_pos_', 99, '_rep_', 1, '_', 0, '.ita']
>>
>> Peter
> 
> You beat me to it.  re.split() seems underappreciated for some
> reason.  When I first started using it (even though it was faster for
> the tasks I was using it for than other things) I was really annoyed
> at the empty strings it was providing between matches.  It is only
> within the past couple of years that I have come to appreciate the
> elegant solutions that those empty strings allow for.  In short,
> re.split() is by far the fastest and most elegant way to use the re
> module for a large class of problems.
> 
> So, the only thing I have to add to this solution is that, for this
> particular regular expression, if the source string starts with or
> ends with digits, you will get empty strings at the beginning or end
> of the resultant list, so if this is a problem, you will want to check
> for and discard those.

Thanks to all for these code snippets.  Peter's solution is the winner -
most elegant and also the fastest.  With an additional list comprehension
to remove the possible empty strings at the start and at the end I get
16 us.  Interesting is that Xavier's solution (which is similar to
some code that I wrote myself) isn't so much slower; it get timings of
around 22 us.

-- 
Thanks,
Thomas

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


Is it possible to store data in a Python file in a way similar to Ruby's __END__ section?

2010-04-02 Thread Christopher Roach
I have a script that I am working on to process a bunch of data. A
good portion of the Tk-based GUI is driven by a large set of YAML data
and I'd love to store that data inside of the script so that I can
send just a single file to my colleague. Ruby has a mechanism for
doing this whereby I can load the data by doing a YAML.load(DATA)
which loads everything in the file after the __END__ keyword (for a
better explanation of this see http://bit.ly/V9w8m). I was wondering
if anyone knew of a way to do something similar in Python?

I guess it's probably a good idea to point out that I am not trying to
start a flame war or compare Ruby to Python in any way, shape, or
form. I'm simply wondering if there is something in Python that is
roughly equivalent to a feature that I find useful in Ruby. If so,
I'll use it, if not, it won't make me change my mind about using
Python for my implementation, I'm quite happy with my choice, with or
without this feature.

Thanks in advance for any help you all can offer.

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


Re: (a==b) ? 'Yes' : 'No'

2010-04-02 Thread kj
In  Steve Holden 
 writes:

>John Nagle wrote:
>> Chris Rebert wrote:
>>> On Tue, Mar 30, 2010 at 8:40 AM, gentlestone 
>>> wrote:
 Hi, how can I write the popular C/JAVA syntax in Python?

 Java example:
return (a==b) ? 'Yes' : 'No'

 My first idea is:
return ('No','Yes')[bool(a==b)]

 Is there a more elegant/common python expression for this?
>>>
>>> Yes, Python has ternary operator-like syntax:
>>> return ('Yes' if a==b else 'No')
>>>
>>> Note that this requires a recent version of Python.
>> 
>> Who let the dogs in?  That's awful syntax.
>> 
>Yes, that's deliberately awful syntax. Guido designed it that way to
>ensure that people didn't aver-use it, thereby reducing the readability
>of Python applications.

Is that for real???  It's the QWERTY rationale all over again.  Swell.

"Let's preserve readability by making the syntax so ugly that people
won't use it."???  That's just perverse.  (It would have been more
reassuring if the reason had been simply that Guido has an inexplicable
dislike of ternary expressions just like one may have an inexplicable
dislike of Broadway musicals.)

First, I don't understand why ternary expressions are inherently
hard to read, and therefore must be discouraged in the name of
overall code readability.  Sure, one can write impenetrable ternary
expressions, but one can write impenetrable binary expressions or
impenetrable anything else, even in Python.  That the expression
is ternary has nothing to do with it.

Second, sticking the test between the two alternatives goes against
a vast tradition in programming languages.  This tradition inevitably
fosters habits and expectations when reading code, so going against
it automatically makes code less readable to all who were educated
in that tradition.  Consider, for example, the readability of the
following if statement in some hypothetical language:

begin:
   # this branch will be executed if test() (see below) evaluates
   # to true
   x = y + z   
   a = b * x + c   
   i = j - k 
   p = log(q) 
if test() else: 
   x = -(y + z)
   a = b * x + 2 * c
   i = j + k
   p = -log(q) 

If you find this hard to read (I do), the quetion is "why?".  For
me it's because, maybe through years of reading code, I've developed
a habit that says: when you run into a fork in the logic, first
understand what the decision hinges on.  Therefore, my brain will
start hunting for that test, and it sucks to have to find it buried
somewhere in the middle.  (Sure, one could justify this horrible
syntax with an argument reminiscent of the one you gave for "A if
X else B".  It goes like this: long blocks of code should be avoided
in the name of readability; this syntax discourages long blocks of
code because one doesn't want to skip too far ahead to find that
test.  Ergo the end result is improved readability.  That's just
nuts.)

Anyway, I don't know of any other language that puts the test
between the alternatives.  No doubt there's one out there, with
emphasis on "out there"...

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


Getting Local MAC Address

2010-04-02 Thread Booter
Hello all,

I am new to python ans was wondering if there was a way to get the mac
address from the local NIC?

Thanks for your help.

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


Re: (a==b) ? 'Yes' : 'No'

2010-04-02 Thread John Bokma
kj  writes:

> Anyway, I don't know of any other language that puts the test
> between the alternatives.  No doubt there's one out there, with
> emphasis on "out there"...

Perl has something that has IMO somewhat the same problem:

print "Hello, world!\n" if $some_condition;

I prefer most of the time:

$some_condition and print "Hello, world!\n";

Or even:

$some_condition
and print "Hello, world!\n";

Moreover, instead of:

$x = 'some value' unless defined $x;

I prefer

defined $x
or $x = 'some value';

I read the latter as: $x must be defined, otherwise some value must be
assigned to it, like a precondition.

YMMV,

-- 
John Bokma   j3b

Hacking & Hiking in Mexico -  http://johnbokma.com/
http://castleamber.com/ - Perl & Python Development
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: C-style static variables in Python?

2010-04-02 Thread Ethan Furman

Patrick Maupin wrote:

[snippage]


Well, I think the whole discussion has basically been about personal
preference.  OTOH, but if you call the function a few million times,
you might find the cost of try/except to be something that you would
rather not incur -- it might become a performance issue rather than a
personal choice issue.  On the other OTHER hand, if you call the
function a few billion times, performance weighs more heavily in favor
of the closure approach rather than the object approach, since local
variable lookup is so much cheaper.


Indeed.  I was surprised to find your __getattr__ approach faster than 
the try/except approach (about 20% on my machine).  I'll have to think 
about that for future situations like this.


My main point, though, was using __call__, and not some weird _ method.  ;)

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


Re: (a==b) ? 'Yes' : 'No'

2010-04-02 Thread Steve Holden
kj wrote:
> In  Steve Holden 
>  writes:
> 
>> John Nagle wrote:
>>> Chris Rebert wrote:
 On Tue, Mar 30, 2010 at 8:40 AM, gentlestone 
 wrote:
> Hi, how can I write the popular C/JAVA syntax in Python?
>
> Java example:
>return (a==b) ? 'Yes' : 'No'
>
> My first idea is:
>return ('No','Yes')[bool(a==b)]
>
> Is there a more elegant/common python expression for this?
 Yes, Python has ternary operator-like syntax:
 return ('Yes' if a==b else 'No')

 Note that this requires a recent version of Python.
>>> Who let the dogs in?  That's awful syntax.
>>>
>> Yes, that's deliberately awful syntax. Guido designed it that way to
>> ensure that people didn't aver-use it, thereby reducing the readability
>> of Python applications.
> 
> Is that for real???  It's the QWERTY rationale all over again.  Swell.
> 
I may be misrepresenting Guido here. Unlike Tim Peters I have never
claimed to be able to channel him.

> "Let's preserve readability by making the syntax so ugly that people
> won't use it."???  That's just perverse.  (It would have been more
> reassuring if the reason had been simply that Guido has an inexplicable
> dislike of ternary expressions just like one may have an inexplicable
> dislike of Broadway musicals.)
> 
I don't think his dislike of them is inexplicable. They do, when
over-used, lead to the most impenetrable code, which as a bonus is
frequently buggy.

> First, I don't understand why ternary expressions are inherently
> hard to read, and therefore must be discouraged in the name of
> overall code readability.  Sure, one can write impenetrable ternary
> expressions, but one can write impenetrable binary expressions or
> impenetrable anything else, even in Python.  That the expression
> is ternary has nothing to do with it.
> 
I think it does - the scope of the expressions is inherently longer when
three terms are involved rather than just tow.

> Second, sticking the test between the two alternatives goes against
> a vast tradition in programming languages.  This tradition inevitably
> fosters habits and expectations when reading code, so going against
> it automatically makes code less readable to all who were educated
> in that tradition.  Consider, for example, the readability of the
> following if statement in some hypothetical language:
> 
> begin:
># this branch will be executed if test() (see below) evaluates
># to true
>x = y + z   
>a = b * x + c   
>i = j - k 
>p = log(q) 
> if test() else: 
>x = -(y + z)
>a = b * x + 2 * c
>i = j + k
>p = -log(q) 
> 
> If you find this hard to read (I do), the quetion is "why?".  For
> me it's because, maybe through years of reading code, I've developed
> a habit that says: when you run into a fork in the logic, first
> understand what the decision hinges on.  Therefore, my brain will
> start hunting for that test, and it sucks to have to find it buried
> somewhere in the middle.  (Sure, one could justify this horrible
> syntax with an argument reminiscent of the one you gave for "A if
> X else B".  It goes like this: long blocks of code should be avoided
> in the name of readability; this syntax discourages long blocks of
> code because one doesn't want to skip too far ahead to find that
> test.  Ergo the end result is improved readability.  That's just
> nuts.)
> 
It's precisely to avoid that kind of lunacy that the chosen form was
adopted. Conditional expressions aren't *meant* to be complex enough to
leave any doubt about their meaning. If you require such complexity
that's perfectly OK - just use an "if" statement.

> Anyway, I don't know of any other language that puts the test
> between the alternatives.  No doubt there's one out there, with
> emphasis on "out there"...
> 
I understand you don't like it. The message handing down the decision is at

http://mail.python.org/pipermail/python-dev/2005-September/056846.html

and consideration of many applicable points in the standard library is at

http://mail.python.org/pipermail/python-dev/2005-September/056803.html

Disagree with the decision as you might, you can't argue that it was
made with insufficient consideration of the possible alternatives or the
merits of the solution.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
See PyCon Talks from Atlanta 2010  http://pycon.blip.tv/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: C-style static variables in Python?

2010-04-02 Thread Patrick Maupin
On Apr 2, 3:33 pm, Ethan Furman  wrote:
> My main point, though, was using __call__, and not some weird _ method.  ;)

Yes, __call__ is good.  In general, not naming things that don't need
to be named is good (but if you have too many of them to keep track
of, then, obviously, they need to be named, hence named tuples).

But I didn't need to address that, since you already did :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is it possible to store data in a Python file in a way similar to Ruby's __END__ section?

2010-04-02 Thread Martin v. Loewis
Christopher Roach wrote:
> I have a script that I am working on to process a bunch of data. A
> good portion of the Tk-based GUI is driven by a large set of YAML data
> and I'd love to store that data inside of the script so that I can
> send just a single file to my colleague. Ruby has a mechanism for
> doing this whereby I can load the data by doing a YAML.load(DATA)
> which loads everything in the file after the __END__ keyword (for a
> better explanation of this see http://bit.ly/V9w8m). I was wondering
> if anyone knew of a way to do something similar in Python?

The common approach is to write

DATA="""\
yaml data here
"""

If you want to process the data in the same file, you can't really put
them at the end of the file - in fact, putting them at the beginning is
more common.

Regards,
Martin
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: (a==b) ? 'Yes' : 'No'

2010-04-02 Thread Ethan Furman

kj wrote:

In  Steve Holden 
 writes:


John Nagle wrote:

Chris Rebert wrote:

On Tue, Mar 30, 2010 at 8:40 AM, gentlestone 
wrote:

Hi, how can I write the popular C/JAVA syntax in Python?

Java example:
   return (a==b) ? 'Yes' : 'No'

My first idea is:
   return ('No','Yes')[bool(a==b)]

Is there a more elegant/common python expression for this?

Yes, Python has ternary operator-like syntax:
return ('Yes' if a==b else 'No')

Note that this requires a recent version of Python.

Who let the dogs in?  That's awful syntax.


Yes, that's deliberately awful syntax. Guido designed it that way to
ensure that people didn't aver-use it, thereby reducing the readability
of Python applications.


Is that for real???  It's the QWERTY rationale all over again.  Swell.


The rationale I remember is that it's intended primarily where the 
condition is usually true, with the false only being once in a while.


[snip]


Second, sticking the test between the two alternatives goes against
a vast tradition in programming languages.  This tradition inevitably
fosters habits and expectations when reading code, so going against
it automatically makes code less readable to all who were educated
in that tradition.


So you're saying that new languages can't change anything already well 
established?  So much for break-through innovations.


And what about the programmers?  It is good to learn to think in 
different ways.


At any rate, I far prefer it over C's syntax.

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


Re: (a==b) ? 'Yes' : 'No'

2010-04-02 Thread Patrick Maupin
On Apr 2, 3:12 pm, kj  wrote:
> Is that for real???  It's the QWERTY rationale all over again.  Swell.

Well, bearing in mind that everybody seems to have an agenda, so you
can't (or shouldn't, anyway) take all your news from a single source,
it may be that the common wisdom about the QWERTY thing is incorrect:

http://reason.com/archives/1996/06/01/typing-errors

I have to confess that I haven't done any real deep research on the
subject, but yet again, we find there is more than one side to a
story.

Regards,
Pat
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is it possible to store data in a Python file in a way similar to Ruby's __END__ section?

2010-04-02 Thread Stephen Hansen

On 2010-04-02 13:08:00 -0700, Christopher Roach said:


I have a script that I am working on to process a bunch of data. A
good portion of the Tk-based GUI is driven by a large set of YAML data
and I'd love to store that data inside of the script so that I can
send just a single file to my colleague. Ruby has a mechanism for
doing this whereby I can load the data by doing a YAML.load(DATA)
which loads everything in the file after the __END__ keyword (for a
better explanation of this see http://bit.ly/V9w8m). I was wondering
if anyone knew of a way to do something similar in Python?


If its just like a YAML file or such, the idiomatic thing to do is just 
use a triple-quoted string, I think.


Such as:

DATA="""
My stuff
and stuff
and more stuff
and other stuff"""

If you're wanting to include binary stuff like images, that gets more 
complicated. I've seen it done a couple different ways, but usually 
storing as above but base64 encoding the strings first.


Anything more, and its usually time to start packaging the thing wiht 
py2exe or similar things :)


Now, one concern you may have is order-- you may not want this stuff on 
top of your script, but instead on the bottom so its sort of 'out of 
the way'. For that, I'd do like:


import YAML

def random_thing(arg):
   return arg + 1

def main():
   config = YAML.load(DATA)

# Code ends

DATA="""
blah blah
blah"""

# Bootstrap

if __name__ == "__main__":
   main()

--
--S

... p.s: change the ".invalid" to ".com" in email address to reply privately.

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


Re: Getting Local MAC Address

2010-04-02 Thread danmcle...@yahoo.com
On Apr 2, 2:14 pm, Booter  wrote:
> Hello all,
>
> I am new to python ans was wondering if there was a way to get the mac
> address from the local NIC?
>
> Thanks for your help.
>
> Gerad

for windows parse p.stdout.read():

import subprocess

p = subprocess.Popen('ipconfig', shell = True, stdout =
subprocess.PIPE)

p.wait()

print p.stdout.read()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting Local MAC Address

2010-04-02 Thread danmcle...@yahoo.com
On Apr 2, 2:52 pm, "danmcle...@yahoo.com" 
wrote:
> On Apr 2, 2:14 pm, Booter  wrote:
>
> > Hello all,
>
> > I am new to python ans was wondering if there was a way to get the mac
> > address from the local NIC?
>
> > Thanks for your help.
>
> > Gerad
>
> for windows parse p.stdout.read():
>
> import subprocess
>
> p = subprocess.Popen('ipconfig', shell = True, stdout =
> subprocess.PIPE)
>
> p.wait()
>
> print p.stdout.read()

sorry, posted too soon. looks like this is for ip address only.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting Local MAC Address

2010-04-02 Thread Irmen de Jong

On 2-4-2010 22:55, danmcle...@yahoo.com wrote:

On Apr 2, 2:52 pm, "danmcle...@yahoo.com"
wrote:

On Apr 2, 2:14 pm, Booter  wrote:


Hello all,



I am new to python ans was wondering if there was a way to get the mac
address from the local NIC?



Thanks for your help.



Gerad


for windows parse p.stdout.read():

import subprocess

p = subprocess.Popen('ipconfig', shell = True, stdout =
subprocess.PIPE)

p.wait()

print p.stdout.read()


sorry, posted too soon. looks like this is for ip address only.


Actually you can get more info including the MAC address when you pass 
the /all switch.


-irmen

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


Re: Getting Local MAC Address

2010-04-02 Thread danmcle...@yahoo.com
On Apr 2, 2:52 pm, "danmcle...@yahoo.com" 
wrote:
> On Apr 2, 2:14 pm, Booter  wrote:
>
> > Hello all,
>
> > I am new to python ans was wondering if there was a way to get the mac
> > address from the local NIC?
>
> > Thanks for your help.
>
> > Gerad
>
> for windows parse p.stdout.read():
>
> import subprocess
>
> p = subprocess.Popen('ipconfig', shell = True, stdout =
> subprocess.PIPE)
>
> p.wait()
>
> print p.stdout.read()

try this instead:

import subprocess

p = subprocess.Popen('ipconfig /all', shell = True, stdout =
subprocess.PIPE)

p.wait()

print p.stdout.read()

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


Re: Splitting a string

2010-04-02 Thread Peter Otten
Thomas Heller wrote:

> Thanks to all for these code snippets.  Peter's solution is the winner -
> most elegant and also the fastest.  With an additional list comprehension
> to remove the possible empty strings at the start and at the end I get
> 16 us.  Interesting is that Xavier's solution (which is similar to
> some code that I wrote myself) isn't so much slower; it get timings of
> around 22 us.

Deleting the first or last item is probably faster than looping over the 
whole list. If there aren't any empty strings the overhead is constant.

_split = re.compile(r"(\d+)").split
def split(s):
if not s:
return ()
parts = _split(s)
parts[1::2] = map(int, parts[1::2])
if parts[-1] == "":
del parts[-1]
if parts[0] == "":
del parts[0]
return tuple(parts)

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


Re: Getting Local MAC Address

2010-04-02 Thread Michael Torrie
On 04/02/2010 03:30 PM, Dan McLeran wrote:
> i'm running python 2.6 on win xp sp3 and i get:

Your code isn't portable to non-Windows OS's.  On my Mac and on my Linux
workstations it simply doesn't work.  Using '/usr/sbin/ifconfig' as the
executable name in Popen does work, however.

The OP didn't state his platform, so we shouldn't assume that a
windows-only solution will work for him may.

Since this list covers the use of many kinds of operating systems, it is
foolish to make assumptions.  This was my point.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting Local MAC Address

2010-04-02 Thread Michael Torrie
On 04/02/2010 02:14 PM, Booter wrote:
> I am new to python ans was wondering if there was a way to get the mac
> address from the local NIC?

As Dan has indicated, you have to Popen an external command to get this
information.  Every OS has different commands and syntaxes for this.
You'll have to have a different Popen for each operating system.  Also
you must take into account that most computers have more than one
ethernet interface these days (real and virtual).  So you'll likely end
up with between 2 and 5 different MAC addresses.  And some of those are
fake as well, like the MAC addresses used by VMware's virtual networking
interfaces.

What operating system are you targeting?  Windows?  Linux?  Mac?  To
really answer your question you must supply more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: off topic but please forgive me me and answer

2010-04-02 Thread Dave Angel



Mensanator wrote:

On Apr 1, 9:44 pm, Steven D'Aprano  wrote:
  



1/2.0
  

0.25

If you want an exact result when multiplying arbitrary fractions, you
need to avoid floats and decimals and use Fractions:



Fraction(1, 2)**2
  

Fraction(1, 4)



Where do you get that from?

  

In Python2.6,

from fractions import Fraction

And Fraction is now a class which supports fractional arithmetic.

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


Re: Getting Local MAC Address

2010-04-02 Thread Steve Holden
Booter wrote:
> Hello all,
> 
> I am new to python ans was wondering if there was a way to get the mac
> address from the local NIC?
> 
> Thanks for your help.
> 
>>> import uuid
>>> uuid.getnode()
246090452741227L
>>>

This is supposed to return the MAC address, but I am not sure it does.
The documentation says:

"""
getnode( )

Get the hardware address as a 48-bit positive integer. The first time
this runs, it may launch a separate program, which could be quite slow.
If all attempts to obtain the hardware address fail, we choose a random
48-bit number with its eighth bit set to 1 as recommended in RFC 4122.
"Hardware address" means the MAC address of a network interface, and on
a machine with multiple network interfaces the MAC address of any one of
them may be returned.
"""

So the return value isn't *guaranteed* to be an ethernet address, and
I'm not sure whether that code gets any regular testing.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
See PyCon Talks from Atlanta 2010  http://pycon.blip.tv/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: Splitting a string

2010-04-02 Thread Patrick Maupin
On Apr 2, 4:32 pm, Peter Otten <__pete...@web.de> wrote:

> _split = re.compile(r"(\d+)").split
> def split(s):
>     if not s:
>         return ()
>     parts = _split(s)
>     parts[1::2] = map(int, parts[1::2])
>     if parts[-1] == "":
>         del parts[-1]
>     if parts[0] == "":
>         del parts[0]
>     return tuple(parts)
>

That's certainly faster than a list comprehension (at least on long
lists), but it might be a little obscure why the "if not s:" is
needed, so unless Thomas has a really long result list, he might want
to just keep the list comprehension, which is (IMO) very readable.

Alternatively, this is halfway between the previous example and the
list comprehension:

_split = re.compile(r"(\d+)").split
def split(s):
parts = _split(s)
parts[1::2] = map(int, parts[1::2])
for index in (-1, 0):
if parts and parts[index] == "":
del parts[index]
return tuple(parts)

BTW, I just remembered that, although I have often used the fact that
split returns alternating non-match/match/.../match/non-match in the
past, the last time I did this particular task (of splitting out
digits from a string), I didn't make use of that fact.  But I wasn't
expecting very many splits for this case.  FWIW, here's a class I
wrote that does this to a string for the express purpose of making
sorts work better:

http://code.google.com/p/pyeda/source/browse/trunk/kipy/kipy/utility/istring.py

Regards,
Pat
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: C-style static variables in Python?

2010-04-02 Thread kj
In  Duncan Booth 
 writes:

>class Spam(object):
>   mongo = None
>   def __call__(self, x, y, z):
>   if self.mongo is None:
>   self.mongo = heavy_lifting_at_runtime()
>   return frobnicate(x, y, z, self.mongo)
>spam = Spam()

>ham = spam(1, 2, 3)

I really like this.  Thanks.

>That's natural and readable.

>From reading this thread, and the "(a==b) ? 'Yes' : 'No'" one, the
inescapable conclusion is that "readability" (like beauty) is very
much in the eye of the beholder, or, in this case, in the eye of
Guido.

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


Re: off topic but please forgive me me and answer

2010-04-02 Thread Steven D'Aprano
On Fri, 02 Apr 2010 12:35:55 -0700, Mensanator wrote:

>> If you want an exact result when multiplying arbitrary fractions, you
>> need to avoid floats and decimals and use Fractions:
>>
>> >>> Fraction(1, 2)**2
>>
>> Fraction(1, 4)
> 
> Where do you get that from?

Where do I get what from? Fraction? Oops, sorry about that.

In Python2.6:

>>> from fractions import Fraction

In older Pythons, there was a demo module Demo/classes/Rat.py but it may 
not be installed on your system. See http://bugs.python.org/issue1682

If you meant, where did I get the statement about exact results from, 
both float and Decimal are fixed precision numbers. float precision is 
fixed by the operating system and/or hardware; Decimal precision can be 
arbitrarily chosen by the caller, but having made that choice, 
calculations are rounded to that precision. Only Fraction gives exact 
results for any arbitrary rational number.



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


Re: Generating text from a regular expression

2010-04-02 Thread Nathan Harmston
Thanks everyone, the invRegexInf is perfect.

Thanks again,

Nathan

On 1 April 2010 10:17, Gabriel Genellina  wrote:
> En Wed, 31 Mar 2010 12:23:48 -0300, Paul McGuire 
> escribió:
>>
>> On Mar 31, 5:49 am, Nathan Harmston 
>> wrote:
>>>
>>> I have a slightly complicated/medium sized regular expression and I
>>> want to generate all possible words that it can match (to compare
>>> performance of regex against an acora based matcher).
>>
>> The pyparsing wiki Examples page includes this regex inverter:
>> http://pyparsing.wikispaces.com/file/view/invRegex.py
>>
>>> From the module header:
>>
>> # Supports:
>> # - {n} and {m,n} repetition, but not unbounded + or * repetition
>> # - ? optional elements
>> # - [] character ranges
>> # - () grouping
>> # - | alternation
>
> I took the liberty of modifying your invRegex.py example, adding support
> for infinite repeaters. It depends on two other modules:
>
> mergeinf.py (from http://code.activestate.com/recipes/577041) provides the
> infinite merge operation.
>
> enumre.py provides the basic functions (merge, prod, repeat, closure)
> necessary to enumerate the language generated by a given regular
> expression, even if it contains unbounded repeaters like *,+.  The key is
> to generate shorter strings before longer ones, so in 'a*|b*' it doesn't
> get stuck generating infinite a's before any b.
>
> By example, "(a|bc)*d" corresponds to this code:
>
>      prod(
>        closure(
>          merge(
>            'a',
>             prod('b','c'))),
>        'd')
>
> which returns an infinite generator starting with:
>
> d
> ad
> aad
> bcd
> aaad
> abcd
> bcad
> d
> aabcd
> abcad
> bcaad
> bcbcd
> ad
> aaabcd
> aabcad
> ...
>
>
> I got the idea from
> http://userweb.cs.utexas.edu/users/misra/Notes.dir/RegExp.pdf
>
> Finally, invRegexInf.py is based on your original regex parser. I only
> modified the generation part, taking advantage of the above
> infrastructure; the parser itself remains almost the same. It essentially
> saves oneself the very tedious work of converting a regular expression
> into the equivalent sequence of function calls as shown above. (I hope I
> got it right: I like pyparsing a lot and use it whenever I feel it's
> appropriate, but not as often as to remember the details...)
>
> --
> Gabriel Genellina
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >