Re: sort functions in python

2008-02-09 Thread Steven D'Aprano
On Fri, 08 Feb 2008 19:09:06 -0800, Jeff Schwab wrote:

> Steven D'Aprano wrote:
>> On Fri, 08 Feb 2008 17:00:27 -0800, t3chn0n3rd wrote:
>> 
>>> Do you think it is relatively easy to write sort algorithms such as
>>> the common Bubble sort in Python as compared to other high level
>>> programming langauges
>> 
>> 
>> You realise that bubble sort is one of the worst possible sort
>> algorithms possible, particularly on modern hardware? It's not the
>> worst: bogo sort and bozo sort are worse, but bubble sort is still
>> pretty atrocious.
> 
> That's the conventional wisdom, mostly because CS professors need a "bad
> algorithm" to show undergrads, but it's not really accurate.  The truth
> is that bubble-sort's performance depends strongly on the input data. In
> the worst case, yes, bubble-sort is O(n^2); however, for almost-sorted
> data (only a few elements out of place), bubble-sort is actually one of
> the fastest known algorithms.

It depends on what you mean by "bubble sort". There are many different 
variations of bubble sort, that are sometimes described by names such as 
comb sort, cocktail sort, exchange sort, and sometimes merely referred to 
bubble sort. It's rather like any divide-and-conquer sorting algorithm 
being called quicksort.

I'm as guilty of that as anyone else -- the example code I posted, raided 
from Wikibooks is very different from this bubble sort algorithm from 
PlanetMath:

http://planetmath.org/encyclopedia/Bubblesort.html

def bubblesort(L):
done = False
while not done:
done = True
for i in xrange(len(L)-1):
if L[i+1] <= L[i]:
L[i], L[i+1] = L[i+1], L[i]
done = False
return L

This one runs significantly faster than the earlier one I posted.

Another vital factor is, what language are you implementing the sort 
routine in? The conventional wisdom for low-level languages like assembly 
and C doesn't necessarily hold for high-level languages like Python. 
Comparisons are slow in Python and fast in C; in C a good algorithm will 
minimize the amount of moves, while in Python a good algorithm will 
minimize the number of comparisons.

Finally, what hardware are you running on? There are interactions between 
hardware caches and pipes that can ruin the performance of an otherwise 
promising algorithm.


But all those factors aside, I fear that your attempt to rehabilitate the 
reputation of bubble sort is misplaced. Here's another person who wants 
to defend bubble sort:

"A fair number of algorithm purists (which means they've probably never 
written software for a living) claim that the bubble sort should never be 
used for any reason. Realistically, there isn't a noticeable performance 
difference between the various sorts for 100 items or less, and the 
simplicity of the bubble sort makes it attractive."

http://linux.wku.edu/~lamonml/algor/sort/bubble.html

But then on the same person's page on insertion sort:

"The insertion sort is a good middle-of-the-road choice for sorting lists 
of a few thousand items or less. The algorithm is significantly simpler 
than the shell sort, with only a small trade-off in efficiency. At the 
same time, the insertion sort is over twice as fast as the bubble sort 
and almost 40% faster than the selection sort."

http://linux.wku.edu/~lamonml/algor/sort/insertion.html

He gives sample C code for both, and the bubble sort has eight lines of 
code, versus nine for insertion sort (excluding bare braces).

Perhaps what he should have said is:

"Bubble sort is a tiny bit simpler than insertion sort, and almost twice 
as slow!"



-- 
Steven

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


troika 2008

2008-02-09 Thread bots
Hello programmers,

IEEE Student branch, Delhi College of Engineering
invites you to be a part of its much awaited technical fest
TROIKA '08

Get ready to enter the battle where your analytical skills and mental
acumen are tested to their maximum, where time runs fast and beating
the odds is a dire necessity.
Welcome to the BITS, BYTES & BOTS saga, a battlefield where the
brainstormers fight to rule the binary world. Code hard and fast and
you might be the next king in town.

Exciting cash prizes to be won!!!

BITS: On-site programming
The event is held on a two-tier basis. The Prelims consist of an
elimination round from which the top coders will be selected for the
final programming challenge. Whilst logic might be the strongest, the
time slips away fast. Grab the chance to make it a win of a lifetime.

Registration has started for the event.
Event date: 19th Feb, 2008
For details see www.troika.dcetech.com
Queries & Registration: [EMAIL PROTECTED]

BYTES: Overnight Online Programming Contest
The event consists of a single round of programming contest in which
the participants code among the toughest of competitors. But if your
logic is right, you may outrun the best of the best. Be a part of
BYTES and let the race begin.

Registrations open.
Event date: 16th Feb, 2008
For details see www.troika.dcetech.com
Queries & Registration: [EMAIL PROTECTED]

BOTS: Virtual-Bot Programming Contest
Based on the theme of the Pirates of the Caribbean, in this
programming contest you develop a code to run a virtual bot. The task
is to find a path to move objects to their destinations avoiding all
possible obstacles and hindrances. Sure the going is tough and the
enemies are strong, but get your moves right and you will be surprised
with the rewards that come your way.

Problem statement released.
Event date: 20th Feb, 2008
For details see www.troika.dcetech.com
Queries & Registration: [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pure Python Salsa20 Stream Cipher Implementation

2008-02-09 Thread Paul Rubin
[EMAIL PROTECTED] writes:
> The reason for a pure python is that it would be independent from the
> platform. A C implementation is faster, but you need to compile it for
> every platform. A python implementation doesn't have that problem and
> could be used to fall back upon.

But why salsa20 in that case, unless it's approved as a standard?  If
you're willing to put up with terrible performance in the fallback
implementation, you may as well use AES, which is a standard.  If you
want reasonable performance in the fallback implementation, use
one of the hashlib functions as a cipher.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pure Python Salsa20 Stream Cipher Implementation

2008-02-09 Thread Paul Rubin
"Gabriel Genellina" <[EMAIL PROTECTED]> writes:
> On most platforms -with a notable exception- there is a C compiler
> available as a standard tool, which is used to compile Python itself.

The notable exception that you're thinking of is pervasive, but since
Python is usually distributed as a binary for those systems, there
might as well also be a binary crypto module, and in fact there are
quite a few.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: multi-Singleton-like using __new__

2008-02-09 Thread Hrvoje Niksic
Matt Nordhoff <[EMAIL PROTECTED]> writes:

> Steven D'Aprano wrote:
>> Except that using has_key() means making an attribute lookup, which takes 
>> time.
>
> I was going to say that, but doesn't 'in' require an attribute lookup of
> some sort too, of __contains__ or whatever?

It doesn't.  Frequent operations like __contains__ are implemented as
slots in the C struct describing the type.  The code that implements
"obj1 in obj2" simply executes something like:

result = obj1->ob_type->tp_contains(obj2);  // intentionally simplified

User-defined types (aka new-style classes) contain additional magic
that react to assignment to YourType.__contains__ (typically performed
while the class is being built), to which they react by setting
"tp_contains" to a C wrapper that calls the intended function and
interprets the result.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to run python script on remote machine

2008-02-09 Thread Tim Golden
Tim Golden wrote:
> ... You can, for example, use DCOM to instantiate a
> remote Python interpreter but the rest you probably be quite hard
> word.

(Ahem!) Or maybe:

You can, for example, use DCOM to instantiate a
remote Python interpreter but doing the rest you'll
probably find quite hard work.

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


Re: which one is more efficient

2008-02-09 Thread bearophileHUGS
Michael Spencer:
> # perhaps faster
> $ python -mtimeit -s"t='D'" "if t in 'DE': pass"
> 100 loops, best of 3: 0.204 usec per loop

That may be faster indeed, but it gives true if t is "DE" too, and
that may be bad.
The new string search done by Effbot is really good :-)

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


online marketing make money

2008-02-09 Thread sam
It is new one online business you can earn minimum 1000$ per month
great oppertunity to students,house wives,retired persons andall
others .
http://onlinemarketingmakemoney.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pure Python Salsa20 Stream Cipher Implementation

2008-02-09 Thread bearophileHUGS
Gabriel Genellina:
> On most platforms -with a notable exception- there is a C compiler
> available as a standard tool, which is used to compile Python itself.

For that platform the Python site may offer a version of binary Python
bundled with the MingGW (and Cython too, maybe), like ShedSkin does.

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


Recursion limit of pickle?

2008-02-09 Thread Victor Lin
Hi,

I encounter a problem with pickle.
I download a html from:

http://www.amazon.com/Magellan-Maestro-4040-Widescreen-Navigator/dp/B000NMKHW6/ref=sr_1_2?ie=UTF8&s=electronics&qid=1202541889&sr=1-2

and parse it with BeautifulSoup.
This page is very huge.
When I use pickle to dump it, a RuntimeError: maximum recursion depth
exceeded occur.
I think it is cause by this problem at first :

http://bugs.python.org/issue1757062

But and then I do not think so, because I log recursion call of pickle
in file
I found that the recursion limit is exceeded in mid-way to expand
whole the BeautifulSoup object.
Not repeat to call some methods.

This is the code for test.

from BeautifulSoup import *

import pickle as pickle
import urllib

doc = urllib.urlopen('http://www.amazon.com/Magellan-Maestro-4040-
Widescreen-Navigator/dp/B000NMKHW6/ref=sr_1_2?
ie=UTF8&s=electronics&qid=1202541889&sr=1-2')

import sys
sys.setrecursionlimit(4)

soup = BeautifulSoup(doc)
print pickle.dumps(soup)

---
What I want to ask is: Is this cause by the limit of recursion limit
and stack size?

I had tired cPickle at first, and then I try pickle, cPickle just stop
running program without any message.
I think it is also implement with recursion way, and it also over flow
stack when dumping soup.

Are there any version of pickle that implement with no-recursion way?

Thanks.

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


Edit Python code programmatically

2008-02-09 Thread Alex
Which library could you recommend to perform simple editing of Python 
code (from Python program)? For example, open *.py file, find specific 
function definition, add another function call inside, find existing 
call and change parameter value, etc.

What I'm trying to implement isn't a real visual programming tool, but 
some code-generation is necessary. For now I think I can generate Python 
syntax manually (like any text file), but it can become more complicated 
in future (like partially implementing code-generation library), plus 
there'll always be possibility of corrupting files and losing data (or 
having to recover valid Python syntax manually) due to coding mistake.

Thanks

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


Re: Edit Python code programmatically

2008-02-09 Thread Guilherme Polo
2008/2/9, Alex <[EMAIL PROTECTED]>:
> Which library could you recommend to perform simple editing of Python
>  code (from Python program)? For example, open *.py file, find specific
>  function definition, add another function call inside, find existing
>  call and change parameter value, etc.
>

You are after inspect, it is included with python.

>  What I'm trying to implement isn't a real visual programming tool, but
>  some code-generation is necessary. For now I think I can generate Python
>  syntax manually (like any text file), but it can become more complicated
>  in future (like partially implementing code-generation library), plus
>  there'll always be possibility of corrupting files and losing data (or
>  having to recover valid Python syntax manually) due to coding mistake.
>

Generating code like this is always dangerous. Maybe you could
generate some other kind of file, then use some library or build one,
to operator over this file.

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


-- 
-- Guilherme H. Polo Goncalves
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Edit Python code programmatically

2008-02-09 Thread Ben Finney
Alex <[EMAIL PROTECTED]> writes:

> Which library could you recommend to perform simple editing of
> Python code (from Python program)? For example, open *.py file, find
> specific function definition, add another function call inside, find
> existing call and change parameter value, etc.

You might want to look into the Python refactoring tool "Bicycle
Repair Man" http://bicyclerepair.sourceforge.net/>, which
presumably needs to do some of this.

-- 
 \"I washed a sock. Then I put it in the dryer. When I took it |
  `\  out, it was gone."  -- Steven Wright |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Edit Python code programmatically

2008-02-09 Thread Alex
Guilherme Polo wrote:
> 2008/2/9, Alex <[EMAIL PROTECTED]>:
>   
>> Which library could you recommend to perform simple editing of Python
>>  code (from Python program)? For example, open *.py file, find specific
>>  function definition, add another function call inside, find existing
>>  call and change parameter value, etc.
> You are after inspect, it is included with python.
Yes, I forgot to mention - I'm new to Python. I didn't necessary mention 
3rd party library. Simply such wasn't mentioned in library review and 
tutorials, so I didn't know of it. What's the module's name?
>> What I'm trying to implement isn't a real visual programming tool, but
>>  some code-generation is necessary. For now I think I can generate Python
>>  syntax manually (like any text file), but it can become more complicated
>>  in future (like partially implementing code-generation library), plus
>>  there'll always be possibility of corrupting files and losing data (or
>>  having to recover valid Python syntax manually) due to coding mistake.
> Generating code like this is always dangerous. Maybe you could
> generate some other kind of file, then use some library or build one,
> to operator over this file.
No, the code by itself is the goal.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Edit Python code programmatically

2008-02-09 Thread Alex
Steven D'Aprano wrote:
> On Sat, 09 Feb 2008 14:38:29 +0300, Alex wrote:
>
>   
>> Which library could you recommend to perform simple editing of Python
>> code (from Python program)? 
>> 
>
> I'm not even sure such a library exists.
>   
Yes they exist, that field is called "code-generation", "generative 
programming" etc.
>
>   
>> For example, open *.py file, find specific
>> function definition, add another function call inside, find existing
>> call and change parameter value, etc.
>> 
>
> Why do you want to do that? I'm not sure what you're trying to 
> accomplish. Code refactoring? I imagine that's probably best done with 
> your text editor: at best, your editor will have dedicated refactoring 
> tools, and at worst, it will have global search and replace.
I don't feel like describing all ideas - it's nothing really intersting 
anyway, just a learning project (to get to know language features), but 
obviously it's not for regular programming - I know text editors can do 
that just fine. Simply in some situation I think instead of generating 
data I'd better generate some code.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: which one is more efficient

2008-02-09 Thread Steven D'Aprano
On Sat, 09 Feb 2008 02:08:15 -0800, bearophileHUGS wrote:

> The new string search done by Effbot is really good :-)


Care to explain what "new string search" you're referring to? Inquiring 
minds want to know.



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


Re: Edit Python code programmatically

2008-02-09 Thread Steven D'Aprano
On Sat, 09 Feb 2008 14:38:29 +0300, Alex wrote:

> Which library could you recommend to perform simple editing of Python
> code (from Python program)? 

I'm not even sure such a library exists.


> For example, open *.py file, find specific
> function definition, add another function call inside, find existing
> call and change parameter value, etc.

Why do you want to do that? I'm not sure what you're trying to 
accomplish. Code refactoring? I imagine that's probably best done with 
your text editor: at best, your editor will have dedicated refactoring 
tools, and at worst, it will have global search and replace.



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


Re: multi-Singleton-like using __new__

2008-02-09 Thread Arnaud Delobelle
On Feb 9, 1:38 am, Freek Dijkstra <[EMAIL PROTECTED]> wrote:
> J Peyret wrote:
[...]
> I'll use __metaclass__ solution. Here is my (non-threaded) version:

Great! There's nothing voodoo about metaclasses.

> class RDFObject(object):
>     _cache = {}   # class variable is shared among all RDFObject
> instances
>     class __metaclass__(type):
>         def __call__(cls, *args, **kwargs):
>             return cls.__new__(cls, *args, **kwargs)
>     def __new__(cls, uri, *args, **kargs):
>         if uri not in cls._cache:
>             obj = object.__new__(cls)
>             cls._cache[uri] = obj
>             obj.__init__(uri, *args, **kargs)
>         return cls._cache[uri]
>     def __init__(self, uri):
>         self.uri = uri
>         print self.__class__, uri
>     # ...
[...]
> Perhaps indeed the try...except KeyError is even prettier (no idea
> about speed, but let's rename this thread if we want to discuss
> performance measurements).

I would go for something like (untested):

def __new__(cls, uri, *args, **kwargs):
obj = cls._cache.get(uri, None):
if obj is None:
obj = cls._cache[uri] = object.__new__(cls)
obj.__init__(uri, *args, **kwargs)
return obj

It doesn't look up the cache sho much and I think reads just as well.

--
Arnaud

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


Re: Edit Python code programmatically

2008-02-09 Thread Dustan
On Feb 9, 6:10 am, Alex <[EMAIL PROTECTED]> wrote:
> Guilherme Polo wrote:
> > 2008/2/9, Alex <[EMAIL PROTECTED]>:
>
> >> Which library could you recommend to perform simple editing of Python
> >>  code (from Python program)? For example, open *.py file, find specific
> >>  function definition, add another function call inside, find existing
> >>  call and change parameter value, etc.
> > You are after inspect, it is included with python.
>
> Yes, I forgot to mention - I'm new to Python. I didn't necessary mention
> 3rd party library. Simply such wasn't mentioned in library review and
> tutorials, so I didn't know of it. What's the module's name?

inspect.

>> What I'm trying to implement isn't a real visual programming tool, but
> >>  some code-generation is necessary. For now I think I can generate Python
> >>  syntax manually (like any text file), but it can become more complicated
> >>  in future (like partially implementing code-generation library), plus
> >>  there'll always be possibility of corrupting files and losing data (or
> >>  having to recover valid Python syntax manually) due to coding mistake.
> > Generating code like this is always dangerous. Maybe you could
> > generate some other kind of file, then use some library or build one,
> > to operator over this file.
>
> No, the code by itself is the goal.

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


Re: Edit Python code programmatically

2008-02-09 Thread Guilherme Polo
2008/2/9, Alex <[EMAIL PROTECTED]>:
> Guilherme Polo wrote:
>  > 2008/2/9, Alex <[EMAIL PROTECTED]>:
>  >
>  >> Which library could you recommend to perform simple editing of Python
>  >>  code (from Python program)? For example, open *.py file, find specific
>  >>  function definition, add another function call inside, find existing
>  >>  call and change parameter value, etc.
>  > You are after inspect, it is included with python.
>
> Yes, I forgot to mention - I'm new to Python. I didn't necessary mention
>  3rd party library. Simply such wasn't mentioned in library review and
>  tutorials, so I didn't know of it. What's the module's name?

inspect is a module, inspect is the name. It is not a module for
editing Python code per se, but it will help with the other part.

>
> >> What I'm trying to implement isn't a real visual programming tool, but
>  >>  some code-generation is necessary. For now I think I can generate Python
>  >>  syntax manually (like any text file), but it can become more complicated
>  >>  in future (like partially implementing code-generation library), plus
>  >>  there'll always be possibility of corrupting files and losing data (or
>  >>  having to recover valid Python syntax manually) due to coding mistake.
>  > Generating code like this is always dangerous. Maybe you could
>  > generate some other kind of file, then use some library or build one,
>  > to operator over this file.
>
> No, the code by itself is the goal.
>
> --
>
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
-- Guilherme H. Polo Goncalves
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Edit Python code programmatically

2008-02-09 Thread Guilherme Polo
2008/2/9, Arnaud Delobelle <[EMAIL PROTECTED]>:
> On Feb 9, 12:32 pm, "Guilherme Polo" <[EMAIL PROTECTED]> wrote:
>  > 2008/2/9, Alex <[EMAIL PROTECTED]>:
>  >
>  > > Guilherme Polo wrote:
>  > >  > 2008/2/9, Alex <[EMAIL PROTECTED]>:
>
> >
>  > >  >> Which library could you recommend to perform simple editing of Python
>  > >  >>  code (from Python program)? For example, open *.py file, find 
> specific
>  > >  >>  function definition, add another function call inside, find existing
>  > >  >>  call and change parameter value, etc.
>  > >  > You are after inspect, it is included with python.
>  >
>  > > Yes, I forgot to mention - I'm new to Python. I didn't necessary mention
>  > >  3rd party library. Simply such wasn't mentioned in library review and
>  > >  tutorials, so I didn't know of it. What's the module's name?
>  >
>
> > inspect is a module, inspect is the name. It is not a module for
>  > editing Python code per se, but it will help with the other part.
>
>
> I don't think the OP wants to edit python code *objects*, rather he
>  wants to edit python *source* code programmatically.  Inspect is not
>  the tool for this.

I didn't tell him to use inspect to edit python code, I said it was
useful for the other part. The other part, as he mentioned on his
email is: "find specific
function definition, add another function call inside, find existing
call".

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


-- 
-- Guilherme H. Polo Goncalves
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Edit Python code programmatically

2008-02-09 Thread Arnaud Delobelle
On Feb 9, 12:32 pm, "Guilherme Polo" <[EMAIL PROTECTED]> wrote:
> 2008/2/9, Alex <[EMAIL PROTECTED]>:
>
> > Guilherme Polo wrote:
> >  > 2008/2/9, Alex <[EMAIL PROTECTED]>:
>
> >  >> Which library could you recommend to perform simple editing of Python
> >  >>  code (from Python program)? For example, open *.py file, find specific
> >  >>  function definition, add another function call inside, find existing
> >  >>  call and change parameter value, etc.
> >  > You are after inspect, it is included with python.
>
> > Yes, I forgot to mention - I'm new to Python. I didn't necessary mention
> >  3rd party library. Simply such wasn't mentioned in library review and
> >  tutorials, so I didn't know of it. What's the module's name?
>
> inspect is a module, inspect is the name. It is not a module for
> editing Python code per se, but it will help with the other part.

I don't think the OP wants to edit python code *objects*, rather he
wants to edit python *source* code programmatically.  Inspect is not
the tool for this.

--
Arnaud

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


[ANN] XPN 1.0.0 released

2008-02-09 Thread Nemesis
XPN (X Python Newsreader) is a multi-platform newsreader with Unicode
support. It is written with Python+GTK. It has features like
scoring/actions, X-Face and Face decoding, muting of quoted text,
newsrc import/export, find article and search in the body, spoiler
char/rot13, random taglines and configurable attribution lines.

You can find it on:

http://xpn.altervista.org/index-en.html

or

http://sf.net/projects/xpn


Changes in this release:

* v1.0.0: added multi-identity support
  This change has required some modifications to the groups db 
  format, in order to keep your subscriptions you need to export 
  to a newsrc file from XPN-0.7.0 and reimport it in XPN-1.0.0.
* v1.0.0: added nineteen new layouts
* v1.0.0: fixed a bug that made garbled the X-Faces in replies
* v1.0.0: merged a patch from Facundo Batista that lets me work on Threads 
objects.
  Its first application is the 'View Option' 'Show All Read 
Threads' that
  lets you hide/show threads with all read articles.
* v1.0.0: eventually GTK supports the long awaited set_enable_tree_lines 
property, that
  shows connecting lines between articles in the same thread
* v1.0.0: some minor fixes.

XPN is translated in Italian French and German, if you'd like to translate it
in your language and you are familiar with gettext and po-files
editing please contact me ([EMAIL PROTECTED]).

-- 
The average person thinks he isn't.

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


Re: Edit Python code programmatically

2008-02-09 Thread Steve Holden
Guilherme Polo wrote:
> 2008/2/9, Arnaud Delobelle <[EMAIL PROTECTED]>:
>> On Feb 9, 12:32 pm, "Guilherme Polo" <[EMAIL PROTECTED]> wrote:
>>  > 2008/2/9, Alex <[EMAIL PROTECTED]>:
>>  >
>>  > > Guilherme Polo wrote:
>>  > >  > 2008/2/9, Alex <[EMAIL PROTECTED]>:
>>
>>  > >  >> Which library could you recommend to perform simple editing of 
>> Python
>>  > >  >>  code (from Python program)? For example, open *.py file, find 
>> specific
>>  > >  >>  function definition, add another function call inside, find 
>> existing
>>  > >  >>  call and change parameter value, etc.
>>  > >  > You are after inspect, it is included with python.
>>  >
>>  > > Yes, I forgot to mention - I'm new to Python. I didn't necessary mention
>>  > >  3rd party library. Simply such wasn't mentioned in library review and
>>  > >  tutorials, so I didn't know of it. What's the module's name?
>>  >
>>
>>> inspect is a module, inspect is the name. It is not a module for
>>  > editing Python code per se, but it will help with the other part.
>>
>>
>> I don't think the OP wants to edit python code *objects*, rather he
>>  wants to edit python *source* code programmatically.  Inspect is not
>>  the tool for this.
> 
> I didn't tell him to use inspect to edit python code, I said it was
> useful for the other part. The other part, as he mentioned on his
> email is: "find specific
> function definition, add another function call inside, find existing
> call".
> 
Yes, the OP was a little ambiguous. So I ought to mention [sigh, these 
name] bicycle repair man

   http://bicyclerepair.sourceforge.net/

It provides refactoring functionality for Python, so may have some bits 
in it that will help (though I don't know how up to date it is).

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: are elements of a list in sequence in list b

2008-02-09 Thread bearophileHUGS
Steven D'Aprano:
> What you're trying to do is the equivalent of substring searching. There
> are simple algorithms that do this, and there are fast algorithms, but
> the simple ones aren't fast and the fast ones aren't simple.
> However, for your use case, the simple algorithm is probably fast enough:
>
> def is_sublist(b, a):
> """Return True if b is a sub-list of a, otherwise False"""
> # Get the simple cases out of the way first, for speed.
> if len(a) < len(b): return False
> elif a == b: return True
> elif not b: return False  # Or maybe True, if you prefer.
> lb = len(b)
> for i in xrange(len(a)-lb+1):
> if a[i:i+lb] == b:
> return True
> return False

I think a compromise can be found, this seem to work, and fast enough
(Psyco helps a lot of this kind of code):


def issubseq(sub, items):
"""issubseq(sub, items): return true if the sequence 'sub' is a
contiguous
subsequence of the 'items' sequence.

>>> issubseq()
Traceback (most recent call last):
  ...
TypeError: issubseq() takes exactly 2 arguments (0 given)
>>> issubseq("abc")
Traceback (most recent call last):
  ...
TypeError: issubseq() takes exactly 2 arguments (1 given)
>>> issubseq(1, [1, 2, 3])
Traceback (most recent call last):
  ...
TypeError: object of type 'int' has no len()
>>> isi = lambda s,i: int(issubseq(s,i))
>>> isi([], [])
1
>>> isi("a", "")
0
>>> isi("", "a")
1
>>> isi("", "aaa")
1
>>> isi("a", "a")
1
>>> isi("ab", "bab")
1
>>> isi("ab", "bab")
1
>>> isi("ba", "bbb")
0
>>> isi("bab", "ab")
0
>>> isi(("a", "b"), ("a","a","b"))
1
>>> isi(("a", "b"), ("a","a","c"))
0
>>> isi([1,2,1], [3,5, 1,2,4, 1,2,1, 6])
1
>>> isi([1,2,1], [3,5, 1,2,4, 1,2,3, 6])
0
>>> l = [1] * 100 + [1,2,3] + [4] * 100
>>> isi([1,2,3], l)
1
>>> l = [1] * 100 + [1,2,4] + [5] * 100
>>> isi([1,2,3], l)
0
"""
len_sub = len(sub)
len_items = len(items)
if len_sub == 0:
return True
if len_sub > len_items:
return False
if len_items == 0:
return False
if sub == items:
return True

table = [0] * (len_sub + 1)

# building prefix-function
m = 0
for i in xrange(1, len_sub):
while m > 0 and sub[m] != sub[i]:
m = table[m - 1]
if sub[m] == sub[i]:
m += 1
table[i] = m

# searching
m, i = 0, 0
for x in items:
while m > 0 and sub[m] != x:
m = table[m - 1]
if sub[m] == x:
m += 1
if m == len_sub:
return True
i += 1

return False


def _is_sublist(sub, items):
"""Return True if sub is a sub-list of items, otherwise False.

>>> _is_sublist()
Traceback (most recent call last):
  ...
TypeError: _is_sublist() takes exactly 2 arguments (0 given)
>>> _is_sublist("abc")
Traceback (most recent call last):
  ...
TypeError: _is_sublist() takes exactly 2 arguments (1 given)
>>> _is_sublist(1, [1, 2, 3])
Traceback (most recent call last):
  ...
TypeError: object of type 'int' has no len()
>>> isi = lambda s,i: int(_is_sublist(s,i))
>>> isi([], [])
1
>>> isi("a", "")
0
>>> isi("", "a")
1
>>> isi("", "aaa")
1
>>> isi("a", "a")
1
>>> isi("ab", "bab")
1
>>> isi("ab", "bab")
1
>>> isi("ba", "bbb")
0
>>> isi("bab", "ab")
0
>>> isi(("a", "b"), ("a","a","b"))
1
>>> isi(("a", "b"), ("a","a","c"))
0
>>> isi([1,2,1], [3,5, 1,2,4, 1,2,1, 6])
1
>>> isi([1,2,1], [3,5, 1,2,4, 1,2,3, 6])
0
>>> l = [1] * 100 + [1,2,3] + [4] * 100
>>> isi([1,2,3], l)
1
>>> l = [1] * 100 + [1,2,4] + [5] * 100
>>> isi([1,2,3], l)
0
"""
# By Steven D'Aprano, modified
len_sub = len(sub)
len_items = len(items)
if len_sub == 0:
return True
if len_sub > len_items:
return False
if len_items == 0:
return False
if sub == items:
return True

for i in xrange(len_items - len_sub + 1):
if items[i : i+len_sub] == sub:
return True
return False


if __name__ == "__main__":
import doctest
doctest.testmod()
print "Doctests finished.\n"


def subsequence_benchmark(with_psyco=False):
from random import randrange
from time import clock

N = 10
NBIG = 1000

small_sub = [1, 2, 3]
big_sub = [randrange(10) for _ in xrange(NBIG)]

small_present = [1] * N + small_sub + [N] * N
small_absent1 = [1] * N + small_sub[:-1] + [N] * N
small_absent2 = small_sub[:-1] * N
big_present = [1] * N + big_sub + [N] * N
big_absent = [1] * N + big_sub[:-1] + [N] * N

test_cases = [(small_sub, small_present), (small_sub,
small_absent1),
   

Re: Edit Python code programmatically

2008-02-09 Thread Alex
Guilherme Polo wrote:
> 2008/2/9, Arnaud Delobelle <[EMAIL PROTECTED]>:
>   
>> On Feb 9, 12:32 pm, "Guilherme Polo" <[EMAIL PROTECTED]> wrote:
>>  > 2008/2/9, Alex <[EMAIL PROTECTED]>:
>>  >
>>  > > Guilherme Polo wrote:
>>  > >  > 2008/2/9, Alex <[EMAIL PROTECTED]>:
>>
>> 
>>  > >  >> Which library could you recommend to perform simple editing of 
>> Python
>>  > >  >>  code (from Python program)? For example, open *.py file, find 
>> specific
>>  > >  >>  function definition, add another function call inside, find 
>> existing
>>  > >  >>  call and change parameter value, etc.
>>  > >  > You are after inspect, it is included with python.
>>  >
>>  > > Yes, I forgot to mention - I'm new to Python. I didn't necessary mention
>>  > >  3rd party library. Simply such wasn't mentioned in library review and
>>  > >  tutorials, so I didn't know of it. What's the module's name?
>>  >
>>
>> 
>>> inspect is a module, inspect is the name. It is not a module for
>>>   
>>  > editing Python code per se, but it will help with the other part.
>>
>>
>> I don't think the OP wants to edit python code *objects*, rather he
>>  wants to edit python *source* code programmatically.  Inspect is not
>>  the tool for this.
>> 
>
> I didn't tell him to use inspect to edit python code, I said it was
> useful for the other part. The other part, as he mentioned on his
> email is: "find specific
> function definition, add another function call inside, find existing
> call".
Sorry but I said "in *.py file", meaning that file isn't executed to 
edit objects in memory. It's instead saved in modified form, possibly to 
be edited by user. Guess it's a common task for visual GUI editors and 
any visual programming tools.
-- 
http://mail.python.org/mailman/listinfo/python-list


Sudden pyexpat error with ElementTree

2008-02-09 Thread Simon Pickles
Hi,

I've been using ElementTree for a few weeks without problem, with 
Stackless Python.

Suddenly I have an error importing expat, in both application and console:

[EMAIL PROTECTED]:~$ python
Python 2.5.2a0 Stackless 3.1b3 060516 (release25-maint:60694M, Feb  9 
2008, 13:21:41)
[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> from xml.parsers import expat
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/lib/python2.5/site-packages/_xmlplus/parsers/expat.py", 
line 4, in 
from pyexpat import *
ImportError: 
/usr/lib/python2.5/site-packages/_xmlplus/parsers/pyexpat.so: undefined 
symbol: PyUnicodeUCS4_Decode
 >>>

Google shows a few other sufferers, but reveals no answers. I have just 
rebuilt python to see if I had messed it up somehow, but the problem 
persists.

Thanks for your advice.

Simon



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


Re: OT: Speed of light [was Re: Why not a Python compiler?]

2008-02-09 Thread Martin P. Hellwig
Steven D'Aprano wrote:
> On Wed, 06 Feb 2008 10:14:10 -0600, Reedick, Andrew wrote:
> 
 'c' is also the speed of light.
>>> 'c' is the speed of light _in_a_vacuum_.
>> True.
>>
>>
 And since nothing can travel faster than light...
>>> Nothing can travel faster than the speed of light _in_a_vacuum_.  There
>>> are situtaitons where things can (and regularly do) travel faster than
>>> light: http://en.wikipedia.org/wiki/Cherenkov_radiation
>>
>> Nope.  It propagates, not travels, faster than light.  Go ask a
>> physicist to explain it.  It's odd...
> 
> Propagate, travel, what's the difference?
> 
Unfortunately, I didn't study any of this but I sure do remember the 
answer one drunk physic said to me in a bar when I ask him the question: 
"Does light travel or propagate?"
He answered: "Depends on how you see light."
He must have studied philosophy too :-)

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


Re: OT: Speed of light [was Re: Why not a Python compiler?]

2008-02-09 Thread Thomas Dybdahl Ahle

On Sat, 2008-02-09 at 14:56 +0100, Martin P. Hellwig wrote:
> > Propagate, travel, what's the difference?
> > 
> Unfortunately, I didn't study any of this but I sure do remember the 
> answer one drunk physic said to me in a bar when I ask him the question: 
> "Does light travel or propagate?"
> He answered: "Depends on how you see light."
> He must have studied philosophy too :-)

Quantum mechanics are closely related to philosophy.

-- 
Best Regards,
Med Venlig Hilsen,
Thomas

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


Re: Edit Python code programmatically

2008-02-09 Thread Guilherme Polo
2008/2/9, Alex <[EMAIL PROTECTED]>:
> Guilherme Polo wrote:
>  > 2008/2/9, Arnaud Delobelle <[EMAIL PROTECTED]>:
>  >
>  >> On Feb 9, 12:32 pm, "Guilherme Polo" <[EMAIL PROTECTED]> wrote:
>  >>  > 2008/2/9, Alex <[EMAIL PROTECTED]>:
>  >>  >
>  >>  > > Guilherme Polo wrote:
>  >>  > >  > 2008/2/9, Alex <[EMAIL PROTECTED]>:
>  >>
>  >>
>  >>  > >  >> Which library could you recommend to perform simple editing of 
> Python
>  >>  > >  >>  code (from Python program)? For example, open *.py file, find 
> specific
>  >>  > >  >>  function definition, add another function call inside, find 
> existing
>  >>  > >  >>  call and change parameter value, etc.
>  >>  > >  > You are after inspect, it is included with python.
>  >>  >
>  >>  > > Yes, I forgot to mention - I'm new to Python. I didn't necessary 
> mention
>  >>  > >  3rd party library. Simply such wasn't mentioned in library review 
> and
>  >>  > >  tutorials, so I didn't know of it. What's the module's name?
>  >>  >
>  >>
>  >>
>  >>> inspect is a module, inspect is the name. It is not a module for
>  >>>
>  >>  > editing Python code per se, but it will help with the other part.
>  >>
>  >>
>  >> I don't think the OP wants to edit python code *objects*, rather he
>  >>  wants to edit python *source* code programmatically.  Inspect is not
>  >>  the tool for this.
>  >>
>  >
>  > I didn't tell him to use inspect to edit python code, I said it was
>  > useful for the other part. The other part, as he mentioned on his
>  > email is: "find specific
>  > function definition, add another function call inside, find existing
>  > call".
>
> Sorry but I said "in *.py file", meaning that file isn't executed to
>  edit objects in memory. It's instead saved in modified form, possibly to
>  be edited by user. Guess it's a common task for visual GUI editors and
>  any visual programming tools.
>

By visual GUI editors I will assume GUI designer tools. These tend to
not generate  direct python code, glade-2 used to but glade-3 doesn't
anymore. Other tools like XRCed generates xrc, wxGlade has an option
to generate .xrc too, Qt Designer generates .ui and .qrc, Glade-3
generates .glade file, Gazpacho generates .glade, or a gazpacho format
or gtkbuilder format. In all these, it is recommended to use something
to work with the generated code, like libglade, wx.xrc and PyQt has
tools to convert .ui and .qrc to python modules but they don't affect
your custom code (it is also possible to load .ui using uic module).

With this we come back to my first email, where I told you it is not
recommended to generate direct python code, especially if you are
doing the kind of things you just mentioned. If you still want to
generate python code, from some other source, inspect can be helpful.

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


-- 
-- Guilherme H. Polo Goncalves
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: are elements of a list in sequence in list b

2008-02-09 Thread Steven D'Aprano
On Sat, 09 Feb 2008 05:44:27 -0800, bearophileHUGS wrote:

> def issubseq(sub, items):
> """issubseq(sub, items): return true if the sequence 'sub' is a
> contiguous subsequence of the 'items' sequence.
[snip]

A stylistic note for you...

I believe that it is considered an abuse of doctest to write a function 
with 28 lines of code and 19 tests (about two tests per three LOC). Your 
second function (adapted from mine) with 18 tests and only 14 LOC is even 
more abusive.

(At least, *I* consider it an abuse of doctest.)

As I understand it, doctests are not supposed to be used to cover trivial 
and uninteresting cases, and many of your tests were trivial and 
uninteresting. Doc tests are meant to be first and foremost 
*documentation*. For extensive, cover-every-case testing, you should be 
using unit testing.

For example, given that your docstring stated that both arguments to 
issubseq() are sequences, I question the need to have a doctest showing 
issubseq() fail when one of the arguments is not a sequence. In my 
opinion, that *doc* test is redundant (it shows nothing the reader hasn't 
already seen), and should be a unit test.


And another thing... your timing code does this:

from time import clock

Linux, Unix and Macintosh users of your code may hate you for this. As 
the timeit module explains:

... on Windows, clock() has microsecond granularity but time()'s
granularity is 1/60th of a second; on Unix, clock() has 1/100th 
of a second granularity and time() is much more precise.

If you're timing fast code, it's probably a good idea to follow Tim 
Peters' recommendation and use time() on Unix and clock() on Windows. An 
easy way to do that is by importing timeit.default_timer.



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


Re: Edit Python code programmatically

2008-02-09 Thread Guilherme Polo
2008/2/9, Alex <[EMAIL PROTECTED]>:
> Guilherme Polo wrote:
>  > 2008/2/9, Alex <[EMAIL PROTECTED]>:
>  >
>  >> Guilherme Polo wrote:
>  >>  > 2008/2/9, Arnaud Delobelle <[EMAIL PROTECTED]>:
>  >>  >
>  >>  >> On Feb 9, 12:32 pm, "Guilherme Polo" <[EMAIL PROTECTED]> wrote:
>  >>  >>  > 2008/2/9, Alex <[EMAIL PROTECTED]>:
>  >>  >>  >
>  >>  >>  > > Guilherme Polo wrote:
>  >>  >>  > >  > 2008/2/9, Alex <[EMAIL PROTECTED]>:
>  >>  >>
>  >>  >>
>  >>  >>  > >  >> Which library could you recommend to perform simple editing 
> of Python
>  >>  >>  > >  >>  code (from Python program)? For example, open *.py file, 
> find specific
>  >>  >>  > >  >>  function definition, add another function call inside, find 
> existing
>  >>  >>  > >  >>  call and change parameter value, etc.
>  >>  >>  > >  > You are after inspect, it is included with python.
>  >>  >>  >
>  >>  >>  > > Yes, I forgot to mention - I'm new to Python. I didn't necessary 
> mention
>  >>  >>  > >  3rd party library. Simply such wasn't mentioned in library 
> review and
>  >>  >>  > >  tutorials, so I didn't know of it. What's the module's name?
>  >>  >>  >
>  >>  >>
>  >>  >>
>  >>  >>> inspect is a module, inspect is the name. It is not a module for
>  >>  >>>
>  >>  >>  > editing Python code per se, but it will help with the other part.
>  >>  >>
>  >>  >>
>  >>  >> I don't think the OP wants to edit python code *objects*, rather he
>  >>  >>  wants to edit python *source* code programmatically.  Inspect is not
>  >>  >>  the tool for this.
>  >>  >>
>  >>  >
>  >>  > I didn't tell him to use inspect to edit python code, I said it was
>  >>  > useful for the other part. The other part, as he mentioned on his
>  >>  > email is: "find specific
>  >>  > function definition, add another function call inside, find existing
>  >>  > call".
>  >>
>  >> Sorry but I said "in *.py file", meaning that file isn't executed to
>  >>  edit objects in memory. It's instead saved in modified form, possibly to
>  >>  be edited by user. Guess it's a common task for visual GUI editors and
>  >>  any visual programming tools.
>  >>
>  >>
>  >
>  > By visual GUI editors I will assume GUI designer tools. These tend to
>  > not generate  direct python code, glade-2 used to but glade-3 doesn't
>  > anymore. Other tools like XRCed generates xrc, wxGlade has an option
>  > to generate .xrc too, Qt Designer generates .ui and .qrc, Glade-3
>  > generates .glade file, Gazpacho generates .glade, or a gazpacho format
>  > or gtkbuilder format. In all these, it is recommended to use something
>  > to work with the generated code, like libglade, wx.xrc and PyQt has
>  > tools to convert .ui and .qrc to python modules but they don't affect
>  > your custom code (it is also possible to load .ui using uic module).
>  >
>  > With this we come back to my first email, where I told you it is not
>  > recommended to generate direct python code, especially if you are
>  > doing the kind of things you just mentioned. If you still want to
>  > generate python code, from some other source, inspect can be helpful.
>
> Thank you for detailed reply... but I still want to generate python
>  code. By the way, Python Package Index references code generators able
>  to generate Python code
>  (http://pypi.python.org/pypi?:action=browse&show=all&c=409), which I'll
>  inspect later (especially their ability to *edit* code). Inspect might
>  be useful too.
>

Depending on what you want to generate, it may be good to generate
python code I won't try to change your mind on this. One of those code
generators there is mine, but it doesn't have an option to edit the
code neither it is in active development at all (got bored), and it
generates direct python code and other language to complement the
generated python code. But if I was going to add a possible code
editing/updating I would probably use inspect for the reasons
mentioned before.

My only intention with this email was to tell that it is pretty hard
to know what you are thinking, so it gets hard to point tools to use.
If you advance in your code generation tool, you may have a better
idea of what you want then you will get better answers too.

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


-- 
-- Guilherme H. Polo Goncalves
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Edit Python code programmatically

2008-02-09 Thread Alex
Guilherme Polo wrote:
> 2008/2/9, Alex <[EMAIL PROTECTED]>:
>   
>> Guilherme Polo wrote:
>>  > 2008/2/9, Arnaud Delobelle <[EMAIL PROTECTED]>:
>>  >
>>  >> On Feb 9, 12:32 pm, "Guilherme Polo" <[EMAIL PROTECTED]> wrote:
>>  >>  > 2008/2/9, Alex <[EMAIL PROTECTED]>:
>>  >>  >
>>  >>  > > Guilherme Polo wrote:
>>  >>  > >  > 2008/2/9, Alex <[EMAIL PROTECTED]>:
>>  >>
>>  >>
>>  >>  > >  >> Which library could you recommend to perform simple editing of 
>> Python
>>  >>  > >  >>  code (from Python program)? For example, open *.py file, find 
>> specific
>>  >>  > >  >>  function definition, add another function call inside, find 
>> existing
>>  >>  > >  >>  call and change parameter value, etc.
>>  >>  > >  > You are after inspect, it is included with python.
>>  >>  >
>>  >>  > > Yes, I forgot to mention - I'm new to Python. I didn't necessary 
>> mention
>>  >>  > >  3rd party library. Simply such wasn't mentioned in library review 
>> and
>>  >>  > >  tutorials, so I didn't know of it. What's the module's name?
>>  >>  >
>>  >>
>>  >>
>>  >>> inspect is a module, inspect is the name. It is not a module for
>>  >>>
>>  >>  > editing Python code per se, but it will help with the other part.
>>  >>
>>  >>
>>  >> I don't think the OP wants to edit python code *objects*, rather he
>>  >>  wants to edit python *source* code programmatically.  Inspect is not
>>  >>  the tool for this.
>>  >>
>>  >
>>  > I didn't tell him to use inspect to edit python code, I said it was
>>  > useful for the other part. The other part, as he mentioned on his
>>  > email is: "find specific
>>  > function definition, add another function call inside, find existing
>>  > call".
>>
>> Sorry but I said "in *.py file", meaning that file isn't executed to
>>  edit objects in memory. It's instead saved in modified form, possibly to
>>  be edited by user. Guess it's a common task for visual GUI editors and
>>  any visual programming tools.
>>
>> 
>
> By visual GUI editors I will assume GUI designer tools. These tend to
> not generate  direct python code, glade-2 used to but glade-3 doesn't
> anymore. Other tools like XRCed generates xrc, wxGlade has an option
> to generate .xrc too, Qt Designer generates .ui and .qrc, Glade-3
> generates .glade file, Gazpacho generates .glade, or a gazpacho format
> or gtkbuilder format. In all these, it is recommended to use something
> to work with the generated code, like libglade, wx.xrc and PyQt has
> tools to convert .ui and .qrc to python modules but they don't affect
> your custom code (it is also possible to load .ui using uic module).
>
> With this we come back to my first email, where I told you it is not
> recommended to generate direct python code, especially if you are
> doing the kind of things you just mentioned. If you still want to
> generate python code, from some other source, inspect can be helpful.
Thank you for detailed reply... but I still want to generate python 
code. By the way, Python Package Index references code generators able 
to generate Python code 
(http://pypi.python.org/pypi?:action=browse&show=all&c=409), which I'll 
inspect later (especially their ability to *edit* code). Inspect might 
be useful too.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sudden pyexpat error with ElementTree

2008-02-09 Thread Stefan Behnel
Simon Pickles wrote:
> ImportError:
> /usr/lib/python2.5/site-packages/_xmlplus/parsers/pyexpat.so: undefined
> symbol: PyUnicodeUCS4_Decode

You changed the build-time configuration of your Python installation, so you
should rebuild PyXML for the new interpreter (or uninstall it, as you don't
need it for ElementTree).

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


Re: OT: Speed of light [was Re: Why not a Python compiler?]

2008-02-09 Thread Grant Edwards
On 2008-02-09, Thomas Dybdahl Ahle <[EMAIL PROTECTED]> wrote:
>
> On Sat, 2008-02-09 at 14:56 +0100, Martin P. Hellwig wrote:
>> > Propagate, travel, what's the difference?
>> > 
>> Unfortunately, I didn't study any of this but I sure do remember the 
>> answer one drunk physic said to me in a bar when I ask him the question: 
>> "Does light travel or propagate?"
>> He answered: "Depends on how you see light."
>> He must have studied philosophy too :-)
>
> Quantum mechanics are closely related to philosophy.

I've never understood that claim.  You can philosophize about
anything: biology, math, weather, the stars, the moon, and so
on.  I don't see how QM is any more related to philosophy than
any other field in science.

-- 
Grant Edwards   grante Yow!  RELAX!!... This
  at   is gonna be a HEALING
   visi.comEXPERIENCE!! Besides,
   I work for DING DONGS!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: keyword 'in' not returning a bool?

2008-02-09 Thread Eyal Lotem
Arnaud Delobelle wrote:

> On Feb 8, 5:20 pm, "Reedick, Andrew" <[EMAIL PROTECTED]> wrote:
>> > -Original Message-
>> > From: [EMAIL PROTECTED] [mailto:python-
>> > [EMAIL PROTECTED] On Behalf Of c james
>> > Sent: Friday, February 08, 2008 12:10 PM
>> > To: [EMAIL PROTECTED]
>> > Subject: keyword 'in' not returning a bool?
>>
>> > Try this
>>
>> > >>> sample = {'t':True, 'f':False}
>> > >>> 't' in sample
>> > True
>> > >>> type('t' in sample)
>> > 
>> > >>> 't' in sample == True
>> > False
>>
>> > Why is this?  Now try
>> > >>> bool('t' in sample) == True
>> > True
>>
>> > Can someone explain what is going on?
>>
>> >>> ('t' in sample) == True
>>
>> True
>>
>> It's operator precedence. 'in' has lower precedence than '=='. Therefore
>> 't' in sample == True
>> evaluates as
>> 't' in (sample == True)
>>
>> The real question is why does
>> 't' in (sample == True)
>> cause an error:
>> TypeError: argument of type 'bool' is not iterable
>> while
>> 't' in sample == True
>> does not?
> 
> That should have told you precedence is not the reason!

I would guess that it is the same reason that:
1 <= (2 < 3)
is different than:
1 <= 2 < 3

Condition-chaining, I think its called, though I might be wrong.

> 
> --
> Arnaud

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

Re: Edit Python code programmatically

2008-02-09 Thread Benjamin
On Feb 9, 5:47 am, "Guilherme Polo" <[EMAIL PROTECTED]> wrote:
> 2008/2/9, Alex <[EMAIL PROTECTED]>:
>
> > Which library could you recommend to perform simple editing of Python
> >  code (from Python program)? For example, open *.py file, find specific
> >  function definition, add another function call inside, find existing
> >  call and change parameter value, etc.
>
> You are after inspect, it is included with python.
>
> >  What I'm trying to implement isn't a real visual programming tool, but
> >  some code-generation is necessary. For now I think I can generate Python
> >  syntax manually (like any text file), but it can become more complicated
> >  in future (like partially implementing code-generation library), plus
> >  there'll always be possibility of corrupting files and losing data (or
> >  having to recover valid Python syntax manually) due to coding mistake.
>
> Generating code like this is always dangerous. Maybe you could
> generate some other kind of file, then use some library or build one,
> to operator over this file.
It can be quite useful, though, say when you're writing interfaces for
several languages and you want to follow DRY.
>
> >  Thanks
>
> >  --
> >  http://mail.python.org/mailman/listinfo/python-list
>
> --
> -- Guilherme H. Polo Goncalves

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


Error on Python

2008-02-09 Thread maehhheeyy
Hi, right now I'm using Python and Multicast. I have the code for
Multicast receiver on Python but I keep getting this error;

File "", line 1, in bind
error: (10049, "Can't assign requested address")

The error is coming from this line;
sock.bind ((MCAST_ADDR, MCAST_PORT))

Can anyone please help me solve this problem?
Thanks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dependency order

2008-02-09 Thread Diez B. Roggisch
[EMAIL PROTECTED] schrieb:
> i'm having trouble trying to figure this out... it's part of a build
> system i'm writing in python.  maybe someone has a good simple way to
> solve this.  i'm trying to create a dependency order out of multiple
> lists.
> 
> list1: B C
> list2: A B
> list3: A C
> 
> i want the end result to be the list: A B C
> i'm very frustrated that i can't come up with anything that always
> works.
> 
> 
> thanks... any clues to solve this would be greatly appreciated.

Maybe the frustration is based on the IMHO wrong data-structure you use. 
What does [B, C] mean?

A common approach for this is to create a dict instead, that maps an 
object to the list of things it depends on (or that depend on it, it's 
essentially the same)

The resulting data-structure is called a directed graph, and there are 
algorithms like "partial orderings" you can google for that will help you.

An example graph would be:


dict(
"A" : ["B", "C"],
"B" : ["C"]
"C" : []
)

Then the result of a partial ordering would be

["C", "B", "A"]

which should be what you are after.

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


dependency order

2008-02-09 Thread belred
i'm having trouble trying to figure this out... it's part of a build
system i'm writing in python.  maybe someone has a good simple way to
solve this.  i'm trying to create a dependency order out of multiple
lists.

list1: B C
list2: A B
list3: A C

i want the end result to be the list: A B C
i'm very frustrated that i can't come up with anything that always
works.


thanks... any clues to solve this would be greatly appreciated.

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


Re: are elements of a list in sequence in list b

2008-02-09 Thread Paddy
On 9 Feb, 15:20, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Sat, 09 Feb 2008 05:44:27 -0800, bearophileHUGS wrote:
> > def issubseq(sub, items):
> > """issubseq(sub, items): return true if the sequence 'sub' is a
> > contiguous subsequence of the 'items' sequence.
>
> [snip]
>
> A stylistic note for you...
>
> I believe that it is considered an abuse of doctest to write a function
> with 28 lines of code and 19 tests (about two tests per three LOC). Your
> second function (adapted from mine) with 18 tests and only 14 LOC is even
> more abusive.
>
> (At least, *I* consider it an abuse of doctest.)
>

Hi Steven,
I disagree with you there. A large problem, along with poor
documentation, is no testing.
If doctest makes it much easier to test, use doctest. If you prefer
other methods then use them, but applaud Bearophile for not only
testing, but showing his tests. If it doesn't interest you then skip
it, but it at least has shown that Bearophile thought to test his
code.

The blatent and interesting bugs are usually the first thought of, and
found. It usually takes thorough analysis of the program under testing
before it is wise to remove a test and trivial, or uninteresting are
not usually reasons to remove a test wothout qualification.

Bearophile might want to use another file for his doctests, but that
would hardly help when posting to usenet.

- Paddy.


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


C function in a Python context

2008-02-09 Thread castironpi
To write quick C things that Python won't do up to speed.  So it's got
a redundancy.

import ext
extA= ext.Ext()
extA[ 'enumfactors' ]= r"""
int enumfactors( int a, const char* sep ) {
int ret= 0, i;
for( i= 1; i<= a; i++ ) {
if( a% i== 0 ) {
ret+= 1;
if( i> 1 ) {
printf( "%s", sep );
}
printf( "%i", i );
}
}
printf( "\n" );
return ret;
}
""", ("i","i","s")

factorsn= extA.enumfactors( 209677683, ', ' )
print( "%i factors total."% factorsn )

import sys
sys.exit()


1, 3, 23, 69, 131, 393, 3013, 9039, 23197, 69591, 533531, 1600593,
3038807, 9116
421, 69892561, 209677683
16 factors total.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dependency order

2008-02-09 Thread belred
On Feb 9, 11:10 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] schrieb:
>
> > i'm having trouble trying to figure this out... it's part of a build
> > system i'm writing in python.  maybe someone has a good simple way to
> > solve this.  i'm trying to create a dependency order out of multiple
> > lists.
>
> > list1: B C
> > list2: A B
> > list3: A C
>
> > i want the end result to be the list: A B C
> > i'm very frustrated that i can't come up with anything that always
> > works.
>
> > thanks... any clues to solve this would be greatly appreciated.
>
> Maybe the frustration is based on the IMHO wrong data-structure you use.
> What does [B, C] mean?
>
> A common approach for this is to create a dict instead, that maps an
> object to the list of things it depends on (or that depend on it, it's
> essentially the same)
>
> The resulting data-structure is called a directed graph, and there are
> algorithms like "partial orderings" you can google for that will help you.
>
> An example graph would be:
>
> dict(
> "A" : ["B", "C"],
> "B" : ["C"]
> "C" : []
> )
>
> Then the result of a partial ordering would be
>
> ["C", "B", "A"]
>
> which should be what you are after.
>
> Diez


i found this program in pypi, it does exactly what i was after :)

http://pypi.python.org/pypi/topsort/0.9

>>> from topsort import topsort
>>> topsort([('B', 'C'),('A', 'B'),('A', 'C')])
['A', 'B', 'C']

very cool!!! i will be able to adapt this to my program without any
problems.



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


Re: are elements of a list in sequence in list b

2008-02-09 Thread bearophileHUGS
Steven D'Aprano:
> I believe that it is considered an abuse of doctest to write a function
> with 28 lines of code and 19 tests

I agree with you. Most of my functions/methods have more compact
doctests (putting things on many lines has the advantage of letting
you locate the failing tests in a simpler way).


> In my opinion, that *doc* test is
> redundant (it shows nothing the reader hasn't
> already seen), and should be a unit test.

Doctests are simpler and faster to use for me, and they have the
advantage of keeping tests close to the tested things, instead of
scattering things in two or more places.
Generally between the choice of less tests or more doctests, I prefer
more doctests. If you have infinite time you don't need to take such
choices.


> ... on Windows, clock() has microsecond granularity but time()'s
> granularity is 1/60th of a second; on Unix, clock() has 1/100th
> of a second granularity and time() is much more precise.

I did know this... Maybe the a single function can be put there, fit
for everyone.


> An easy way to do that is by importing timeit.default_timer.

I didn't know about this, thank you. I think the timeit docs don't
show that function well enough, I can't find it in a quick search. And
that name is quite long to write, so maybe a shorter name is better
(like "timer").

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


wxpython file dialog

2008-02-09 Thread Janwillem
Is there a way to force the wx.FileDialog to show as default the 
thumbnails vie in stead of list view?
thanks, janwillem
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OT: Speed of light [was Re: Why not a Python compiler?]

2008-02-09 Thread Doug Morse
So, showing of my physics ignorance:  I presume then that this means that
light, say from the sun, is actually sending particles to the earth, since the
space between is mostly vacuum?  Or is there enough material in the
near-vacuum of space for propogation to occur?


On Sat, 09 Feb 2008 12:25:51 -0800, Dennis Lee Bieber <[EMAIL PROTECTED]>
wrote:
> ...
>   Or just the old particle/wave dichotomy... particles travel, waves
>  propagate (that is, the wave form -- crest/dip -- changes position, but
>  the material of the medium it is in just jiggles in place).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: C function in a Python context

2008-02-09 Thread castironpi
On Feb 9, 1:48 pm, [EMAIL PROTECTED] wrote:
> To write quick C things that Python won't do up to speed.  So it's got
> a redundancy.
>
> import ext
> extA= ext.Ext()
> extA[ 'enumfactors' ]= r"""
>     int enumfactors( int a, const char* sep ) {
>         int ret= 0, i;
>         for( i= 1; i<= a; i++ ) {
>             if( a% i== 0 ) {
>                 ret+= 1;
>                 if( i> 1 ) {
>                     printf( "%s", sep );
>                 }
>                 printf( "%i", i );
>             }
>         }
>         printf( "\n" );
>         return ret;
>     }
>     """, ("i","i","s")
>
> factorsn= extA.enumfactors( 209677683, ', ' )
> print( "%i factors total."% factorsn )
>
> import sys
> sys.exit()
>
> 1, 3, 23, 69, 131, 393, 3013, 9039, 23197, 69591, 533531, 1600593,
> 3038807, 9116
> 421, 69892561, 209677683
> 16 factors total.

'''Prototype implementation, slightly rigid.  If anyone knows how to
compile and link without intermediate object file, and from a string,
memory, or stdin, let me know.  Change first four lines.  If you are
not using gcc, look at regenpyd().'''

compilercommand='c:/programs/mingw/bin/gcc'
pythondll=  'python30'
pythonpathinclude=  'c:/programs/python/include'
pythonpathlibs= 'c:/programs/python/libs'

class Ext:
strctypes= { 'i': 'int', 's': 'const char*' }
class ExtElem:
def __init__( self, name, code, types ):
self.name, self.code= name, code
self.types= types
def __init__( self ):
self.__dict__[ 'exts' ]= []
def regenc( self ):
extcode= open( 'extcode.c', 'w' )
wr= extcode.write
wr( '#include <%s'% pythonpathinclude )
wr( '/Python.h>\n\n' )
for ext in self.exts:
wr( ext.code )
wr( '\n' )
for ext in self.exts:
wr( 'static PyObject *\n' )
wr( 'extcode_%s'% ext.name )
wr( '(PyObject *self, ' )
wr( 'PyObject *args) {\n' )
wr( '\t%s result;\n'%
Ext.strctypes[ext.types[0]] )
for i, type in enumerate( ext.types[1:] ):
wr( '\t%s arg%i;\n'%
( Ext.strctypes[type], i ) )
wr( '\tPyArg_ParseTuple(args, "' )
wr( ''.join( ext.types[1:] ) )
wr( '"' )
for i, type in enumerate( ext.types[1:] ):
wr( ', &arg%i'% i )
wr( ' );\n' )
wr( '\tresult= %s( '% ext.name )
wr( ', '.join( [ 'arg%i'% i for i
in range( len( ext.types[1:] ) ) ] ) )
wr( ' );\n' )
wr( '\treturn Py_BuildValue' )
wr( '( "%s", result );\n'% ext.types[0] )
wr( '}\n\n' )
wr( 'static PyMethodDef ExtcodeMethods[] = {\n' )
for ext in self.exts:
wr( '\t{ "%s", extcode_%s, '%
( ext.name, ext.name ) )
wr( 'METH_VARARGS, "" },\n' )
wr( '\t{NULL, NULL, 0, NULL}\n' )
wr( '};\n\n' )
wr( 'PyMODINIT_FUNC\n' )
wr( 'initextcode(void) {\n' )
wr( '\t(void) Py_InitModule' )
wr( '("extcode", ExtcodeMethods);\n' )
wr( '}\n\n' )
extcode.close()
def regenpyd( self ):
import os, os.path
if os.path.exists( 'extcode.pyd' ):
os.remove( 'extcode.pyd' )
import subprocess
retcompile= subprocess.call(
'%s extcode.c -c -I%s'%
( compilercommand, pythonpathinclude ) )
assert not retcompile, 'Compiler error'
retlink= subprocess.call(
'%s -shared extcode.o -o extcode.pyd -L%s -l%s'
% ( compilercommand, pythonpathlibs,
pythondll ) )
assert not retlink, 'Linker error'
os.remove( 'extcode.o' )
os.remove( 'extcode.c' )
def __setitem__( self, key, value ):
code, types= value
self.exts.append( Ext.ExtElem( key, code, types ) )
self.regenc()
self.regenpyd()
import extcode
setattr( self, key, getattr( extcode, key ) )
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OT: Speed of light [was Re: Why not a Python compiler?]

2008-02-09 Thread Jeff Schwab
Grant Edwards wrote:
> On 2008-02-09, Thomas Dybdahl Ahle <[EMAIL PROTECTED]> wrote:
>> On Sat, 2008-02-09 at 14:56 +0100, Martin P. Hellwig wrote:
 Propagate, travel, what's the difference?

>>> Unfortunately, I didn't study any of this but I sure do remember the 
>>> answer one drunk physic said to me in a bar when I ask him the question: 
>>> "Does light travel or propagate?"
>>> He answered: "Depends on how you see light."
>>> He must have studied philosophy too :-)
>> Quantum mechanics are closely related to philosophy.
> 
> I've never understood that claim.  You can philosophize about
> anything: biology, math, weather, the stars, the moon, and so
> on.  I don't see how QM is any more related to philosophy than
> any other field in science.

Any science with sufficient room for uncertainty (no pun) will 
immediately be claimed as evidence for every pseudo-theory ever imagined 
over a bowl of bad weed.  "Particles can tunnel anywhere?  Ahh, that 
must be how the telepaths are doing it."
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wxpython file dialog

2008-02-09 Thread Guilherme Polo
2008/2/9, Janwillem <[EMAIL PROTECTED]>:
> Is there a way to force the wx.FileDialog to show as default the
>  thumbnails vie in stead of list view?
>  thanks, janwillem
>
> --
>  http://mail.python.org/mailman/listinfo/python-list
>

You should be using wx.lib.imagebrowser.ImageDialog instead of
wx.FileDialog for that purpose.


-- 
-- Guilherme H. Polo Goncalves
-- 
http://mail.python.org/mailman/listinfo/python-list


different key, same value in dictionaries

2008-02-09 Thread Magdoll
Is there a cleaner way to do this example:

d = {('a','b'): 10, ('a','c'): 20, ('b','c'): 30}

The key is always a pair (x,y), but d[(x,y)] should have the same
result as d[(y,x)]. So either I would have to store both d[(x,y)] and
d[(y,x)] (unncessary extra space?), or write something like:

if x <= y: return d[(x,y)]
else:   return d[(y,x)]

I'm not familiar with python enough, so I want to know whether these
are my only choices
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sort functions in python

2008-02-09 Thread Jeff Schwab
Carl Banks wrote:
> On Feb 8, 10:09 pm, Jeff Schwab <[EMAIL PROTECTED]> wrote:
>> If you expect your data to be pretty nearly sorted
>> already, but you just want to make sure (e.g. because a small number of
>> elements may have been inserted or removed since the last sort),
>> bubble-sort is a good choice.
> 
> But if you're at that stage you probably were doing something wrong in
> the first place.

How do you figure?  You don't always have control over the 
insertions/replacements, or where they happen.  As a silly example, 
assume you have a sorted list of children, by height.  Maybe you check 
your list once per school semester.  The new sort order for any given 
semester will likely be very close to the previous order; however, a few 
  swaps may be in order, according to the different speeds at which 
children have grown.

> For a list of any decent size a few insertions using a bisection
> algorithm will take fewer comparisons than a single bubblesort pass.

Do you mean that if newly inserted data are kept separate from the 
already-sorted list, then they can be merged into the list in O(log N) time?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sort functions in python

2008-02-09 Thread Jeff Schwab
Steven D'Aprano wrote:
> On Fri, 08 Feb 2008 19:09:06 -0800, Jeff Schwab wrote:
> 
>> Steven D'Aprano wrote:
>>> On Fri, 08 Feb 2008 17:00:27 -0800, t3chn0n3rd wrote:
>>>
 Do you think it is relatively easy to write sort algorithms such as
 the common Bubble sort in Python as compared to other high level
 programming langauges
>>>
>>> You realise that bubble sort is one of the worst possible sort
>>> algorithms possible, particularly on modern hardware? It's not the
>>> worst: bogo sort and bozo sort are worse, but bubble sort is still
>>> pretty atrocious.
>> That's the conventional wisdom, mostly because CS professors need a "bad
>> algorithm" to show undergrads, but it's not really accurate.  The truth
>> is that bubble-sort's performance depends strongly on the input data. In
>> the worst case, yes, bubble-sort is O(n^2); however, for almost-sorted
>> data (only a few elements out of place), bubble-sort is actually one of
>> the fastest known algorithms.
> 
> It depends on what you mean by "bubble sort". There are many different 
> variations of bubble sort, that are sometimes described by names such as 
> comb sort, cocktail sort, exchange sort, and sometimes merely referred to 
> bubble sort. It's rather like any divide-and-conquer sorting algorithm 
> being called quicksort.
> 
> I'm as guilty of that as anyone else -- the example code I posted, raided 
> from Wikibooks is very different from this bubble sort algorithm from 
> PlanetMath:
> 
> http://planetmath.org/encyclopedia/Bubblesort.html
> 
> def bubblesort(L):
> done = False
> while not done:
> done = True
> for i in xrange(len(L)-1):
> if L[i+1] <= L[i]:
> L[i], L[i+1] = L[i+1], L[i]
> done = False
> return L
> 
> This one runs significantly faster than the earlier one I posted.
> 
> Another vital factor is, what language are you implementing the sort 
> routine in? The conventional wisdom for low-level languages like assembly 
> and C doesn't necessarily hold for high-level languages like Python. 
> Comparisons are slow in Python and fast in C; in C a good algorithm will 
> minimize the amount of moves, while in Python a good algorithm will 
> minimize the number of comparisons.
> 
> Finally, what hardware are you running on? There are interactions between 
> hardware caches and pipes that can ruin the performance of an otherwise 
> promising algorithm.
> 
> 
> But all those factors aside, I fear that your attempt to rehabilitate the 
> reputation of bubble sort is misplaced. Here's another person who wants 
> to defend bubble sort:
> 
> "A fair number of algorithm purists (which means they've probably never 
> written software for a living) claim that the bubble sort should never be 
> used for any reason. Realistically, there isn't a noticeable performance 
> difference between the various sorts for 100 items or less, and the 
> simplicity of the bubble sort makes it attractive."
> 
> http://linux.wku.edu/~lamonml/algor/sort/bubble.html
> 
> But then on the same person's page on insertion sort:
> 
> "The insertion sort is a good middle-of-the-road choice for sorting lists 
> of a few thousand items or less. The algorithm is significantly simpler 
> than the shell sort, with only a small trade-off in efficiency. At the 
> same time, the insertion sort is over twice as fast as the bubble sort 
> and almost 40% faster than the selection sort."
> 
> http://linux.wku.edu/~lamonml/algor/sort/insertion.html
> 
> He gives sample C code for both, and the bubble sort has eight lines of 
> code, versus nine for insertion sort (excluding bare braces).
> 
> Perhaps what he should have said is:
> 
> "Bubble sort is a tiny bit simpler than insertion sort, and almost twice 
> as slow!"

So basically, you and I agree that the right sorting algorithm for the 
job depends on the job.  I have no particular interest in evangelizing 
for bubble-sort; however, I hate to see an algorithm (or data structure, 
or language, or programming style) taken out of the running before the 
race even starts, just because it's out of fashion.
-- 
http://mail.python.org/mailman/listinfo/python-list


Turn off ZeroDivisionError?

2008-02-09 Thread Neal Becker
I'd like to turn off ZeroDivisionError.  I'd like 0./0. to just give NaN,
and when output, just print 'NaN'.  I notice fpconst has the required
constants.  I don't want to significantly slow floating point math, so I
don't want to just trap the exception.

If I use C code to turn off the hardware signal, will that stop python from
detecting the exception, or is python checking for 0 denominator on it's
own (hope not, that would waste cycles).

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


Re: sort functions in python

2008-02-09 Thread Hrvoje Niksic
Steven D'Aprano <[EMAIL PROTECTED]> writes:

> It depends on what you mean by "bubble sort". There are many different 
> variations of bubble sort, that are sometimes described by names such as 
> comb sort, cocktail sort, exchange sort, and sometimes merely referred to 
> bubble sort.

I've never seen anything better than bubble sort being called bubble
sort.  Comb sort is definitely regarded as a different algorithm, and
cocktail sort is no better than bubble sort anyway.

> It's rather like any divide-and-conquer sorting algorithm being
> called quicksort.

Where have you seen this?  I've never heard of non-quicksort
divide-and-conquer algorithms (such as mergesort) being referred to as
quicksort.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sort functions in python

2008-02-09 Thread Steven D'Aprano
On Sat, 09 Feb 2008 13:37:23 -0800, Jeff Schwab wrote:

> Carl Banks wrote:
>> On Feb 8, 10:09 pm, Jeff Schwab <[EMAIL PROTECTED]> wrote:
>>> If you expect your data to be pretty nearly sorted already, but you
>>> just want to make sure (e.g. because a small number of elements may
>>> have been inserted or removed since the last sort), bubble-sort is a
>>> good choice.
>> 
>> But if you're at that stage you probably were doing something wrong in
>> the first place.
> 
> How do you figure?  You don't always have control over the
> insertions/replacements, or where they happen.  As a silly example,
> assume you have a sorted list of children, by height.  Maybe you check
> your list once per school semester.  The new sort order for any given
> semester will likely be very close to the previous order; however, a few
>   swaps may be in order, according to the different speeds at which
> children have grown.

You check their heights once per semester, but you're worried about an 
extra ten or twenty microseconds to sort the data?

Frankly, if we're talking about sorting at the level of Python 
application programming, nothing you write is going to beat the speed of 
the built-in list.sort() and sorted() built-ins. Here's that bubble sort 
from yesterday again:

def bubble(A):
# http://planetmath.org/encyclopedia/Bubblesort.html
N = len(A)-1
done = False
while not done:
done = True
for i in xrange(N):
if A[i+1] <= A[i]:
A[i], A[i+1] = A[i+1], A[i]
done = False
return A


and some speed tests:

>>> L = [1, 2, 3, 4, 6, 5, 7, 9, 8]
>>> min(timeit.Timer('bubble(L)', 
... 'from __main__ import bubble, L').repeat(number=1000))
0.012052059173583984
>>> min(timeit.Timer('sorted(L)', 
... 'from __main__ import L').repeat(number=1000))
0.008681488037109
>>> min(timeit.Timer('bubble(L)', 
... 'from __main__ import bubble; L=range(5)').repeat(number=1000))
0.008541107177734375
>>> min(timeit.Timer('sorted(L)', 
... 'L=range(5)').repeat(number=1000))
0.0046191215515136719


If you're writing code in a low-level language, or a high-level language 
with no built-in sort (or a crappy one), your mileage may vary.



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


Re: different key, same value in dictionaries

2008-02-09 Thread Steven D'Aprano
On Sat, 09 Feb 2008 13:51:34 -0800, Magdoll wrote:

> Is there a cleaner way to do this example:
> 
> d = {('a','b'): 10, ('a','c'): 20, ('b','c'): 30}
> 
> The key is always a pair (x,y), but d[(x,y)] should have the same result
> as d[(y,x)]. So either I would have to store both d[(x,y)] and d[(y,x)]
> (unncessary extra space?)

Worse than the extra space is the near certainty of d[(x,y)] and d[(y,x)] 
getting out of sync.


> or write something like:
> 
> if x <= y: return d[(x,y)]
> else:   return d[(y,x)]

Arggh, scattering all those tests throughout your code is too much like 
hard work!

 
> I'm not familiar with python enough, so I want to know whether these are
> my only choices

Oh no. Here's a good one:


class PairDict(dict):
def __getitem__(self, key):
if key[1] < key[0]: key = (key[1], key[0])
return super(PairDict, self).__getitem__(key)


and here it is in use:

>>> d = PairDict([((1,2), 5), ((3,4), 10)])
>>> d[(1,2)]
5
>>> d[(2,1)]
5



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


pyinstall and matplotlib

2008-02-09 Thread John Henry
Has anybody been able to create an exe of their python applications
involving matplotlib using pyinstall (ver 1.3)?  I am getting a:

 RuntimeError: Could not find the matplotlib data files

when I attempt to run the exe created.

In searching the web, it appears this is an issue when others tried to
use py2exe as well.  Unfortunately, the few hits I saw doesn't include
enough details to inspire me as to what I should be doing in my
pyinstall .spec file.

Does anybody has an example or information about this?

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


Re: OT: Star Wars and parsecs

2008-02-09 Thread Bjoern Schliessmann
Lou Pecora wrote:
[parsecs]
> Which is the Earth's orbit.  So, long, long ago in a galaxy far,
> far away did they know about the Earth and decide to use it as the
> basis for length in the universe?  Even before people on earth
> defined it? 

No, even simpler: In the Star Wars galaxy, parsec is a time unit. We
on earth just accidentally defined a unit with exactly the same
name -- which is a distance unit instead. :)

Regards,


Björn

-- 
BOFH excuse #167:

excessive collisions & not enough packet ambulances

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


Re: Pure Python Salsa20 Stream Cipher Implementation

2008-02-09 Thread Aahz
In article <[EMAIL PROTECTED]>,
Gabriel Genellina <[EMAIL PROTECTED]> wrote:
>En Sat, 09 Feb 2008 01:34:30 -0200, <[EMAIL PROTECTED]> escribió:
>> On 8 Feb., 17:18, Paul Rubin  wrote:
>>>
>>> I don't understand why a pure python version of salsa20 would be
>>> interesting.  Is there some application that uses salsa20, that's
>>> worth being able to interoperate with in pure python?
>>
>> The reason for a pure python is that it would be independent from the
>> platform. A C implementation is faster, but you need to compile it for
>> every platform. A python implementation doesn't have that problem and
>> could be used to fall back upon.
>
>On most platforms -with a notable exception- there is a C compiler  
>available as a standard tool, which is used to compile Python itself.
>distutils can easily compile and install C extensions itself, so most of  
>the time "python setup.py install" is the only thing users have to  
>execute, exactly the same as if the package were pure Python. With  
>setuptools, things may be even easier.

What about Jython, PyPy, and IronPython?
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"All problems in computer science can be solved by another level of 
indirection."  --Butler Lampson
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: sort functions in python

2008-02-09 Thread Jeff Schwab
Steven D'Aprano wrote:
> On Sat, 09 Feb 2008 13:37:23 -0800, Jeff Schwab wrote:
> 
>> Carl Banks wrote:
>>> On Feb 8, 10:09 pm, Jeff Schwab <[EMAIL PROTECTED]> wrote:
 If you expect your data to be pretty nearly sorted already, but you
 just want to make sure (e.g. because a small number of elements may
 have been inserted or removed since the last sort), bubble-sort is a
 good choice.
>>> But if you're at that stage you probably were doing something wrong in
>>> the first place.
>> How do you figure?  You don't always have control over the
>> insertions/replacements, or where they happen.  As a silly example,
>> assume you have a sorted list of children, by height.  Maybe you check
>> your list once per school semester.  The new sort order for any given
>> semester will likely be very close to the previous order; however, a few
>>   swaps may be in order, according to the different speeds at which
>> children have grown.
> 
> You check their heights once per semester, but you're worried about an 
> extra ten or twenty microseconds to sort the data?

Are you serious?

The fact that you wouldn't use a Python script for this is what makes it 
a "silly" example in the first place.  The debate is whether Bubble Sort 
is so bad that someone should get slapped upside the head for even 
mentioning it.  I think it's a tool, like any other, and that 
occasionally it might be the right tool for the job.  Imagine that 
instead of children, we're keeping a sorted list of a very large number 
of crystals that may grow at varying speeds, and that the sizes of the 
individual crystals are polled at a rate limited by the time taken by 
the sort algorithm.

> Frankly, if we're talking about sorting at the level of Python 
> application programming, nothing you write is going to beat the speed of 
> the built-in list.sort() and sorted() built-ins.

That's probably true with five-nines probability, but there may be 
exceptions.  Do you really not understand what I'm getting at, or do you 
just disagree?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Turn off ZeroDivisionError?

2008-02-09 Thread Ryszard Szopa
On Feb 9, 11:03 pm, Neal Becker <[EMAIL PROTECTED]> wrote:
> I'd like to turn off ZeroDivisionError.  I'd like 0./0. to just give NaN,
> and when output, just print 'NaN'.  I notice fpconst has the required
> constants.  I don't want to significantly slow floating point math, so I
> don't want to just trap the exception.

What you are trying to do looks like something very, very wrong, in
the vast majority of cases. Think: normal Python code and the
interpreter itself are written under the assumption that dividing by
zero doesn't pass silently. Changing it is asking for bogus behavior.

Have you actually timed how big is the overhead of catching the
exception?

In [83]: import timeit

In [84]: x = """\
try:
1.0/rand.next()
except:
pass"""

In [85]: t = timeit.Timer(x, 'import random \nrand =
iter([random.randint(0,10) for i in xrange(100)])')

In [86]: x_nozero = "1.0/rand.next()"

In [87]: t_nozero = timeit.Timer(x_nozero, 'import random \nrand =
iter([random.randint(1,10) for i in xrange(100)])')

In [88]: t.repeat()
Out[88]: [0.91399192810058594, 0.8678128719329834,
0.86738419532775879]

In [89]: t_nozero.repeat()
Out[89]: [0.64040493965148926, 0.58412599563598633,
0.59886980056762695]

As you can see, the overhead isn't so huge.

If this overhead is too big for you, you should consider using a
different language (C? Fortran?) or at least a numeric package for
Python (NumPy?).

Anyway, turning off division by zero signaling looks like the wrong
answer to the wrong question.

HTH,

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


Re: different key, same value in dictionaries

2008-02-09 Thread Gary Herron
Magdoll wrote:
> Is there a cleaner way to do this example:
>
> d = {('a','b'): 10, ('a','c'): 20, ('b','c'): 30}
>
> The key is always a pair (x,y), but d[(x,y)] should have the same
> result as d[(y,x)]. So either I would have to store both d[(x,y)] and
> d[(y,x)] (unncessary extra space?), or write something like:
>
> if x <= y: return d[(x,y)]
> else:   return d[(y,x)]
>
> I'm not familiar with python enough, so I want to know whether these
> are my only choices
>   
You could use ImmutableSets as indexes.  (In fact this is the whole
reason for the existence of ImmutableSets.)

You could derive your own dictionary type from the builtin dictionary
type, and map an index operation d[(x,y)] to
d[ImmutableSet(a,b)].  Then all of d[a,b], d[b,a], d[(a,b)] and d[(b,a)]
would index the same element.

See http://docs.python.org/lib/module-sets.html for details of the set
module.

Gary Herron

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


Re: different key, same value in dictionaries

2008-02-09 Thread Matt Nordhoff
Gary Herron wrote:
> You could use ImmutableSets as indexes.  (In fact this is the whole
> reason for the existence of ImmutableSets.)
> 
> You could derive your own dictionary type from the builtin dictionary
> type, and map an index operation d[(x,y)] to
> d[ImmutableSet(a,b)].  Then all of d[a,b], d[b,a], d[(a,b)] and d[(b,a)]
> would index the same element.
> 
> See http://docs.python.org/lib/module-sets.html for details of the set
> module.

Since Python 2.4, sets are built-in types. Use "set" and "frozenset"
instead of "sets.Set" and "sets.ImmutableSet", respectively.

If you need Python 2.3 compatibility, you can do something like this:

try:
set, frozenset
except NameError:
from sets import Set as set, ImmutableSet as frozenset
-- 
-- 
http://mail.python.org/mailman/listinfo/python-list


What is wrong with this

2008-02-09 Thread nure123
Hi,

I am new to Python and would be grateful if anyone could tell me what
is wrong with the following statement.

Y=array([1/S, 0*lam])

where
S=[1, 2, 3, 4]
lam=[5, 6, 7, 8]

I am using Numeric not the NumPy and the original module in which this
statement appears is supposed to be working perfectly fine since an
executable based on that module is working fine ( I may be wrong if
the original author derived his executable file from a version of
module other than the one whose code is distributed)

Thanks,

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


Re: different key, same value in dictionaries

2008-02-09 Thread Paul Rubin
Matt Nordhoff <[EMAIL PROTECTED]> writes:
> Since Python 2.4, sets are built-in types. Use "set" and "frozenset"
> instead of "sets.Set" and "sets.ImmutableSet", respectively.
> 
> If you need Python 2.3 compatibility, you can do something like this:

As an alternative, you could canonicalize the keys by sorting them
into lexicographic order.  I.e. you'd store both (2,3) and (3,2) as
(2,3).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sort functions in python

2008-02-09 Thread Steven D'Aprano
On Sat, 09 Feb 2008 23:07:44 +0100, Hrvoje Niksic wrote:

> Steven D'Aprano <[EMAIL PROTECTED]> writes:
> 
>> It depends on what you mean by "bubble sort". There are many different
>> variations of bubble sort, that are sometimes described by names such
>> as comb sort, cocktail sort, exchange sort, and sometimes merely
>> referred to bubble sort.
> 
> I've never seen anything better than bubble sort being called bubble
> sort.

What, you didn't read the post you're replying to? There goes your 
credibility, right out the window and accelerating fast. The very next 
paragraph in my post said:

"I'm as guilty of that as anyone else -- the example code I posted, 
raided from Wikibooks is very different from this bubble sort algorithm 
from PlanetMath:"

So as you can see, there are at least two quite different sort 
algorithms, with very different speeds and behaviours, and both are 
called bubble sort by the people who put them on the web.

The Wikibooks version always makes the same number of passes over the 
list, regardless of it's initial order. Even if the list is sorted, it
still walks over the list O(N**2) times, doing pointless comparisons over 
and over again. It ends up doing a constant 1/2*N*(N-1) comparisons, 
regardless of the state of the list, whether it is sorted, reversed or 
something in between.

http://en.wikibooks.org/wiki/Algorithm_implementation/Sorting/Bubble_sort

The Planet Math version does not run a fixed number of times. If the list 
is already sorted, it only walks it once, doing only (N-1) comparisons. 
But if the list is far from sorted, it can end up doing N*(N-1) 
comparisons.

http://planetmath.org/encyclopedia/Bubblesort.html

If we're going to call them both bubble sort, we might as well call 
virtually any exchange sort (e.g. gnome sort, comb sort, cocktail sort, 
insertion sort, etc.) "bubble sort". And that would be stupid.

Sure, they're all *similar* algorithms, with O(N**2) behaviour, but their 
differences are significant: they differ in their best, worst and average 
behaviour and the coefficient multiplier.

> Comb sort is definitely regarded as a different algorithm, 

And so it should be.

> and cocktail sort is no better than bubble sort anyway.

Not according to Wikipedia:

http://en.wikipedia.org/wiki/Cocktail_sort


 
>> It's rather like any divide-and-conquer sorting algorithm being called
>> quicksort.
> 
> Where have you seen this?  I've never heard of non-quicksort
> divide-and-conquer algorithms (such as mergesort) being referred to as
> quicksort.


My apologies for not being more clear. What I meant was that lumping all 
exchange-sorts (a family of algorithms) as "bubble sort" (a specific 
example of the family) is as bogus as lumping all divide-and-conquer 
algorithms together as "quicksort" would be, if anyone did it.



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


Is there an easy way to sort a list by two criteria?

2008-02-09 Thread neocortex
Hello!
I am a newbie in Python. Recently, I get stuck with the problem of
sorting by two criteria. In brief, I have a two-dimensional list (for
a table or a matrix). Now, I need to sort by two columns, but I cannot
figure out how to do that. I read somewhere that it is possible to do:
>>> table.sort().sort()
but it does not work.
Can anyone help me with this?
PS: I am using Python under Ubuntu 6.06.

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


help with data extraction

2008-02-09 Thread Amitava Maity
Hello,

I have a data file (data.csv) that is something like this:

data, Conductor, ACSR
data, diameter, 0.02862
data, cross-section, 0.0004845
data, weight, 1.621
data, Mod, 70
data, Uts, 13450
data, Coef, 0.193
data, Cr, 20
data, span, 350
data, Wind pres, 0
data, temp, 32
data, ten, 3326
cond, Final wind press, 0, Final temp, 4
cond, Final wind press, 30, Final temp, 4
cond, Final wind press, 45, Final temp, 32
cond, Final wind press, 0, Final temp, 64
section, 234, 267, 289, 197

I need to to extract the third element from the rows with 'data' as
the first element, the third and fifth element from the rows with
'cond' as the first element and
all the elements following the 'section' element in the rows with
'section' as the first element.

here is the code used to extract the data:

import csv

keys = ["type", "d", "x", "c", "m", "u", "a", "tcr", "s", "wi", "ti", "Ti"]
values = []
wind   = []
temp   = []
sec= []


reader = csv.reader(open("data.csv", "rb"))

for row in reader:
if row[0] == 'data': values.append(row[2])
if row[0] == 'cond': wind.append(row[2]), temp.append(row[4])
if row[0] == 'section': sec = row[1:]


inputs = dict(zip(keys, values))
conditions = dict(zip(wind, temp))
condition = tuple(conditions.items())

print inputs, condition, sec

What I can't understand here is why the 1st row with 'cond' data and
1st element with 'section' data being skipped.

What is the fix?

thanks in advance,

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


Re: Is there an easy way to sort a list by two criteria?

2008-02-09 Thread Jeff Schwab
neocortex wrote:
> Hello!
> I am a newbie in Python. Recently, I get stuck with the problem of
> sorting by two criteria. In brief, I have a two-dimensional list (for
> a table or a matrix). Now, I need to sort by two columns, but I cannot
> figure out how to do that. I read somewhere that it is possible to do:
 table.sort().sort()
> but it does not work.
> Can anyone help me with this?
> PS: I am using Python under Ubuntu 6.06.

You can specify an arbitrary comparison function with the cmp key to 
sort.  IOW, use table.sort(cmp=f), where f is defined to compare table 
entries (rows?) by whichever criteria are required.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is wrong with this

2008-02-09 Thread Steven D'Aprano
On Sat, 09 Feb 2008 16:44:52 -0800, nure123 wrote:

> Hi,
> 
> I am new to Python and would be grateful if anyone could tell me what is
> wrong with the following statement.
> 
> Y=array([1/S, 0*lam])
> 
> where
> S=[1, 2, 3, 4]
> lam=[5, 6, 7, 8]


Oh, a guessing game! I love guessing games.

Let's see now... did you actually want to do a Fourier transform of some 
data?

If not, perhaps you could tell us what you expected to happen, and what 
actually happened, so we can stop guessing and actually help.



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


Re: Is there an easy way to sort a list by two criteria?

2008-02-09 Thread Steve Holden
neocortex wrote:
> Hello!
> I am a newbie in Python. Recently, I get stuck with the problem of
> sorting by two criteria. In brief, I have a two-dimensional list (for
> a table or a matrix). Now, I need to sort by two columns, but I cannot
> figure out how to do that. I read somewhere that it is possible to do:
 table.sort().sort()
> but it does not work.
> Can anyone help me with this?
> PS: I am using Python under Ubuntu 6.06.
> 
I think your best bet would be to google for "decorate sort undecorate" 
  or "Schwartzian transform" unless the columns happen to be in the 
right order in the rows you want to sort.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: Error on Python

2008-02-09 Thread Tim Roberts
maehhheeyy <[EMAIL PROTECTED]> wrote:

>Hi, right now I'm using Python and Multicast. I have the code for
>Multicast receiver on Python but I keep getting this error;
>
>File "", line 1, in bind
>error: (10049, "Can't assign requested address")
>
>The error is coming from this line;
>sock.bind ((MCAST_ADDR, MCAST_PORT))
>
>Can anyone please help me solve this problem?

Where did you get the multicast module?  Are you trying to do TCP
multicast?  What is the address you are trying to use?
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there an easy way to sort a list by two criteria?

2008-02-09 Thread Steven D'Aprano
On Sat, 09 Feb 2008 18:05:14 -0800, neocortex wrote:

> Hello!
> I am a newbie in Python. Recently, I get stuck with the problem of
> sorting by two criteria. In brief, I have a two-dimensional list (for a
> table or a matrix). Now, I need to sort by two columns, but I cannot
> figure out how to do that.


Can you give a (small, simple) example of your data, and what you expect 
if you sort it successfully?


> I read somewhere that it is possible to do:
> >>> table.sort().sort()
> but it does not work.

No it doesn't, because the sort() method returns None, and None doesn't 
have a sort() method of its own.

table.sort() will sort table in place, so you need something like this:

>>> table.sort()
>>> table.sort()

except naturally that just does the exact same sort twice in a row, which 
is silly. So what you actually need is something like this:

>>> table.sort(magic goes here)
>>> table.sort(different magic goes here)

where the first piece of magic tells Python to sort by the first column, 
and the second by the second column. But to do that, we need to know more 
about how you're setting up the table.

I'm *guessing* that you probably have something like this:


table = [ ['fred', 35, 8],  # name, age, score
['bill', 29, 8], 
['betty', 30, 9],
['morris', 17, 4], 
['catherine', 23, 6], 
['anna', 45, 8], 
['george', 19, 5],
['tanya', 27, 7],
]


Now let's sort it:


>>> from operator import itemgetter
>>> import pprint
>>> table.sort(key=itemgetter(0))  # sort by name
>>> table.sort(key=itemgetter(2))  # sort by score
>>> pprint.pprint(table)
[['morris', 17, 4],
 ['george', 19, 5],
 ['catherine', 23, 6],
 ['tanya', 27, 7],
 ['anna', 45, 8],
 ['bill', 29, 8],
 ['fred', 35, 8],
 ['betty', 30, 9]]



Does this help?



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


Re: help with data extraction

2008-02-09 Thread Andrew Seaford
Amitava Maity wrote:
> Hello,
> 
> I have a data file (data.csv) that is something like this:
> 
> data, Conductor, ACSR
> data, diameter, 0.02862
> data, cross-section, 0.0004845
> data, weight, 1.621
> data, Mod, 70
> data, Uts, 13450
> data, Coef, 0.193
> data, Cr, 20
> data, span, 350
> data, Wind pres, 0
> data, temp, 32
> data, ten, 3326
> cond, Final wind press, 0, Final temp, 4
> cond, Final wind press, 30, Final temp, 4
> cond, Final wind press, 45, Final temp, 32
> cond, Final wind press, 0, Final temp, 64
> section, 234, 267, 289, 197
> 
> I need to to extract the third element from the rows with 'data' as
> the first element, the third and fifth element from the rows with
> 'cond' as the first element and
> all the elements following the 'section' element in the rows with
> 'section' as the first element.
> 
> here is the code used to extract the data:
> 
> import csv
> 
> keys = ["type", "d", "x", "c", "m", "u", "a", "tcr", "s", "wi", "ti", "Ti"]
> values = []
> wind   = []
> temp   = []
> sec= []
> 
> 
> reader = csv.reader(open("data.csv", "rb"))
> 
> for row in reader:
> if row[0] == 'data': values.append(row[2])
> if row[0] == 'cond': wind.append(row[2]), temp.append(row[4])
> if row[0] == 'section': sec = row[1:]
> 
> 
> inputs = dict(zip(keys, values))
> conditions = dict(zip(wind, temp))
> condition = tuple(conditions.items())
> 
> print inputs, condition, sec
> 
> What I can't understand here is why the 1st row with 'cond' data and
> 1st element with 'section' data being skipped.
> 
> What is the fix?
> 
> thanks in advance,
> 

The code does not skip the 1st row with 'cond' and 'section'. The file 
is read correctly and the data is appended to the wind and temp lists. 
Resulting in the two lists below

wind = [0,30,45,0]
temp = [4,4,32,64]

The line conditions = dict(zip(wind, temp)) creates a dictionary using 
the wind and temp lists. In a dictionary each key is unique. The first 
key is 0 which is assigned the value 4. The second key is 30 with the 
value 4. The third key is 45 with the value 32. The key 0 is assigned a 
new value of 64. The result is that the dictionary has three key value 
pairs, not four.


Andrew Seaford
Simulation Director

Simulation eXpertise
web http://www.simx.co.uk";>www.simx.co.uk
email mailto:[EMAIL PROTECTED]">[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: shelve.open call gives error

2008-02-09 Thread Gabriel Genellina
En Sat, 09 Feb 2008 03:35:14 -0200, waltbrad <[EMAIL PROTECTED]>  
escribi�:

> On Feb 8, 5:29 pm, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:
>> En Fri, 08 Feb 2008 06:36:53 -0200, waltbrad <[EMAIL PROTECTED]>
>> escribió:
>>
>> > Working through the Mark Lutz book Programming Python 3rd Edition.
>> > A couple of modules in the "Preview" chapter give me errors. Both on a
>> > shelve.open call:
>>
>> shelve uses the anydbm module; anydbm tries to select the best database
>> module available, but apparently fails in your system.
>
> But as I gain experience I'd like to return to this issue and try to
> fix it.  Can you give me advice on how to go about that?
>
> I'm working on a win98 system.  I have python on a linux system,
> (Kubuntu) and winxp but it's more convenient right now for me to use
> the 98 laptop.

I've tried the example on WinXP and it runs fine. Looks like the bsddb  
package isn't working on Windows98; I don't know if that platform is still  
supported or not. Try submitting a bug report http://bugs.python.org

-- 
Gabriel Genellina

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

Re: Is there an easy way to sort a list by two criteria?

2008-02-09 Thread thebjorn
On Feb 10, 3:05 am, neocortex <[EMAIL PROTECTED]> wrote:
> Hello!
> I am a newbie in Python. Recently, I get stuck with the problem of
> sorting by two criteria. In brief, I have a two-dimensional list (for
> a table or a matrix). Now, I need to sort by two columns, but I cannot
> figure out how to do that. I read somewhere that it is possible to do:>>> 
> table.sort().sort()
>
> but it does not work.
> Can anyone help me with this?
> PS: I am using Python under Ubuntu 6.06.
>
> Best,
> PM

I'm not sure which Python is default for Ubuntu 6.06, but assuming you
can access a recent one (2.4), the list.sort() function takes a key
argument (that seems to be rather sparsely documented in the tutorial
and the docstring...). E.g.:

>>> lst = [(1,2,4),(3,2,1),(2,2,2),(2,1,4),(2,4,1)]
>>> lst.sort(key=lambda (a,b,c):(c,b))
>>> lst
[(3, 2, 1), (2, 4, 1), (2, 2, 2), (2, 1, 4), (1, 2, 4)]
>>>

The "fancy" lambda simply takes a source-tuple and returns a tuple of
the keys to be sorted on, in this case sort on the last element, then
on the middle element.

You can use the cmp argument to get similar results (with the same
list as above):

>>> lst.sort(cmp=lambda (a1,a2,a3),(b1,b2,b3):cmp((a3,a2),(b3,b2)))
>>> lst
[(3, 2, 1), (2, 4, 1), (2, 2, 2), (2, 1, 4), (1, 2, 4)]

The lambda in this case is starting to get complicated though, so
probably better to write a separate function. Using the cmp argument
is slower than using the key argument since key is only called once
for each element in the list while cmp is called for each comparison
of elements (it's not the number of times the function is called
that's the big deal, but rather that the highly optimized sort needs
to continually call back to Python in the cmp case).

The old-school way of doing this is using a Schwartzian transform
(a.k.a. decorate-sort-undecorate) which creates an auxilliary list
with the keys in correct sorting order so that sort() can work
directly:

>>> lst
[(1, 2, 4), (3, 2, 1), (2, 2, 2), (2, 1, 4), (2, 4, 1)]
>>> decorate = [(x[2],x[1],x) for x in lst]
>>> decorate.sort()
>>> decorate
[(1, 2, (3, 2, 1)), (1, 4, (2, 4, 1)), (2, 2, (2, 2, 2)), (4, 1, (2,
1, 4)), (4, 2, (1, 2, 4))]
>>> lst = [x[2] for x in decorate]  # undecorate
>>> lst
[(3, 2, 1), (2, 4, 1), (2, 2, 2), (2, 1, 4), (1, 2, 4)]
>>>

hth,
-- bjorn
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Recursion limit of pickle?

2008-02-09 Thread Gabriel Genellina
En Sat, 09 Feb 2008 09:49:46 -0200, Victor Lin <[EMAIL PROTECTED]>  
escribi�:

> I encounter a problem with pickle.
> I download a html from:
>
> http://www.amazon.com/Magellan-Maestro-4040-Widescreen-Navigator/dp/B000NMKHW6/ref=sr_1_2?ie=UTF8&s=electronics&qid=1202541889&sr=1-2
>
> and parse it with BeautifulSoup.
> This page is very huge.
> When I use pickle to dump it, a RuntimeError: maximum recursion depth
> exceeded occur.

BeautifulSoup objects usually aren't pickleable, independently of your  
recursion error.

py> import pickle
py> import BeautifulSoup
py> soup = BeautifulSoup.BeautifulSoup("Hello, world!")
py> print pickle.dumps(soup)
Traceback (most recent call last):
...
TypeError: 'NoneType' object is not callable
py>

Why do you want to pickle it? Store the downloaded page instead, and  
rebuild the BeautifulSoup object later when needed.

-- 
Gabriel Genellina

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

Re: What is wrong with this

2008-02-09 Thread nure123
On Feb 9, 8:56 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Sat, 09 Feb 2008 16:44:52 -0800, nure123 wrote:
> > Hi,
>
> > I am new to Python and would be grateful if anyone could tell me what is
> > wrong with the following statement.
>
> > Y=array([1/S, 0*lam])
>
> > where
> > S=[1, 2, 3, 4]
> > lam=[5, 6, 7, 8]
>
> Oh, a guessing game! I love guessing games.
>
> Let's see now... did you actually want to do a Fourier transform of some
> data?
>
> If not, perhaps you could tell us what you expected to happen, and what
> actually happened, so we can stop guessing and actually help.
>
> --
> Steven


I get an error like 'inconsistent shape in sequence.' I changed it to
Y=array([1/S, zeros(len(lam))])

it works fine. But I am still interested in knowing why did the
original programmer did not get any error whereas I got an error with
the statement : Y=array([1/S, 0*lam])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dependency order

2008-02-09 Thread Gabriel Genellina
En Sat, 09 Feb 2008 16:57:44 -0200, <[EMAIL PROTECTED]> escribi�:

> i'm having trouble trying to figure this out... it's part of a build
> system i'm writing in python.  maybe someone has a good simple way to
> solve this.  i'm trying to create a dependency order out of multiple
> lists.
>
> list1: B C
> list2: A B
> list3: A C
>
> i want the end result to be the list: A B C
> i'm very frustrated that i can't come up with anything that always
> works.

"Topological sort". There were two threads here last month.

http://groups.google.com/group/comp.lang.python/search?q=topological+sort&start=0&scoring=d

-- 
Gabriel Genellina

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

Re: sort functions in python

2008-02-09 Thread Carl Banks
On Feb 9, 4:37 pm, Jeff Schwab <[EMAIL PROTECTED]> wrote:
> Carl Banks wrote:
> > On Feb 8, 10:09 pm, Jeff Schwab <[EMAIL PROTECTED]> wrote:
> >> If you expect your data to be pretty nearly sorted
> >> already, but you just want to make sure (e.g. because a small number of
> >> elements may have been inserted or removed since the last sort),
> >> bubble-sort is a good choice.
>
> > But if you're at that stage you probably were doing something wrong in
> > the first place.
>
> How do you figure?

"Probably."

:)


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


Re: Error on Python

2008-02-09 Thread Steve Holden
Tim Roberts wrote:
> maehhheeyy <[EMAIL PROTECTED]> wrote:
> 
>> Hi, right now I'm using Python and Multicast. I have the code for
>> Multicast receiver on Python but I keep getting this error;
>>
>> File "", line 1, in bind
>> error: (10049, "Can't assign requested address")
>>
>> The error is coming from this line;
>> sock.bind ((MCAST_ADDR, MCAST_PORT))
>>
>> Can anyone please help me solve this problem?
> 
> Where did you get the multicast module?  Are you trying to do TCP
> multicast?  What is the address you are trying to use?

TCP multicast? That doesn't make sense, there can only be two endpoints 
to a TCP connection. But *you* know that.

Couldn't the port just be in use?

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: Recursion limit of pickle?

2008-02-09 Thread Victor Lin
On 2月10日, 上午11時42分, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> En Sat, 09 Feb 2008 09:49:46 -0200, Victor Lin <[EMAIL PROTECTED]>
> escribi�:
>
> > I encounter a problem with pickle.
> > I download a html from:
>
> >http://www.amazon.com/Magellan-Maestro-4040-Widescreen-Navigator/dp/B...
>
> > and parse it with BeautifulSoup.
> > This page is very huge.
> > When I use pickle to dump it, a RuntimeError: maximum recursion depth
> > exceeded occur.
>
> BeautifulSoup objects usually aren't pickleable, independently of your
> recursion error.
But I pickle and unpickle other soup objects successfully.
Only this object seems too deep to pickle.
>
> py> import pickle
> py> import BeautifulSoup
> py> soup = BeautifulSoup.BeautifulSoup("Hello, world!")
> py> print pickle.dumps(soup)
> Traceback (most recent call last):
> ...
> TypeError: 'NoneType' object is not callable
> py>
>
> Why do you want to pickle it? Store the downloaded page instead, and
> rebuild the BeautifulSoup object later when needed.
>
> --
> Gabriel Genellina

Because parsing html cost a lots of cpu time. So I want to cache soup
object as file. If I have to get same page, I can get it from cache
file, even the parsed soup file. My program's bottleneck is on parsing
html, so if I can parse once and unpickle them later, it could save a
lots of time.
-- 
http://mail.python.org/mailman/listinfo/python-list

Using Cookie and Proxy handler with urllib2

2008-02-09 Thread Joshua Gilman
Hello, here is my current code:

import urllib, urllib2, cookielib

class wrapper:
def __init__(self):
self.setupCookies()

def request(self, address, postData=None, headers={ }):
if not postData == None:
postData = urllib.urlencode(postData)
req = urllib2.Request(address, postData, headers)
return urllib2.urlopen(req).read()

def loadCookies(self, cookieFile):
self.cookieJar.load(cookieFile)

def saveCookies(self, cookieFile):
self.cookieJar.save(cookieFile)

def useProxy(self, proxy):
proxymap = {'http': proxy}
self.cookieJar = cookielib.LWPCookieJar()

director = urllib2.OpenerDirector()
director.add_handler(urllib2.ProxyHandler(proxymap))
director.add_handler(urllib2.HTTPCookieProcessor(self.cookieJar))

urllib2.install_opener(director)

def setupCookies(self):
self.cookieJar = cookielib.LWPCookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(
self.cookieJar))
urllib2.install_opener(opener)

proxyhttp = wrapper()
proxyhttp.useProxy(proxy)
postData = {'username': username, 'password': password}
content = proxyhttp.request('http://blah.com/login.php', postData)

Now, basically what this should do is send a POST request to login.php using
the given proxy and then save the returned cookies using the cookie handler.
Either I'm doing something wrong or the proxy and cookie handler don't place
nicely together. Here is the resulting error:

  File "C:\Python25\neolib\wrapper.py", line 11, in request
return urllib2.urlopen(req).read()
  File "C:\Python25\lib\urllib2.py", line 121, in urlopen
return _opener.open(url, data)
  File "C:\Python25\lib\urllib2.py", line 380, in open
response = meth(req, response)
  File "C:\Python25\lib\urllib2.py", line 1124, in http_response
self.cookiejar.extract_cookies(response, request)
  File "C:\Python25\lib\cookielib.py", line 1627, in extract_cookies
_debug("extract_cookies: %s", response.info())
AttributeError: 'NoneType' object has no attribute 'info'

I don't know much about these handlers to really understand what's going
wrong. I assume it has to be something with these two handlers conflicting
because I can't seem to find anything wrong with my code. Is this a bug or
am I doing something wrong? Help is much appreciated, thanks.

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

Re: OT: Star Wars and parsecs [was Re: Why not a Python compiler?]

2008-02-09 Thread [EMAIL PROTECTED]
On Feb 8, 2:53�pm, Lou Pecora <[EMAIL PROTECTED]> wrote:
> In article <[EMAIL PROTECTED]>,
> �Grant Edwards <[EMAIL PROTECTED]> wrote:
>
> > On 2008-02-08, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
>
> > > � � � A Parsec is a fixed value (which, admittedly, presumes the culture
> > > developed a 360degree circle broken into degrees => minutes =>
> > > seconds... or, at least, some units compatible with the concept of an
> > > "arc second", like 400 grads of, say, 100 "minutes", each of 100
> > > "seconds")
>
> > It also presumes a standard diamter of that circle.
>
> Which is the Earth's orbit. �So, long, long ago in a galaxy far, far
> away did they know about the Earth and decide to use it as the basis for
> length in the universe? �Even before people on earth defined it? �
>
> Or (ominous music builds here, switch to low voice) is it as some now
> contend? �We are the decendents of a long, lost civilization who
> colonized Earth and used it as a base for their operations to the point
> of adopting it as their own home?
>
> ... �You Betcha!
>
> :-)

How come they spoke English?

>
> --
> -- Lou Pecora

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

Re: OT: Speed of light [was Re: Why not a Python compiler?]

2008-02-09 Thread Gabriel Genellina
En Sat, 09 Feb 2008 19:01:31 -0200, Doug Morse <[EMAIL PROTECTED]> escribi�:

> So, showing of my physics ignorance:  I presume then that this means that
> light, say from the sun, is actually sending particles to the earth,  
> since the
> space between is mostly vacuum?  Or is there enough material in the
> near-vacuum of space for propogation to occur?

Before the famous Michelson-Morley experiment (end of s. XIX), some  
physicists would have said "light propagates over ether, some kind of  
matter that fills the whole space but has no measurable mass", but the  
experiment failed to show any evidence of it existence.
Then it was hard to explain light propagation as a wave (but Maxwell  
equations appeared to be so right!), and previous experiments showed that  
light was not made of particles either. Until DeBroglie formulated its  
hypothesis of dual nature of matter (and light): wave and particle at the  
same time.

-- 
Gabriel Genellina

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

Re: Pure Python Salsa20 Stream Cipher Implementation

2008-02-09 Thread Gabriel Genellina
En Sat, 09 Feb 2008 20:29:58 -0200, Aahz <[EMAIL PROTECTED]> escribió:

> In article <[EMAIL PROTECTED]>,
> Gabriel Genellina <[EMAIL PROTECTED]> wrote:
>> En Sat, 09 Feb 2008 01:34:30 -0200, <[EMAIL PROTECTED]>  
>> escribió:
>>> On 8 Feb., 17:18, Paul Rubin  wrote:

 I don't understand why a pure python version of salsa20 would be
 interesting.  Is there some application that uses salsa20, that's
 worth being able to interoperate with in pure python?
>>>
>>> The reason for a pure python is that it would be independent from the
>>> platform. A C implementation is faster, but you need to compile it for
>>> every platform. A python implementation doesn't have that problem and
>>> could be used to fall back upon.
>>
>> On most platforms -with a notable exception- there is a C compiler
>> available as a standard tool, which is used to compile Python itself.
>> distutils can easily compile and install C extensions itself, so most of
>> the time "python setup.py install" is the only thing users have to
>> execute, exactly the same as if the package were pure Python. With
>> setuptools, things may be even easier.
>
> What about Jython, PyPy, and IronPython?

What about them?
Do you mean that there should be a Python implementation for each and  
every imaginable module over there, so it can be used with all of those  
Python variants? Restricted of course to their minimum common feature set?

-- 
Gabriel Genellina

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


Re: sort functions in python

2008-02-09 Thread Steven D'Aprano
On Sat, 09 Feb 2008 14:28:15 -0800, Jeff Schwab wrote:

> Steven D'Aprano wrote:
>> On Sat, 09 Feb 2008 13:37:23 -0800, Jeff Schwab wrote:
>> 
>>> Carl Banks wrote:
 On Feb 8, 10:09 pm, Jeff Schwab <[EMAIL PROTECTED]> wrote:
> If you expect your data to be pretty nearly sorted already, but you
> just want to make sure (e.g. because a small number of elements may
> have been inserted or removed since the last sort), bubble-sort is a
> good choice.
 But if you're at that stage you probably were doing something wrong
 in the first place.
>>> How do you figure?  You don't always have control over the
>>> insertions/replacements, or where they happen.  As a silly example,
>>> assume you have a sorted list of children, by height.  Maybe you check
>>> your list once per school semester.  The new sort order for any given
>>> semester will likely be very close to the previous order; however, a
>>> few
>>>   swaps may be in order, according to the different speeds at which
>>> children have grown.
>> 
>> You check their heights once per semester, but you're worried about an
>> extra ten or twenty microseconds to sort the data?
> 
> Are you serious?
> 
> The fact that you wouldn't use a Python script for this is what makes it
> a "silly" example in the first place.


Okay, now you've broken my brain. Why on earth do you think Python isn't 
suitable for processing a list of a few hundred, or even thousand, items?


> The debate is whether Bubble Sort
> is so bad that someone should get slapped upside the head for even
> mentioning it.

Perhaps we have a different opinion about what "slapped upside the head" 
means. But if you care to point out precisely what it was that I -- or 
anyone else -- said that could be classified as abusive to the original 
poster for mentioning bubble sort, I'll be glad to apologize to him.

If not, perhaps you should chill out and stop accusing folks of bad 
behaviour that didn't happen.


> I think it's a tool, like any other, and that
> occasionally it might be the right tool for the job.

Sure its a tool. So is a stone axe, and if I were worried about the 
collapse of industrial civilization and the loss of metal-working skills, 
then I might advocate that engineering students learn how to make stone 
axes.

In the case of bubble sort, I think it's a perfectly fine algorithm to 
play around with *as a learning exercise*.


> Imagine that
> instead of children, we're keeping a sorted list of a very large number
> of crystals that may grow at varying speeds, and that the sizes of the
> individual crystals are polled at a rate limited by the time taken by
> the sort algorithm.

Bubble sort doesn't degrade gracefully. On "a very large" set of data, if 
your almost-sorted data is actually less sorted than you imagined, you 
could see your expected 10 seconds of processing time blow out to 35 
minutes.

I'd be more sympathetic to the idea of using bubble sort on tiny data 
sets, where if it goes bad, nobody is going to care that 0.01 second 
blows out to 3s. Who'd even notice?

But then, for such small amounts of data, why would you bother with 
bubble sort when insertion sort and Shell sort exist?


>> Frankly, if we're talking about sorting at the level of Python
>> application programming, nothing you write is going to beat the speed
>> of the built-in list.sort() and sorted() built-ins.
> 
> That's probably true with five-nines probability, but there may be
> exceptions.  Do you really not understand what I'm getting at, or do you
> just disagree?

It's not that bubble sort has no positives, but that they're so minor, 
and the negatives so serious, that I can't think of any situation where 
I'd recommend using bubble sort in production code -- or take somebody 
seriously if they suggested it, without a *whole* lot of actual timing 
results backing them up.


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


Re: What is wrong with this

2008-02-09 Thread Steven D'Aprano
On Sat, 09 Feb 2008 19:40:25 -0800, nure123 wrote:

> But I am still interested in knowing why did the original
> programmer did not get any error whereas I got an error with the
> statement : Y=array([1/S, 0*lam])


*shrug*

How do you know it worked fine for the original programmer? Maybe he 
released software with a bug. It happens.



-- 
Steven

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


Re: Is there an easy way to sort a list by two criteria?

2008-02-09 Thread Duncan Booth
thebjorn <[EMAIL PROTECTED]> wrote:

> I'm not sure which Python is default for Ubuntu 6.06, but assuming you
> can access a recent one (2.4), the list.sort() function takes a key
> argument (that seems to be rather sparsely documented in the tutorial
> and the docstring...). E.g.:
> 
 lst = [(1,2,4),(3,2,1),(2,2,2),(2,1,4),(2,4,1)]
 lst.sort(key=lambda (a,b,c):(c,b))
 lst
> [(3, 2, 1), (2, 4, 1), (2, 2, 2), (2, 1, 4), (1, 2, 4)]


It may be simpler just to use the key argument multiple times (not 
forgetting to specify the keys in reverse order, i.e. the most significant 
comes last). So with this example, sorting by column 2 then column 1 and 
ignoring column 0 can be done by:

>>> from operator import itemgetter
>>> lst = [(1,2,4),(3,2,1),(2,2,2),(2,1,4),(2,4,1)]
>>> lst.sort(key=itemgetter(1))
>>> lst.sort(key=itemgetter(2))
>>> lst
[(3, 2, 1), (2, 4, 1), (2, 2, 2), (2, 1, 4), (1, 2, 4)]


or even:

>>> from operator import itemgetter
>>> lst = [(1,2,4),(3,2,1),(2,2,2),(2,1,4),(2,4,1)]
>>> for keycolumn in reversed([2,1]):
lst.sort(key=itemgetter(keycolumn))


>>> lst
[(3, 2, 1), (2, 4, 1), (2, 2, 2), (2, 1, 4), (1, 2, 4)]

The important point here is to remember that the sort is stable (so you can 
do multiple sorts without disrupting earlier results).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: which one is more efficient

2008-02-09 Thread Christian Heimes
ki lo wrote:
> I have type variable which may have been set to 'D' or 'E'
> 
> Now, which one of following statements are more efficient
> 
> if type =='D' or type == 'E':
> 
> or
> 
> if re.search("D|E", type):
> 
> Please let me know because the function is going to called 10s of millions
> of times.

For maximum efficiency you have to use a set. You can speed up the check
even more if you rebind the set in the function declaration. It saves
the global lookup or the creation of the frozen set in every function call.

type_set=frozenset(('D', 'E'))

def yourfunction(self, ..., type_set=type_set):
...
if type in type_set:
...
...

Christian

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


Python Beginner needs help with for loop

2008-02-09 Thread [EMAIL PROTECTED]
Hi, I'm trying to write a for loop in place of the string
method .replace() to replace a character within a string if it's
found.

So far, I've got

s = raw_input("please enter a string: ")
c = raw_input("please enter a character: ")
b_s = s[::-1] #string backwards

found = False #character's existence within the string

for i in range(0,len(s)):
if(b_s[i] == c):
print "the last occurrence of %s is in position: " % (c),
print (len(s)-i)-1 #extract 1 for correct index
found = True
break #run just once to print the last position
if found:
s2 = s.replace(c,"!")
print "the new string with the character substituted is: " +
s2

I need to replace s2 = s.replace(c,"!") with a for loop function
somehow.

I don't really see how a for loop would iterate through the string and
replace the character, and would like to see an example if possible.


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


Re: which one is more efficient

2008-02-09 Thread Paul Rubin
> ki lo wrote:
> > I have type variable which may have been set to 'D' or 'E'
> > 
> > Now, which one of following statements are more efficient
> > 
> > if type =='D' or type == 'E':
> > 
> > or
> > 
> > if re.search("D|E", type):
> > 
> > Please let me know because the function is going to called 10s of millions
> > of times.
> 
> For maximum efficiency you have to use a set.

   if type in 'DE': ...

might be faster.  Really the only way to know is make actual
measurements.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Beginner needs help with for loop

2008-02-09 Thread Gabriel Genellina
En Sun, 10 Feb 2008 04:06:54 -0200, [EMAIL PROTECTED]  
<[EMAIL PROTECTED]> escribi�:

> I need to replace s2 = s.replace(c,"!") with a for loop function
> somehow.
>
> I don't really see how a for loop would iterate through the string and
> replace the character, and would like to see an example if possible.

Try starting with an empty string, and building the output one character  
at a time (s = s + x); when you are at the position to be replaced, use  
the replacement character instead.

-- 
Gabriel Genellina

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

Re: Python Beginner needs help with for loop

2008-02-09 Thread [EMAIL PROTECTED]
On Feb 10, 12:06 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]>
wrote:
> Hi, I'm trying to write a for loop in place of the string
> method .replace() to replace a character within a string if it's
> found.
>
> So far, I've got
>
> s = raw_input("please enter a string: ")
> c = raw_input("please enter a character: ")
> b_s = s[::-1] #string backwards
>
> found = False #character's existence within the string
>
> for i in range(0,len(s)):
> if(b_s[i] == c):
> print "the last occurrence of %s is in position: " % (c),
> print (len(s)-i)-1 #extract 1 for correct index
> found = True
> break #run just once to print the last position
> if found:
> s2 = s.replace(c,"!")
> print "the new string with the character substituted is: " +
> s2
>
> I need to replace s2 = s.replace(c,"!") with a for loop function
> somehow.
>
> I don't really see how a for loop would iterate through the string and
> replace the character, and would like to see an example if possible.


s.replace(c,"!") will replace all instances of that character. What
you need to do is just create a new string that equals the old one,
but the target character is replaced with the replacement character.

You don't have to set a flag for "found" at all. You can do it all in
that for loop. Here's an example.

FOR LOOP
  IF MATCH
CONSTRUCT NEW STRING WITH REPLACEMENT
SET NEW STRING TO OLD STRING

I can provide actual python code as well.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Beginner needs help with for loop

2008-02-09 Thread Paul Rubin
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:
> Hi, I'm trying to write a for loop in place of the string
> method .replace() to replace a character within a string if it's
> found.

I think you mean you want to replace the last occurrence of the
character in the string, but leave other occurrences intact.

> So far, I've got
> 
> s = raw_input("please enter a string: ")
> c = raw_input("please enter a character: ")

So far so good

> b_s = s[::-1] #string backwards
> found = False #character's existence within the string

I wouldn't bother with this

> for i in range(0,len(s)):

I'd use the built-in rindex function to find the last index:

   loc = s.rindex(c)

Note this will raise an exception if c isn't found.  If you don't
want that, use rfind instead of rindex.  rfind will return -1 and
then you'll have to check for that.

> print "the last occurrence of %s is in position: " % (c),
> print (len(s)-i)-1 #extract 1 for correct index

You can put both expressions in the same formatted string:

  print "the last occurrence of %s is in position %d: " % (c, loc)

> s2 = s.replace(c,"!")
> print "the new string with the character substituted is: " + s2

s2 = '%s!%s'% (s[:loc], s[loc+1:])
-- 
http://mail.python.org/mailman/listinfo/python-list


Better way to negate a boolean list?

2008-02-09 Thread David Trémouilles
Hi,

  Is there any better (shorter) way to negate a boolean list than:
 >>> negated_boolean_list = [not elem for elem in boolean_list]
?

I tried:
 >>> map(not, boolean_list)
but it seems that "not" is not a function.

Thanks in advance,

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


Re: Python Beginner needs help with for loop

2008-02-09 Thread [EMAIL PROTECTED]
I'm replacing all occurrences of the character in the string with '!',
which in turn is the new string, s2.

I'm also not allowed to use rfind or rindex or replace() because we
are supposed to be learning about for loops.

Thanks for the advices so far, I will try some more on my own.
-- 
http://mail.python.org/mailman/listinfo/python-list