Re: Does '!=' equivelent to 'is not'
Yaieee! On Wed, Jun 18, 2008 at 01:32:28AM -0400, Terry Reedy wrote: > > >Saying a flat "no" alone, without qualifying your statement is > > >generally interpreted as rude in English... > As a very much native English speaker I disagree that 'No' is > necessarily rude. I never said it was necessarily anything. Generalities generally have lots of exceptions. :D It definitely isn't *necessarily* rude, and I didn't interpret Gabriel's message as rude. I was merely pointing out that such statements are often interpreted as rude, whether or not they were intended that way. FWIW, my post wasn't intended to be a post at all, but instead a private message to Gabriel. I guess I zigged when I should have zagged... ;-) That said, what he did do, was to contradict a statement which was literally true, in an abrupt manner. Lots of people would interpret this as rude demeanor. His commentary was spot on, but the way he went about making it has a tendency to make some (perhaps many) responees defensive, if not belligerent. But, if I actually thought Gabriel was intentionally being rude, I wouldn't have bothered to say anything, and just deleted all his posts. :) I don't even think an apology was warranted... On Wed, Jun 18, 2008 at 07:01:23AM -0700, Paul McGuire wrote: > Geez, man, this is Usenet. If you want rude or condescending, the > answer would have been "No, you flatulent moron." Or maybe the > alarmist, "No! No! No!" Sure, those statements would generally be considered *blatantly* rude (but still sometimes may not be, in context). This does not mean that less blatant statements are not also rude. Geez indeed... > I see the unqualified "No." often on this list, I see it lots of places, and maybe as much as 1/3 of the time, I see it start flame wars. It seemed clear to me that Gabriel had no intention of being offensive... All I'm saying is that if you want to avoid offending some people unintentionally and needlessly, it's a good idea to avoid making curt statements, especially curt negative statements. If the intention is to signal that more is to come, a simple improvement is to add an elipsis, whose purpose is exactly that: "No..." But even more effective at avoiding the appearance of being rude are statements like "Not exactly..." "I don't think so..." etc. They're not even all that much extra typing. There are lots of times when a simple "no" is exactly what's called for. "Do you like dark Chocolate?" "No." "Are you watching the Celtics game?" "No." Or even, "Is the baby's new shirt blue?" "No, it's green." Being concise is not the same as being curt. Tone also plays a big role, but conveying the appropriate tone of a simple "no" is pretty much impossible in an e-mail. In written communication, it should be avoided like the plague. > Back in my college days, I would not be surprised for a professor to > respond "No." Sure, lots of professors are arrogant, insensitive jerks. Does that make it OK? But, depending on the context and the professor's tone, even the situation you describe isn't necessarily rude. It often isn't. The world is full of Jerks with a capital 'J'. Imagine if it weren't? How nice that would be... But, all I was offering here was a suggestion regarding how to not appear like a Jerk when one isn't intending to. > but as one of the most informed and careful posters on this list, > I'm inclined to give Gabriel a little slack. Sure. But not everyone here knows Gabriel. Not everyone here has seen his informed contributions. Not everyone here has been here more than a day... More than a few people have posted on this list complaining about the sort of responses people provide on this list, and many such complaints are quite reasonable (though sometimes the person doing the complaining is himself rather unreasonable, if not completely bonkers, I admit). I am somewhat incredulous that this required explanation... In the end what I thought would be a nice little, "hey, avoid this pot hole" kind of note seems to mostly have generated a lot of silly noise. I now retire from this discussion, and crawl back into my happy lurk-spot. :) Cheers -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D pgpCV8qGT1EYK.pgp Description: PGP signature -- http://mail.python.org/mailman/listinfo/python-list
Re: How do i : Python Threads + KeyboardInterrupt exception
I tested this a bit more. My windows example was incorrect. It should have used CTRL_C_EVENT. But even then, the problem is that the process will also close the console window from which it was called because of the 0. Also this requires that the process actually have a console and is not a GUI application. Is there some other method rather than a blocking "for line in fin:" that i can use for reading from a file like device that plays nicely with other threads asynchronously waking it up? Sorry for all the posts. I am giving updates as i look further into the problem. -- http://mail.python.org/mailman/listinfo/python-list
Re: Regular expressions for accents like ó character in python
En Thu, 19 Jun 2008 02:08:38 -0300, Sallu <[EMAIL PROTECTED]> escribió: i want to restrict to user to not enter accents character. si i need to make an Regular expressions for accents like ó character You may enumerate all the allowed characters: py> allowed_re = re.compile(r"^[A-Za-z0-9 ]*$") py> input = "hello world" py> allowed_re.match(input) <_sre.SRE_Match object at 0x00A3C1E0> py> input = "código inválido" py> allowed_re.match(input) py> print allowed_re.match(input) None -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Doc tests in Python
Hello. Im new to using doctests in python. Could some1 tel me how to use doctests if i have a constructor in my code? -- http://mail.python.org/mailman/listinfo/python-list
good
I like your programming choice becaz python is safe than c or c++ or any other compiled languages as it protects against buffer overflow which causes potentail security problems i am wanted to know how many requests can it handle is it configurable for that. Raashid Bhatt (C) -- http://mail.python.org/mailman/listinfo/python-list
Mr nazim
nazim why you want to use an IDE for gui development as we got a tk wrapper for python use Tkinter import it in python its easy -- http://mail.python.org/mailman/listinfo/python-list
Re: RELEASED Python 2.6b1 and 3.0b1
Barry Warsaw wrote: -BEGIN PGP SIGNED MESSAGE- Hash: SHA1 On behalf of the Python development team and the Python community, I am happy to announce the first beta releases of Python 2.6 and Python 3.0. As usual, this is the source code release. A Windows installer built from that code should follow soon. Martin has usually done so within a day or two. So be patient along with me ;-). For more information and downloadable distributions, see the Python 2.6 website: http://www.python.org/download/releases/2.6/ and the Python 3.0 web site: http://www.python.org/download/releases/3.0/ -- http://mail.python.org/mailman/listinfo/python-list
Regular expressions for accents like ó character in python
i want to restrict to user to not enter accents character. si i need to make an Regular expressions for accents like ó character -- http://mail.python.org/mailman/listinfo/python-list
Why doesnt PDB allow me to view the current line?
I have some code that I am trying to debug (Python 2.5.2 on OSX) using pdb. However, when the code reaches the pdb.set_trace(), it does not allow me to view the current line: > /Users/chris/Research/ISEC/build/bdist.macosx-10.3-i386/egg/pyrl/reinforcement.py(943)__call__() (Pdb) n > /Users/chris/Research/ISEC/build/bdist.macosx-10.3-i386/egg/pyrl/reinforcement.py(946)__call__() (Pdb) l [EOF] (Pdb) l [EOF] It steps through the code fine, but for some reason returns end-of- file when I want to look at the code. -- http://mail.python.org/mailman/listinfo/python-list
Re: How do i : Python Threads + KeyboardInterrupt exception
> I don't know the "standard" way, but perhaps you can get some ideas from > this recent > thread:http://groups.google.com/group/comp.lang.python/browse_thread/thread/... > I had a quick read through that thread. I think i will need some more time to think about what they are saying in there though. They seem to talking about killing a python thread kind of similar to the C functions TerminateThread() in windows or pthread_cancel() on UNIX which are not suitable for my purpose. > You might try using the PyThreadState_SetAsyncExc function (from the > Python C API) to inject a KeyboardInterrupt exception into the Read thread > - but I don't know if it will work at all, the execution might be blocked > waiting for an I/O call to complete, and never return to Python code... > Unfortunately that is the problem. It is blocking in a IO system call and i want to force it to exit that with an error, hopefully causing a Python exception. I looked at what you mentioned and it is described a bit here too: http://sebulba.wikispaces.com/recipe+thread2 I really need a python mechanism for interrupting blocking system calls. have dealt with this sort of thing before in C/C++ on windows and UNIX. For UNIX it is really a matter of sending a signal to the process (SIGINTR), the main thread which is the only one in Python to accept signals (others as i understand are masked) will get the signal and and return with an EINTR breaking out of the blocking read hopefully a python exception of Interrupted IO or KeyboardInterrupt. Note that this only works for the one thread , but that is all i need. For windows, it is possible to do a similar thing using: GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, 0) with which behaves a bit like a UNIX signal and i assume is what causes the KeyboardInterrupt in the first place. The problem i have is how do I achieve this in python? -- http://mail.python.org/mailman/listinfo/python-list
Re: ��python in a nutshell��and��programming python��
"yps" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > as a new learner of python,which book in and > is more suitable? I don't have "Python in a Nutshell," but let me ask... do you have a strong programming background in C++, Java, etc.? If so, you'll probably find "Programming Python" a little too basic. > and recommend several books? For those with prior programming experience, I'd recomment "Python: Essential Reference." "Python Pocket Reference" is worth having regardless of your background. A similar document is the freely download quick reference here: http://rgruet.free.fr/#QuickRef ---Joel -- http://mail.python.org/mailman/listinfo/python-list
Re: python/ruby question..
On Jun 18, 10:33�pm, "bruce" <[EMAIL PROTECTED]> wrote: > hi... > > can someone point me to where/how i would go about calling a ruby app from a > python app, and having the python app being able to get a returned value > from the ruby script. > > something like > > test.py > �a = os.exec(testruby.rb) > > testruby.py > �foo = 9 > �return foo > > i know this doesn't work... but i've been searching for hours on this with > no luck (and yeah, i'm relatively new to both ruby/python!!) > > thanks Well, I don't know anything about Ruby, but here's how I do it for C programs (compiled to .exe that write to stdout). import os factor_program = 'factor! -d200 ' # factor!.exe from MIRACL n = '50818429800343305993022114330311033271249313957919046352679206262204589342623811236647989889145173098650749' # call external program and capture stdout the_output = os.popen(factor_program+n).readlines() print 'n: %s' % n for i in the_output: print i, ##n: 50818429800343305993022114330311033271249313957919046352679206262204589342623811236647989889145173098650749 ##PRIME_FACTOR 37 ##PRIME_FACTOR 43 ##PRIME_FACTOR 167 ##COMPOSITE_FACTOR 507787751 ##PRIME_FACTOR 69847 ##PRIME_FACTOR 30697 ##PRIME_FACTOR 89017 ##PRIME_FACTOR 3478697 ##PRIME_FACTOR 434593 ##PRIME_FACTOR 49998841 ##PRIME_FACTOR 161610704597143 ##PRIME_FACTOR 14064370273 ##COMPOSITE_FACTOR 963039394703598565337297 ##PRIME_FACTOR 11927295803 -- http://mail.python.org/mailman/listinfo/python-list
Re: Ternary operator alternative in Ptyhon
Thank you everyone. I ended up implementing the dict.get() method, which seems "cleaner", but I'll keep the (x if y else z) syntax in mind. I didn't know it existed, I guess it's what I was looking for to begin with. Thanks again! Allen wrote: kretik wrote: I'm sure this is a popular one, but after Googling for a while I couldn't figure out how to pull this off. -- http://mail.python.org/mailman/listinfo/python-list
Re: ¡¶python in a nutshell¡·and¡¶programming p ython¡·
Learning Python may be another good choice. But really, for just starting out, nothing beats online documentation. http://docs.python.org/tut/tut.html http://diveintopython.org/ On Jun 18, 9:02Â pm, "yps" <[EMAIL PROTECTED]> wrote: > as a new learner of python,which book in and > is more suitable? > and recommend several books? > thanks > best regards > > Â Â Â Â Â Â Â Â Â Â pase.Y -- http://mail.python.org/mailman/listinfo/python-list
python/ruby question..
hi... can someone point me to where/how i would go about calling a ruby app from a python app, and having the python app being able to get a returned value from the ruby script. something like test.py a = os.exec(testruby.rb) testruby.py foo = 9 return foo i know this doesn't work... but i've been searching for hours on this with no luck (and yeah, i'm relatively new to both ruby/python!!) thanks -- http://mail.python.org/mailman/listinfo/python-list
RELEASED Python 2.6b1 and 3.0b1
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 On behalf of the Python development team and the Python community, I am happy to announce the first beta releases of Python 2.6 and Python 3.0. Please note that these are beta releases, and as such are not suitable for production environments. We continue to strive for a high degree of quality, and these releases are intended to freeze the feature set for Python 2.6 and 3.0. From now until the planned final releases in September 2008, we will be fixing known problems and stabilizing these new Python versions. You can help by downloading and testing them, providing feedback and hopefully helping to fix bugs. You can also use these releases to determine how changes in 2.6 and 3.0 might impact you. If you find things broken or incorrect, please submit bug reports at http://bugs.python.org For more information and downloadable distributions, see the Python 2.6 website: http://www.python.org/download/releases/2.6/ and the Python 3.0 web site: http://www.python.org/download/releases/3.0/ See PEP 361 for release schedule details: http://www.python.org/dev/peps/pep-0361/ Enjoy, - -Barry Barry Warsaw [EMAIL PROTECTED] Python 2.6/3.0 Release Manager (on behalf of the entire python-dev team) -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.9 (Darwin) iQCVAwUBSFnIbnEjvBPtnXfVAQKCMgP+L9Vpk9vQgYw01KShtF9HyvCKE0guSy86 0Q/IRbkXGahXg910D4nVLY9NORaOSq/VP8Kx+fOU8egUDHvVF9MuKkY75ZHYoixR mieeV7BIpYHYKYhva48FVoF4p0+sUeNvfeOAP0nnV5Pi2icGqCpzizfSHZloXJjc Y8M4F5vVrOM= =Oo15 -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
��python in a nutshell��and��programming python��
as a new learner of python,which book in and is more suitable? and recommend several books? thanks best regards pase.Y -- http://mail.python.org/mailman/listinfo/python-list
Re: How do i : Python Threads + KeyboardInterrupt exception
En Wed, 18 Jun 2008 21:39:41 -0300, Brendon Costa <[EMAIL PROTECTED]> escribió: I have a small python project i am working on. Basically i always have two threads. A "Read" thread that sits in a loop reading a line at a time from some input (Usually stdin) and then generating events to be processed and a "Proc" thread that processes incoming events from a queue. There will be additional threads as well that asynchronously insert events into the queue to be processed, but they are not a part of this so i have omitted them. What i want to know is: "What is the standard/best way of implementing such a pattern that works in the presence of errors and particularly with the KeyboardInterrupt exception?" I don't know the "standard" way, but perhaps you can get some ideas from this recent thread: http://groups.google.com/group/comp.lang.python/browse_thread/thread/82636f1bdd1d2d83/ Some sample code is shown below. This code works as is, except in the case where the "Proc" thread wants to initiate the exit of the application. You might try using the PyThreadState_SetAsyncExc function (from the Python C API) to inject a KeyboardInterrupt exception into the Read thread - but I don't know if it will work at all, the execution might be blocked waiting for an I/O call to complete, and never return to Python code... -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 372 -- Adding an ordered directory to collections
On Jun 18, 3:15 pm, [EMAIL PROTECTED] wrote: > In Python 2.5 a dict(int:None) needs about 36.2 bytes/element. I am > suggesting to add 2 pointers, to create a linked list, so it probably > becomes (on 32 bit systems) about 44.2 bytes/pair. PyDictEntry is typedef struct { Py_ssize_t me_hash; PyObject *me_key; PyObject *me_value; } PyDictEntry; Which should be 12 bytes on a 32-bit machine. I thought the space for growth factor for dicts was about 12% but it is really 100%. In any case, a pair of lists will take up less space than a dict and a list. Or the storage could be an array of PyDictEntrys (to cache the hash values of the keys), an approach that is in some sense halfway between the others. There is one advantage of this last approach - I think the amount of hacking on dictobject.c that would have to take place is minimal. In fact it almost seems like you could get the desired result by setting mp->ma_lookup to a new function (and keep most of the rest of the methods as they are). This seems too easy though, so there might be a catch. David -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for lots of words in lots of files
On Jun 18, 11:01 pm, Kris Kennaway <[EMAIL PROTECTED]> wrote: > Calvin Spealman wrote: > > Upload, wait, and google them. > > > Seriously tho, aside from using a real indexer, I would build a set of > > thewordsI'mlookingfor, and then loop over each file, looping over > > thewordsand doing quick checks for containment in the set. If so, add > > to a dict of file names to list ofwordsfound until the list hits 10 > > length. I don't think that would be a complicated solution and it > > shouldn't be terrible at performance. > > > If you need to run this more than once, use an indexer. > > > If you only need to use it once, use an indexer, so you learn how for > > next time. > > If you can't use an indexer, and performance matters, evaluate using > grep and a shell script. Seriously. > > grep is a couple of orders of magnitude faster at pattern matching > strings infiles(and especially regexps) than python is. Even if you > are invoking grep multiple times it is still likely to be faster than a > "maximally efficient" single pass over the file in python. This > realization was disappointing to me :) > > Kris Alternatively, if you don't feel like writing shell scripts, you can write a Python program which auto-generate the desired shell script which utilizes grep. E.g. use Python for generating the file list which is passed to grep as arguments. ;-P -- http://mail.python.org/mailman/listinfo/python-list
Python email server
I am starting to build a Python email server. Before assembling the individual pieces I am wondering if there is a prebuilt package anyone would recommend? Thanks in advance for your advice and guidance. John S. -- http://mail.python.org/mailman/listinfo/python-list
How do i : Python Threads + KeyboardInterrupt exception
Hi all, I have a small python project i am working on. Basically i always have two threads. A "Read" thread that sits in a loop reading a line at a time from some input (Usually stdin) and then generating events to be processed and a "Proc" thread that processes incoming events from a queue. There will be additional threads as well that asynchronously insert events into the queue to be processed, but they are not a part of this so i have omitted them. What i want to know is: "What is the standard/best way of implementing such a pattern that works in the presence of errors and particularly with the KeyboardInterrupt exception?" Some sample code is shown below. This code works as is, except in the case where the "Proc" thread wants to initiate the exit of the application. For example: * running the code below and pressing Ctrl + C works fine as the Read thread is initiating the shutdown. * running the code below and entering: pquit some other data will cause oytput: Processing: pquit Proc: Initiating quit and then it HANGS waiting for the Read thread to exit. Some questions i have that are: * KeyboardInterrupt exception seems to only be recieved by the main thread. Is this ALWAYS the case across all UNIX + windows platforms (not so worried about others)? * Can i somehow get the Proc thread to force the Read thread to generate a KeyboardInterrupt or somehow exit its blocking "for line in fin:" call? Thanks, Brendon --- SNIP --- # Two or more threads # # proc : Is a processing thread that basically reads events from a event queue and processes them # read : Is a thread reading in a loop from stdin and generating events for "proc" # * : Other additional threads that may asynchronously add events to the queue to be processed import Queue import threading import sys def Read(queue, fin, fout): ret = (1, 'Normal Exit') try: for line in fin: queue.put((0, line)) #raise Exception("Blah") #raise "Blah" except KeyboardInterrupt: ret = (1, 'KeyboardInterrupt') except Exception, e: ret = (1, 'ERROR: ' + str(e)) except:ret = (1, 'UNKNOWN-ERROR') # Notify Proc thread that we are exiting. queue.put(ret) print >>fout, 'Read: Initiating quit' def Proc(queue, fout, ignore): quit = False while not quit: (evt_type, evt_data) = queue.get() if evt_type == 0: print >>fout, 'Processing: ' + str(evt_data) if evt_data.startswith('pquit'): print >>fout, 'Proc: Initiating quit' quit = True elif evt_type == 1: print >>fout, 'Quit: ' + str(evt_data) quit = True class MyThread(threading.Thread): def __init__(self, func, queue, file1, file2, *args, **kwds): threading.Thread.__init__(self, *args, **kwds) self.func = func self.queue = queue self.file1 = file1 self.file2 = file2 self.start() def run(self): return self.func(self.queue, self.file1, self.file2) if __name__ == '__main__': queue = Queue.Queue() # Read thread is the main thread and seems to get the KeyboardInterrupt exception. t = MyThread(Proc, queue, sys.stderr, None) Read(queue, sys.stdin, sys.stderr) # Read thread is NOT the main thread and never seems to get the KeyboardInterrupt exception. # This doesnt work for that reason. #t = MyThread(Read, queue, sys.stdin, sys.stderr) #Proc(queue, sys.stderr, None) # @@@Brendon How do we notify the Read thread that they should exit? # If the Read thread initiated the quit then all is fine. # If the Proc thread initiated the quit then i need to get the Read # thread to exit too somehow. But it is currently blocking in a read # on an input file. print >>sys.stderr, 'Joining thread.' t.join() -- http://mail.python.org/mailman/listinfo/python-list
Personal project announcement
Hi, Just wanted to announce a little project I've just uploaded. It's a web server written in Python. You can get it at http://code.google.com/p/sws-d/ . Any suggestions or comments are welcome! Regards, Sebastian -- http://mail.python.org/mailman/listinfo/python-list
Re: advanced listcomprehenions?
On Jun 18, 4:42 pm, cirfu <[EMAIL PROTECTED]> wrote: > I am wondering if it is possible to write advanced listcomprehensions. > > For example: > """Write a program that prints the numbers from 1 to 100. But for > multiples of three print "Fizz" instead of the number and for the > multiples of five print "Buzz". For numbers which are multiples of > both three and five print "FizzBuzz".""" > Obv it doesnt have to be a list according tot hat definition but > suppose i want to generate that list. > > >>> [["Fizzbuzz",x] for x in xrange(1,101) if x%3 == 0 and x%5 == 0] > > [['Fizzbuzz', 15], ['Fizzbuzz', 30], ['Fizzbuzz', 45], ['Fizzbuzz', > 60], ['Fizzbuzz', 75], ['Fizzbuzz', 90]] > > is not what i want. the following does the trick but is ldo not a > listcomprehension: > > for i in xrange(1,101): > s = "" > if i%3 == 0: > s += "Fizz" > if i%5 == 0: > s += "Buzz" > if s: > print "%d : %s" % (i,s) > else: > print i > > or to generate a lisrt but not by listcomprehsnion: > map(lambda x: (not x%3 and not x%5 and "FizzBuzz") or (not x%3 and > "Fizz") > or (not x%5 and "Buzz") or x, xrange(1,101)) [(('Fizz' if num % 3 == 0 else '') + ('Buzz' if num % 5 == 0 else '')) or str(num) for num in xrange(1, 101)] -- http://mail.python.org/mailman/listinfo/python-list
Re: Ultimate Prime Sieve -- Sieve Of Zakiya (SoZ)
On Jun 13, 1:12 pm, jzakiya <[EMAIL PROTECTED]> wrote: > The paper presents benchmarks with Ruby 1.9.0-1 (YARV). I would love > to see my various prime generators benchmarked with optimized > implementations in other languages. I'm hoping Python gurus will do > better than I, though the methodology is very very simple, since all I > do is additions, multiplications, and array reads/writes. After playing a little with it, I managed to get a 32-47% improvement on average for the pure Python version, and a 230-650% improvement with an extra "import psyco; psyco.full()" (pasted at http://codepad.org/C2nQ8syr) The changes are: - Replaced range() with xrange() - Replaced x**2 with x*x - Replaced (a,b) = (c,d) with a=c; b=d - Replaced generator expressions with list comprehensions. This was the big one for letting psyco do its magic. I also tried adding type declarations and running it through Cython but the improvement was much less impressive than Psyco. I'm not a Pyrex/Cython expert though so I may have missed something obvious. George -- http://mail.python.org/mailman/listinfo/python-list
Re: advanced listcomprehenions?
On Jun 18, 10:42 pm, cirfu <[EMAIL PROTECTED]> wrote: > I am wondering if it is possible to write advanced listcomprehensions. > > For example: > """Write a program that prints the numbers from 1 to 100. But for > multiples of three print "Fizz" instead of the number and for the > multiples of five print "Buzz". For numbers which are multiples of > both three and five print "FizzBuzz".""" > Obv it doesnt have to be a list according tot hat definition but > suppose i want to generate that list. > > >>> [["Fizzbuzz",x] for x in xrange(1,101) if x%3 == 0 and x%5 == 0] > > [['Fizzbuzz', 15], ['Fizzbuzz', 30], ['Fizzbuzz', 45], ['Fizzbuzz', > 60], ['Fizzbuzz', 75], ['Fizzbuzz', 90]] > > is not what i want. the following does the trick but is ldo not a > listcomprehension: > > for i in xrange(1,101): > s = "" > if i%3 == 0: > s += "Fizz" > if i%5 == 0: > s += "Buzz" > if s: > print "%d : %s" % (i,s) > else: > print i > > or to generate a lisrt but not by listcomprehsnion: > map(lambda x: (not x%3 and not x%5 and "FizzBuzz") or (not x%3 and > "Fizz") > or (not x%5 and "Buzz") or x, xrange(1,101)) [("FizzBuzz" if n % 15 == 0 else "Fizz" if n % 3 == 0 else "Buzz" if n % 5 == 0 else str(n)) for n in range(1, 101)] -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 372 -- Adding an ordered directory to collections
On Jun 16, 1:37 am, Armin Ronacher <[EMAIL PROTECTED]> wrote: > Abstract > > > This PEP proposes an ordered dictionary as a new data structure for > the ``collections`` module, called "odict" in this PEP for short. The > proposed API incorporates the experiences gained from working with > similar implementations that exist in various real-world applications > and other programming languages. > > Rationale > = > > In current Python versions, the widely used built-in dict type does > not specify an order for the key/value pairs stored. This makes it > hard to use dictionaries as data storage for some specific use cases. > > Some dynamic programming languages like PHP and Ruby 1.9 guarantee a > certain order on iteration. In those languages, and existing Python > ordered-dict implementations, the ordering of items is defined by the > time of insertion of the key. New keys are appended at the end, keys > that are overwritten and not moved. > > The following example shows the behavior for simple assignments: > > >>> d = odict() > >>> d['parrot'] = 'dead' > >>> d['penguin'] = 'exploded' > >>> d.items() > > [('parrot', 'dead'), ('penguin', 'exploded')] > > That the ordering is preserved makes an odict useful for a couple of > situations: > > - XML/HTML processing libraries currently drop the ordering of > attributes, use a list instead of a dict which makes filtering > cumbersome, or implement their own ordered dictionary. This affects > ElementTree, html5lib, Genshi and many more libraries. > > - There are many ordererd dict implementations in various libraries > and applications, most of them subtly incompatible with each other. > Furthermore, subclassing dict is a non-trivial task and many > implementations don't override all the methods properly which can > lead to unexpected results. > > Additionally, many ordered dicts are implemented in an inefficient > way, making many operations more complex then they have to be. > > - PEP 3115 allows metaclasses to change the mapping object used for > the class body. An ordered dict could be used to create ordered > member declarations similar to C structs. This could be useful, for > example, for future ``ctypes`` releases as well as ORMs that define > database tables as classes, like the one the Django framework ships. > Django currently uses an ugly hack to restore the ordering of > members in database models. > > - Code ported from other programming languages such as PHP often > depends on a ordered dict. Having an implementation of an > ordering-preserving dictionary in the standard library could ease > the transition and improve the compatibility of different libraries. > > Ordered Dict API > > > The ordered dict API would be mostly compatible with dict and existing > ordered dicts. (Note: this PEP refers to the Python 2.x dictionary > API; the transfer to the 3.x API is trivial.) > > The constructor and ``update()`` both accept iterables of tuples as > well as mappings like a dict does. The ordering however is preserved > for the first case: > > >>> d = odict([('a', 'b'), ('c', 'd')]) > >>> d.update({'foo': 'bar'}) > >>> d > > collections.odict([('a', 'b'), ('c', 'd'), ('foo', 'bar')]) > > If ordered dicts are updated from regular dicts, the ordering of new > keys is of course undefined again unless ``sort()`` is called. > > All iteration methods as well as ``keys()``, ``values()`` and > ``items()`` return the values ordered by the the time the key-value > pair was inserted: > > >>> d['spam'] = 'eggs' > >>> d.keys() > > ['a', 'c', 'foo', 'spam']>>> d.values() > > ['b', 'd', 'bar', 'eggs']>>> d.items() > > [('a', 'b'), ('c', 'd'), ('foo', 'bar'), ('spam', 'eggs')] > > New methods not available on dict: > > ``odict.byindex(index)`` > > Index-based lookup is supported by ``byindex()`` which returns > the key/value pair for an index, that is, the "position" of a > key in the ordered dict. 0 is the first key/value pair, -1 > the last. > > >>> d.byindex(2) > ('foo', 'bar') > > ``odict.sort(cmp=None, key=None, reverse=False)`` > > Sorts the odict in place by cmp or key. This works exactly > like ``list.sort()``, but the comparison functions are passed > a key/value tuple, not only the value. > > >>> d = odict([(42, 1), (1, 4), (23, 7)]) > >>> d.sort() > >>> d > collections.odict([(1, 4), (23, 7), (42, 1)]) > > ``odict.reverse()`` > > Reverses the odict in place. > > ``odict.__reverse__()`` > > Supports reverse iteration by key. > > Questions and Answers > = > > What happens if an existing key is reassigned? > > The key is not moved but assigned a new value in place. This is > consistent with existing implementations and allows subclasses to > change the behavior easily:: > > class movingcollections.odict): >
Re: Does '!=' equivelent to 'is not'
On Jun 18, 9:43 pm, Lie <[EMAIL PROTECTED]> wrote: > On Jun 19, 2:51 am, Paul McGuire <[EMAIL PROTECTED]> wrote: > > > On Jun 18, 2:22 pm, Lie <[EMAIL PROTECTED]> wrote: > > > > I'm not a native English speaker, although I think my parents would > > > have liked me to be more straightforward when talking, cause I tend to > > > say things like "possibly", "maybe", "probably", and other ambiguous > > > expressions to the extent that it has frustrated them now and then. > > > Well, at least you *talk* to your parents! Mostly what I get from my > > kids is, "can I borrow 10 dollars?" > > lol, I rarely initiate the talk to my parents unless I have to, they > usually starts talking first which I usually responded with the > ambiguous statements. Well, in fact, I rarely initiate a talk with > anybody, it's my nature to keep myself in the shade until I have to be > in the light. > "'Tis better to remain silent and be thought a fool, than open one's mouth and remove all doubt." - Samuel Johnson. :-) > But I never asked for money up straight like that though. -- http://mail.python.org/mailman/listinfo/python-list
Re: python string comparison oddity
Faheem Mitha wrote: On Wed, 18 Jun 2008 12:57:44 -0700 (PDT), Lie <[EMAIL PROTECTED]> wrote: On Jun 19, 2:26 am, Faheem Mitha <[EMAIL PROTECTED]> wrote: Hi everybody, I was wondering if anyone can explain this. My understanding is that 'is' checks if the object is the same. However, in that case, why this inconsistency for short strings? I would expect a 'False' for all three comparisons. This is reproducible across two different machines, so it is not just a local quirk. I'm running Debian etch with Python 2.4.4 (the default). Thanks, Faheem. In [1]: a = '--' In [2]: a is '--' Out[2]: False In [4]: a = '-' In [5]: a is '-' Out[5]: True In [6]: a = 'foo' In [7]: a is 'foo' Out[7]: True Yes, this happens because of small objects caching. When small integers or short strings are created, there are possibility that they might refer to the same objects behind-the-scene. Don't rely on this behavior. Yes, but why is '-' and 'foo' cached, and not '--'? Do you know what the basis of the choice is? Shortish Python identifiers and operators, I think. Plus a handful like '\x00'. The source would know for sure, but alas, I am lazy. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: advanced listcomprehenions?
En Wed, 18 Jun 2008 18:42:00 -0300, cirfu <[EMAIL PROTECTED]> escribió: I am wondering if it is possible to write advanced listcomprehensions. For example: """Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".""" Obv it doesnt have to be a list according tot hat definition but suppose i want to generate that list. Go to http://groups.google.com/group/comp.lang.python and search for "fizz buzz"... or to generate a lisrt but not by listcomprehsnion: map(lambda x: (not x%3 and not x%5 and "FizzBuzz") or (not x%3 and "Fizz") or (not x%5 and "Buzz") or x, xrange(1,101)) You can translate that into a list comprehension - in general, map(f, items) is the same as [f(x) for x in items]. We have then: [(not x%3 and not x%5 and "FizzBuzz") or (not x%3 and "Fizz") or (not x%5 and "Buzz") or x for x in xrange(1,101)] Quite unreadable IMHO. Just to add another variant to the zillion ones already posted: def fb(x): mult3 = x%3 == 0 mult5 = x%5 == 0 if mult3 and mult5: return "FizzBuzz" elif mult3: return "Fizz" elif mult5: return "Buzz" return str(x) [fb(x) for x in range(1,101)] -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 372 -- Adding an ordered directory to collections
dbpoko...: > Why keep the normal dict operations at the same speed? There is a > substantial cost this entails. I presume now we can create a list of possible odict usages, because I think that despite everyone using it for different purposes, we may find some main groups of its usage. I use odicts is situations where an dict is nearly the right data structure, so keeping all operations close to the time complexity of dicts has a purpose. > but the storage requirements are reduced to 2n from 4n. In Python 2.5 a dict(int:None) needs about 36.2 bytes/element. I am suggesting to add 2 pointers, to create a linked list, so it probably becomes (on 32 bit systems) about 44.2 bytes/pair. Note that computer science is full of strange data structures, so maybe a skip list can be used here, to increase some operation timings, and reduce other ones... :-) Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: python string comparison oddity
On Wed, 18 Jun 2008 12:57:44 -0700 (PDT), Lie <[EMAIL PROTECTED]> wrote: > On Jun 19, 2:26 am, Faheem Mitha <[EMAIL PROTECTED]> wrote: >> Hi everybody, >> >> I was wondering if anyone can explain this. My understanding is that 'is' >> checks if the object is the same. However, in that case, why this >> inconsistency for short strings? I would expect a 'False' for all three >> comparisons. This is reproducible across two different machines, so it is >> not just a local quirk. I'm running Debian etch with Python 2.4.4 (the >> default). >> Thanks, Faheem. >> >> In [1]: a = '--' >> >> In [2]: a is '--' >> Out[2]: False >> >> In [4]: a = '-' >> >> In [5]: a is '-' >> Out[5]: True >> >> In [6]: a = 'foo' >> >> In [7]: a is 'foo' >> Out[7]: True > > Yes, this happens because of small objects caching. When small > integers or short strings are created, there are possibility that they > might refer to the same objects behind-the-scene. Don't rely on this > behavior. Yes, but why is '-' and 'foo' cached, and not '--'? Do you know what the basis of the choice is? Faheem. -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting Python exit code when calling Python script from Java program
En Wed, 18 Jun 2008 08:09:58 -0300, A.T.Hofkamp <[EMAIL PROTECTED]> escribió: On 2008-06-18, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: picking up 0. On investigation it turned out that the exit value being read is from python.exe process, not from the Python script. Is there any way I can obtain the return value of a python script from a Java This is not what I see happening here: x.py: import sys sys.exit(138) % python2.4 x.py % echo $? 138 as you can see, the mechanism works at my Linux system. It works fine on Windows too, the OS she appears to be using: C:\TEMP>python x.py C:\TEMP>echo %ERRORLEVEL% 138 -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 372 -- Adding an ordered directory to collections
Wow, I was completely wrong about sorted dicts and odicts. On Jun 17, 4:21 am, [EMAIL PROTECTED] wrote: > mean. I think for this data structure it's important to keep all the > normal dict operations at the same speed. If you use a C Why keep the normal dict operations at the same speed? There is a substantial cost this entails. It seems that some odict solutions take up 4n words per entry in the limit (ignoring the fixed percentage growth space for lists and dicts). This is n words for _keys and 3n words for the underlying dict. What about storing the key:value pairs as a pair of lists (maybe interleaved)? Key lookup then becomes an O(n) operation, but the storage requirements are reduced to 2n from 4n. Here is a hypothetical (somewhat contrived) example: odicts are used to store the attributes of XML elements in a medium-sized XML document (say 250K). If the required munging does some surgery on elements 3-4 layers deep in a few places, then the number of key lookups may be relatively small. (Assuming that very few odicts will have more than 30 entries, each individual lookup will be fairly quick as well). The document has to be loaded into memory anyway, so the extra cost of key lookups is more than compensated for by the substantial reduction in the number of cache line misses. The main concern is that doubling the size of the data structure in order to turn key lookup into an O(1) operation may give worse performance in the common case (this is a personal impression from reading the use case list in the rationale), and a data structure like this seems to be way off by itself in the time-space complexity landscape. In this case the odict no longer inherits from the dict. Cheers, David -- http://mail.python.org/mailman/listinfo/python-list
advanced listcomprehenions?
I am wondering if it is possible to write advanced listcomprehensions. For example: """Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".""" Obv it doesnt have to be a list according tot hat definition but suppose i want to generate that list. >>> [["Fizzbuzz",x] for x in xrange(1,101) if x%3 == 0 and x%5 == 0] [['Fizzbuzz', 15], ['Fizzbuzz', 30], ['Fizzbuzz', 45], ['Fizzbuzz', 60], ['Fizzbuzz', 75], ['Fizzbuzz', 90]] is not what i want. the following does the trick but is ldo not a listcomprehension: for i in xrange(1,101): s = "" if i%3 == 0: s += "Fizz" if i%5 == 0: s += "Buzz" if s: print "%d : %s" % (i,s) else: print i or to generate a lisrt but not by listcomprehsnion: map(lambda x: (not x%3 and not x%5 and "FizzBuzz") or (not x%3 and "Fizz") or (not x%5 and "Buzz") or x, xrange(1,101)) -- http://mail.python.org/mailman/listinfo/python-list
Re: extra positional arguments before optional parameters syntax
On Jun 18, 5:25 pm, MisterWilliam <[EMAIL PROTECTED]> wrote: > I noticed that in PEP 3105, the PEP about turning print to print(), > the syntax for print() is defined as follows: > def print(*args, sep=' ', end='\n', file=None) > > Ignoring the fact that print is a reserved keyword in python, this is > not valid python because extra positional arguments (*args), cannot > come before optional parameters (sep=' ', end='\n', file=None). > > >>> def f(*args, sep=' ', end='\n', file=None): > > File "", line 1 > def f(*args, sep=' ', end='\n', file=None): >^ > SyntaxError: invalid syntax > > Am I misunderstanding something? Is this type of syntax suppose to be > allowed in a future version of Python? (I can't find anything about > this through my searching.) You didn't search hard enough; it's three PEPs earlier: http://www.python.org/dev/peps/pep-3102/ George -- http://mail.python.org/mailman/listinfo/python-list
Re: Does '!=' equivelent to 'is not' [drifting a little more]
En Wed, 18 Jun 2008 14:26:31 -0300, Ethan Furman <[EMAIL PROTECTED]> escribió: Gabriel Genellina wrote: (This thread is getting way above 1cp...) What is 1cp? cp = centipoise, a unit of dynamic viscosity, measuring the resistence to flow. Honey viscosity is a few hundreds, corn syrup a few thousands, and something above 1 cp is really viscous... -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Function argument conformity check
On Jun 18, 5:05 pm, George Sakkis <[EMAIL PROTECTED]> wrote: > On Jun 18, 3:41 pm, [EMAIL PROTECTED] wrote: > > > > > On Jun 18, 3:13 pm, Cédric Lucantis <[EMAIL PROTECTED]> wrote: > > > > Hi, > > > > Le Wednesday 18 June 2008 20:19:12 [EMAIL PROTECTED], vous avez écrit : > > > > > Hi. I am looking for a way to check if some given set of (*args, > > > > **kwds) conforms to the argument specification of a given function, > > > > without calling that function. > > > > > For example, given the function foo: > > > > def foo(a, b, c): pass > > > > > and some tuple args and some dict kwds, is there a way to tell if i > > > > _could_ call foo(*args, **kwds) without getting an exception for those > > > > arguments? I am hoping there is a way to do this without actually > > > > writing out the argument logic python uses. > > > > Each function object is associated to a code object which you can get with > > > foo.func_code. Two of this object's attributes will help you: co_argcount > > > and > > > co_varnames. The first is the number of arguments of the function, and the > > > second a list of all the local variables names, including the arguments > > > (which are always the first items of the list). When some arguments have > > > default values, they are stored in foo.func_defaults (and these arguments > > > are > > > always after non-default args in the co_argnames list). > > > > Finally, it seems that some flags are set in code.co_flags if the function > > > accepts varargs like *args, **kwargs, but I don't know where these are > > > defined. > > > > Note that I never found any doc about that and merely guessed it by > > > playing > > > with func objects, so consider all this possibly wrong or subject to > > > change. > > > > -- > > > Cédric Lucantis > > > I am aware of these attributes, although you can get them all in a > > more organized form using the getfullargspec function in the inspect > > module from the standard library. > > > The problem is that using these attributes, I would essentially have > > to re-write the logic python uses when calling a function with a given > > set of arguments. I was hoping there is a way to get at that logic > > without rewriting it. > > Sure; copy it from someone that has already done it ;-) > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/551779 > > HTH, > George This is exactly what I was looking for- thanks! -- http://mail.python.org/mailman/listinfo/python-list
extra positional arguments before optional parameters syntax
I noticed that in PEP 3105, the PEP about turning print to print(), the syntax for print() is defined as follows: def print(*args, sep=' ', end='\n', file=None) Ignoring the fact that print is a reserved keyword in python, this is not valid python because extra positional arguments (*args), cannot come before optional parameters (sep=' ', end='\n', file=None). >>> def f(*args, sep=' ', end='\n', file=None): File "", line 1 def f(*args, sep=' ', end='\n', file=None): ^ SyntaxError: invalid syntax Am I misunderstanding something? Is this type of syntax suppose to be allowed in a future version of Python? (I can't find anything about this through my searching.) This kind of syntax seems useful, especially one wants to overwrite the new function print(). Thanks, William Chang -- http://mail.python.org/mailman/listinfo/python-list
Re: NumPy chararray and whitespace
OKB (not okblacke) wrote: Hi. I'm trying to use NumPy's chararray class for an array of characters. I notice that when I try to set a chararray element to a space, it actually gets set to an empty string. I found some pages online indicating that the chararray strips trailing whitespace from its values. You should ask numpy questions on the numpy mailing list. http://www.scipy.org/Mailing_Lists I am really, really, hoping this is not a hard-coded, unalterable behavior. Is there a way to get NumPy chararray to include the characters I tell it to, without modificiation? Sure. Just subclass chararray and redefine __getitem__ to do what you want. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: Function argument conformity check
On Jun 18, 3:41 pm, [EMAIL PROTECTED] wrote: > On Jun 18, 3:13 pm, Cédric Lucantis <[EMAIL PROTECTED]> wrote: > > > > > Hi, > > > Le Wednesday 18 June 2008 20:19:12 [EMAIL PROTECTED], vous avez écrit : > > > > Hi. I am looking for a way to check if some given set of (*args, > > > **kwds) conforms to the argument specification of a given function, > > > without calling that function. > > > > For example, given the function foo: > > > def foo(a, b, c): pass > > > > and some tuple args and some dict kwds, is there a way to tell if i > > > _could_ call foo(*args, **kwds) without getting an exception for those > > > arguments? I am hoping there is a way to do this without actually > > > writing out the argument logic python uses. > > > Each function object is associated to a code object which you can get with > > foo.func_code. Two of this object's attributes will help you: co_argcount > > and > > co_varnames. The first is the number of arguments of the function, and the > > second a list of all the local variables names, including the arguments > > (which are always the first items of the list). When some arguments have > > default values, they are stored in foo.func_defaults (and these arguments > > are > > always after non-default args in the co_argnames list). > > > Finally, it seems that some flags are set in code.co_flags if the function > > accepts varargs like *args, **kwargs, but I don't know where these are > > defined. > > > Note that I never found any doc about that and merely guessed it by playing > > with func objects, so consider all this possibly wrong or subject to change. > > > -- > > Cédric Lucantis > > I am aware of these attributes, although you can get them all in a > more organized form using the getfullargspec function in the inspect > module from the standard library. > > The problem is that using these attributes, I would essentially have > to re-write the logic python uses when calling a function with a given > set of arguments. I was hoping there is a way to get at that logic > without rewriting it. Sure; copy it from someone that has already done it ;-) http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/551779 HTH, George -- http://mail.python.org/mailman/listinfo/python-list
NumPy chararray and whitespace
Hi. I'm trying to use NumPy's chararray class for an array of characters. I notice that when I try to set a chararray element to a space, it actually gets set to an empty string. I found some pages online indicating that the chararray strips trailing whitespace from its values. I am really, really, hoping this is not a hard-coded, unalterable behavior. Is there a way to get NumPy chararray to include the characters I tell it to, without modificiation? Thanks, -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown -- http://mail.python.org/mailman/listinfo/python-list
Re: Who is using python-ldap with Python 1.5.x and 2.0-2.2?
Michael Ströder wrote: > Please tell me > which Python version you're using We do have one venerable machine here at work using python2.2 with python-ldap2.0.0pre04. As you can see, we haven't bothered to update either in quite a while ;-) > and why it'd be important for you to > have python-ldap updates still supporting it. For us, it is not important. Should we want or need to update python-ldap on that one machine, we'll update python along with it (and vice versa.) Thank you, Jeffrey -- http://mail.python.org/mailman/listinfo/python-list
Re: How to split a string containing nested commas-separated substrings
On Jun 18, 10:54 am, Matimus <[EMAIL PROTECTED]> wrote: > On Jun 18, 10:19 am, Robert Dodier <[EMAIL PROTECTED]> wrote: > > > > > Hello, > > > I'd like to split a string by commas, but only at the "top level" so > > to speak. An element can be a comma-less substring, or a > > quoted string, or a substring which looks like a function call. > > If some element contains commas, I don't want to split it. > > > Examples: > > > 'foo, bar, baz' => 'foo' 'bar' 'baz' > > 'foo, "bar, baz", blurf' => 'foo' 'bar, baz' 'blurf' > > 'foo, bar(baz, blurf), mumble' => 'foo' 'bar(baz, blurf)' 'mumble' > > > Can someone suggest a suitable regular expression or other > > method to split such strings? > > > Thank you very much for your help. > > > Robert > > You might look at the shlex module. It doesn't get you 100%, but its > close: > > >>> shlex.split('foo, bar, baz') > > ['foo,', 'bar,', 'baz']>>> shlex.split( 'foo, "bar, baz", blurf') > > ['foo,', 'bar, baz,', 'blurf']>>> shlex.split('foo, bar(baz, blurf), mumble') > > ['foo,', 'bar(baz,', 'blurf),', 'mumble'] > > Using a RE will be tricky, especially if it is possible to have > recursive nesting (which by definition REs can't handle). For a real > general purpose solution you will need to create a custom parser. > There are a couple modules out there that can help you with that. > > pyparsing is one:http://pyparsing.wikispaces.com/ > > Matt Following up to my own post, Here is a working example that uses the built-in _ast module. I posted something similar the other day. This uses pythons own internal parser to do it for you. It works in this case because, at least from what you have posted, your syntax doesn't violate python syntax. [code] import _ast def eval_tuple(text): """ Evaluate a string representing a tuple of strings, names and calls, returns a tuple of strings. """ ast = compile(text, "", 'eval', _ast.PyCF_ONLY_AST) return _traverse(ast.body) def _traverse(ast): """ Traverse the AST returning string representations of tuples strings names and calls. """ if isinstance(ast, _ast.Tuple): return tuple(_traverse(el) for el in ast.elts) elif isinstance(ast, _ast.Str): return ast.s elif isinstance(ast, _ast.Name): return ast.id elif isinstance(ast, _ast.Call): name = ast.func.id args = [_traverse(x) for x in ast.args] return "%s(%s)"%(name, ", ".join(args)) raise SyntaxError() examples = [ ('foo, bar, baz', ('foo', 'bar', 'baz')), ('foo, "bar, baz", blurf', ('foo', 'bar, baz', 'blurf')), ('foo, bar(baz, blurf), mumble', ('foo', 'bar(baz, blurf)', 'mumble')), ] def test(): for text, expected in examples: print "trying %r => %r"%(text, expected) result = eval_tuple(text) if result == expected: print "PASS" else: print "FAIL, GOT: %r"%result if __name__ == "__main__": test() [/code] Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: Ternary operator alternative in Ptyhon
jeremie fouche wrote: > You can also use : > self.SomeField = params.has_key("mykey") and params["mykey"] or None Have caution with this solution: it may not provide the desired result in the case where params["mykey"] is a false value, such as 0, or [] Jeffrey -- http://mail.python.org/mailman/listinfo/python-list
Re: Does '!=' equivelent to 'is not'
On Jun 19, 2:51 am, Paul McGuire <[EMAIL PROTECTED]> wrote: > On Jun 18, 2:22 pm, Lie <[EMAIL PROTECTED]> wrote: > > > > > I'm not a native English speaker, although I think my parents would > > have liked me to be more straightforward when talking, cause I tend to > > say things like "possibly", "maybe", "probably", and other ambiguous > > expressions to the extent that it has frustrated them now and then. > > Well, at least you *talk* to your parents! Mostly what I get from my > kids is, "can I borrow 10 dollars?" lol, I rarely initiate the talk to my parents unless I have to, they usually starts talking first which I usually responded with the ambiguous statements. Well, in fact, I rarely initiate a talk with anybody, it's my nature to keep myself in the shade until I have to be in the light. But I never asked for money up straight like that though. -- http://mail.python.org/mailman/listinfo/python-list
Re: Function argument conformity check
In article <[EMAIL PROTECTED]>, > The problem is that using these attributes, I would essentially have > to re-write the logic python uses when calling a function with a > given set of arguments. I was hoping there is a way to get at that > logic without rewriting it. I don't think there is. I ended up rewriting it when I wanted to do a similar thing. -M- -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 372 -- Adding an ordered directory to collections
> What's the purpose of having list.insert? It's a convenience function: you don't have to write a loop to move all items to a later index. Any reformulation of it is easy to get wrong, and difficult to read. > One creates tons of unnecessary method calls, the other creates a full > blown list object just to throw it away later. Both less than optimal > solutions that can be implemented in a more efficient way on the C > layer where one only has to iterate over the linked list offset times > and return the item. And iteration for that linked list is most likely > something like "for (n = 0; n != offset; ++n) iter = iter->next". Ok, so it is about performance, and intended to provide a speedup by a constant factor (over the trivial reformulation without it). What are the use cases for this function? I.e. in what specific applications did you use it, or would you want to use it? In these applications, could you instead also have used a (hypothetical) function def nth(iter, n): while n: iter.next() n-=1 return iter.next() instead? Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Numeric type conversions
John Dann <[EMAIL PROTECTED]> writes: > I suppose there must be some logic in including the start position > but excluding the end position, though it does escape me for now. I > can understand making a range inclusive or exclusive but not a > mixture of the two. Suppose it's just something you have to get used > to with Python and, no doubt, much commented on in the past. Half-open ranges are not specific to Python: for example, they're used in Java (String.substring), Lisp (start and stop arguments to sequence functions), and C++ (STL algorithms accept begin and end iterators that generalize from pointers to the beginning and one-past-the-end of an array). Ranges so expressed have several nice properties. The size of the range is expressed simply as b-a, you don't need to remember to add 1. Empty range is easily expressed as [a, a>, rather than the much less intuitive [a, a-1] for all-inclusive ranges. Consecutive ranges are easily concatenated without missing or duplicating an element, so [a, b> + [b, c> is exactly equivalent to [a, c>. -- http://mail.python.org/mailman/listinfo/python-list
Re: python string comparison oddity
On Jun 19, 2:26 am, Faheem Mitha <[EMAIL PROTECTED]> wrote: > Hi everybody, > > I was wondering if anyone can explain this. My understanding is that 'is' > checks if the object is the same. However, in that case, why this > inconsistency for short strings? I would expect a 'False' for all three > comparisons. This is reproducible across two different machines, so it is > not just a local quirk. I'm running Debian etch with Python 2.4.4 (the > default). > Thanks, Faheem. > > In [1]: a = '--' > > In [2]: a is '--' > Out[2]: False > > In [4]: a = '-' > > In [5]: a is '-' > Out[5]: True > > In [6]: a = 'foo' > > In [7]: a is 'foo' > Out[7]: True Yes, this happens because of small objects caching. When small integers or short strings are created, there are possibility that they might refer to the same objects behind-the-scene. Don't rely on this behavior. -- http://mail.python.org/mailman/listinfo/python-list
Re: Does '!=' equivelent to 'is not'
On Jun 18, 2:22 pm, Lie <[EMAIL PROTECTED]> wrote: > > I'm not a native English speaker, although I think my parents would > have liked me to be more straightforward when talking, cause I tend to > say things like "possibly", "maybe", "probably", and other ambiguous > expressions to the extent that it has frustrated them now and then. Well, at least you *talk* to your parents! Mostly what I get from my kids is, "can I borrow 10 dollars?" -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Function argument conformity check
On Jun 18, 3:13 pm, Cédric Lucantis <[EMAIL PROTECTED]> wrote: > Hi, > > Le Wednesday 18 June 2008 20:19:12 [EMAIL PROTECTED], vous avez écrit : > > > Hi. I am looking for a way to check if some given set of (*args, > > **kwds) conforms to the argument specification of a given function, > > without calling that function. > > > For example, given the function foo: > > def foo(a, b, c): pass > > > and some tuple args and some dict kwds, is there a way to tell if i > > _could_ call foo(*args, **kwds) without getting an exception for those > > arguments? I am hoping there is a way to do this without actually > > writing out the argument logic python uses. > > Each function object is associated to a code object which you can get with > foo.func_code. Two of this object's attributes will help you: co_argcount and > co_varnames. The first is the number of arguments of the function, and the > second a list of all the local variables names, including the arguments > (which are always the first items of the list). When some arguments have > default values, they are stored in foo.func_defaults (and these arguments are > always after non-default args in the co_argnames list). > > Finally, it seems that some flags are set in code.co_flags if the function > accepts varargs like *args, **kwargs, but I don't know where these are > defined. > > Note that I never found any doc about that and merely guessed it by playing > with func objects, so consider all this possibly wrong or subject to change. > > -- > Cédric Lucantis I am aware of these attributes, although you can get them all in a more organized form using the getfullargspec function in the inspect module from the standard library. The problem is that using these attributes, I would essentially have to re-write the logic python uses when calling a function with a given set of arguments. I was hoping there is a way to get at that logic without rewriting it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Calling pcre with ctypes
moreati schrieb: > Recently I discovered the re module doesn't support POSIX character > classes: > > Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42) > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. import re r = re.compile('[:alnum:]+') print r.match('123') > None > > So I thought I'd try out pcre through ctypes, to recreate pcredemo.c > in python. The c code is at: > http://vcs.pcre.org/viewvc/code/trunk/pcredemo.c?view=markup > > Partial Python code is below > > I'm stuck, from what I can tell a c array, such as: > int ovector[OVECCOUNT]; > > translates to > ovector = ctypes.c_int * OVECOUNT > > but when I pass ovector to a function I get the traceback > $ python pcredemo.py [a-z] fred > Traceback (most recent call last): > File "pcredemo.py", line 65, in > compiled_re, None, subject, len(subject), 0, 0, ovector, OVECOUNT > ctypes.ArgumentError: argument 7: : Don't > know how to convert parameter 7 > > What is the correct way to construct and pass ovector? 'ctypes.c_int * OVECOUNT' does not create an array *instance*, it creates an array *type*, comparable to a typedef in C. You can create an array instance by calling the type, with zero or more initializers: ovector = (ctypes.c_int * OVECOUNT)(0, 1, 2, 3, ...) Thomas -- http://mail.python.org/mailman/listinfo/python-list
python string comparison oddity
Hi everybody, I was wondering if anyone can explain this. My understanding is that 'is' checks if the object is the same. However, in that case, why this inconsistency for short strings? I would expect a 'False' for all three comparisons. This is reproducible across two different machines, so it is not just a local quirk. I'm running Debian etch with Python 2.4.4 (the default). Thanks, Faheem. In [1]: a = '--' In [2]: a is '--' Out[2]: False In [4]: a = '-' In [5]: a is '-' Out[5]: True In [6]: a = 'foo' In [7]: a is 'foo' Out[7]: True -- http://mail.python.org/mailman/listinfo/python-list
Re: Does '!=' equivelent to 'is not'
On Jun 18, 12:32 pm, Terry Reedy <[EMAIL PROTECTED]> wrote: > >> Saying a flat "no" alone, without qualifying your statement is > >> generally interpreted as rude in English... It's kind of like how you > >> talk to children when they're too young to understand the explanation. > >> Yucky. > > > I didn't meant to be rude at all - and I apologize to Mr. Lie. The > > explanation for such strong "No" was in the paragraph below it (the idea > > was to say: "No to this, yes to that") > > As a very much native English speaker I disagree that 'No' is > necessarily rude. I wish I could more often get such a clean answer to > my questions from my child. I'm not a native English speaker, although I think my parents would have liked me to be more straightforward when talking, cause I tend to say things like "possibly", "maybe", "probably", and other ambiguous expressions to the extent that it has frustrated them now and then. -- http://mail.python.org/mailman/listinfo/python-list
Re: Does '!=' equivelent to 'is not'
On Jun 18, 7:26 am, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote: > En Tue, 17 Jun 2008 09:09:41 -0300, Derek Martin <[EMAIL PROTECTED]> > escribió: > > > On Tue, Jun 17, 2008 at 04:33:03AM -0300, Gabriel Genellina wrote: > >> > Basically 'a is b' and 'not(a is b)' is similar to 'id(a) == id(b)' > >> > and 'not(id(a) == id(b))' > > >> No. > > > Sure it is... he said "similar"... not identical. They are not the > > same, but they are similar. > > 'equality' and 'identity' are similar too, so the whole answer would make > no sense in that case. You can't explain identity based on things that > aren't identical. A fine grained question for a fine grained difference > requires a fine grained answer. In my defense, I admit I have the tendency to forget (purposefully) fine-grained differences if I thought that the difference was not significant enough in the context of speaking. The OP asked about != and 'is not', so I explained in terms of those being equality and identity testing respectively. To give a more concise and easy to understand example, I said that 'is not' is like using testing the 'id()' of the objects. Since (I think) the difference between != and 'is not' is much larger compared to the difference between 'is not' and 'id() test', I thought I could consider 'is not' and 'id() test' as "equivalent" in the context of this thread: 'Does != is equivalent to "is not"'. Either way, I'm sorry that I failed to put explicit notice that 'is not' and 'id() testing' isn't exactly the same either. > > Saying a flat "no" alone, without qualifying your statement is > > generally interpreted as rude in English... It's kind of like how you > > talk to children when they're too young to understand the explanation. > > Yucky. > > I didn't meant to be rude at all - and I apologize to Mr. Lie. I don't deserve the apology because the mistake is on me and I didn't feel offended, in fact I'm delighted someone could point out my mistake. > The > explanation for such strong "No" was in the paragraph below it (the idea > was to say: "No to this, yes to that") -- http://mail.python.org/mailman/listinfo/python-list
Re: Function argument conformity check
Hi, Le Wednesday 18 June 2008 20:19:12 [EMAIL PROTECTED], vous avez écrit : > Hi. I am looking for a way to check if some given set of (*args, > **kwds) conforms to the argument specification of a given function, > without calling that function. > > For example, given the function foo: > def foo(a, b, c): pass > > and some tuple args and some dict kwds, is there a way to tell if i > _could_ call foo(*args, **kwds) without getting an exception for those > arguments? I am hoping there is a way to do this without actually > writing out the argument logic python uses. > Each function object is associated to a code object which you can get with foo.func_code. Two of this object's attributes will help you: co_argcount and co_varnames. The first is the number of arguments of the function, and the second a list of all the local variables names, including the arguments (which are always the first items of the list). When some arguments have default values, they are stored in foo.func_defaults (and these arguments are always after non-default args in the co_argnames list). Finally, it seems that some flags are set in code.co_flags if the function accepts varargs like *args, **kwargs, but I don't know where these are defined. Note that I never found any doc about that and merely guessed it by playing with func objects, so consider all this possibly wrong or subject to change. -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: How to split a string containing nested commas-separated substrings
On Jun 18, 12:19 pm, Robert Dodier <[EMAIL PROTECTED]> wrote: > Hello, > > I'd like to split a string by commas, but only at the "top level" so > to speak. An element can be a comma-less substring, or a > quoted string, or a substring which looks like a function call. > If some element contains commas, I don't want to split it. > > Examples: > > 'foo, bar, baz' => 'foo' 'bar' 'baz' > 'foo, "bar, baz", blurf' => 'foo' 'bar, baz' 'blurf' > 'foo, bar(baz, blurf), mumble' => 'foo' 'bar(baz, blurf)' 'mumble' > > Can someone suggest a suitable regular expression or other > method to split such strings? > > Thank you very much for your help. > > Robert tests = """\ foo, bar, baz foo, "bar, baz", blurf foo, bar(baz, blurf), mumble""".splitlines() from pyparsing import Word, alphas, alphanums, Optional, \ Group, delimitedList, quotedString ident = Word(alphas+"_",alphanums+"_") func_call = Group(ident + "(" + Optional(Group(delimitedList(ident))) + ")") listItem = func_call | ident | quotedString for t in tests: print delimitedList(listItem).parseString(t).asList() Prints: ['foo', 'bar', 'baz'] ['foo', '"bar, baz"', 'blurf'] ['foo', ['bar', '(', ['baz', 'blurf'], ')'], 'mumble'] -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: 32 bit or 64 bit?
On Jun 18, 10:00 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: > On Jun 18, 3:02 am, Phil Hobbs > > <[EMAIL PROTECTED]> wrote: > > [EMAIL PROTECTED] wrote: > > > > That was suggested. Problem is, that sometimes the velocities are near > > > zero. So this solution, by itself, is not general enough. > > > Are you sure? I sort of doubt that you're spending zillions of > > iterations getting closer and closer to zero. It would be worth > > actually doing the error analysis and finding out. > > > Cheers, > > > Phil Hobbs > > See my comment to Brodie. Oops, the "See my comment to Brodie" was not intended to you. I meant to say: I might try your suggestion, but for now mpmath will do. Now I'm working on implementing the electromagnetic force, so I'll get back to this issue later. -- http://mail.python.org/mailman/listinfo/python-list
Re: 32 bit or 64 bit?
On Jun 18, 3:02 am, Phil Hobbs <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] wrote: > > > That was suggested. Problem is, that sometimes the velocities are near > > zero. So this solution, by itself, is not general enough. > > Are you sure? I sort of doubt that you're spending zillions of > iterations getting closer and closer to zero. It would be worth > actually doing the error analysis and finding out. > > Cheers, > > Phil Hobbs See my comment to Brodie. -- http://mail.python.org/mailman/listinfo/python-list
Re: 32 bit or 64 bit?
On Jun 18, 7:12 pm, Peter Pearson <[EMAIL PROTECTED]> wrote: > On Tue, 17 Jun 2008 08:13:40 -0400, Phil Hobbs wrote: > > [EMAIL PROTECTED] wrote: > [snip] > >> I have a physical system set up in which a body is supposed to > >> accelerate and to get very close to lightspeed, while never really > >> attaining it. After approx. 680 seconds, Python gets stuck and tells > >> me the object has passed lightspeed. I put the same equations in > >> Mathematica, again I get the same mistake around 680 seconds. So I > >> think, I have a problem with my model! Then I pump up the > >> WorkingPrecision in Mathematica to about 10. I run the same equations > >> again, and it works! At least for the first 10,000 seconds, the object > >> does not pass lightspeed. > >> I concluded that I need Python to work at a higher precision. > [snip] > > You need to change your representation. Try redoing the algebra using > > (c-v) as the independent variable, and calculate that. > > Or represent the velocity as c*tanh(b), where b is the independent > variable. If memory serves, this is the representation in which > constant acceleration corresponds to db/dt = constant. > > -- > To email me, substitute nowhere->spamcop, invalid->net. See my comment to Brodie. -- http://mail.python.org/mailman/listinfo/python-list
Re: 32 bit or 64 bit?
On Jun 17, 5:04 pm, "Richard Brodie" <[EMAIL PROTECTED]> wrote: > <[EMAIL PROTECTED]> wrote in message > > news:[EMAIL PROTECTED] > > >That was suggested. Problem is, that sometimes the velocities are near > >zero. So this solution, by itself, is not general enough. > > Maybe working in p, and delta-p would be more stable. That's a good one. It will, however, involve complicated calculations for obtaining v from p, so it might be slower than mpmath. I'll consider it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Numeric type conversions
On Jun 18, 12:23 am, John Dann <[EMAIL PROTECTED]> wrote: > On Tue, 17 Jun 2008 08:58:11 -0700 (PDT), MRAB > > <[EMAIL PROTECTED]> wrote: > >[snip] > >Please note that in slicing the start position is included and the end > >position is excluded, so that should be ByteStream[12:14]. > > Yes, I just tripped over that, in fact, hence the error in my original > post. I suppose there must be some logic in including the start > position but excluding the end position, though it does escape me for > now. I can understand making a range inclusive or exclusive but not a > mixture of the two. Suppose it's just something you have to get used > to with Python and, no doubt, much commented on in the past. > > JGD There is actually a logic to that. It's explained in the help/tutorial file, that you should think about the index as a cursor, the index itself doesn't point to the item itself, but to the interval between the item. (read this on a monospace font, or it'll look screwed up) 0 1 2 3 4 5 +---+ | A | B | C | D | E | +---+ -5 -4 -3 -2 -1 0 So to get BCD, you say [1:4] -- http://mail.python.org/mailman/listinfo/python-list
Function argument conformity check
Hi. I am looking for a way to check if some given set of (*args, **kwds) conforms to the argument specification of a given function, without calling that function. For example, given the function foo: def foo(a, b, c): pass and some tuple args and some dict kwds, is there a way to tell if i _could_ call foo(*args, **kwds) without getting an exception for those arguments? I am hoping there is a way to do this without actually writing out the argument logic python uses. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to split a string containing nested commas-separated substrings
Hi, Le Wednesday 18 June 2008 19:19:57 Robert Dodier, vous avez écrit : > Hello, > > I'd like to split a string by commas, but only at the "top level" so > to speak. An element can be a comma-less substring, or a > quoted string, or a substring which looks like a function call. > If some element contains commas, I don't want to split it. > > Examples: > > 'foo, bar, baz' => 'foo' 'bar' 'baz' > 'foo, "bar, baz", blurf' => 'foo' 'bar, baz' 'blurf' > 'foo, bar(baz, blurf), mumble' => 'foo' 'bar(baz, blurf)' 'mumble' > > Can someone suggest a suitable regular expression or other > method to split such strings? > I'd do something like this (note that it doesn't check for quote/parenthesis mismatch and removes _all_ the quotes) : def mysplit (string) : pardepth = 0 quote = False ret = [''] for car in string : if car == '(' : pardepth += 1 elif car == ')' : pardepth -= 1 elif car in ('"', "'") : quote = not quote car = '' # just if you don't want to keep the quotes if car in ', ' and not (pardepth or quote) : if ret[-1] != '' : ret.append('') else : ret[-1] += car return ret # test for s in ('foo, bar, baz', 'foo, "bar, baz", blurf', 'foo, bar(baz, blurf), mumble') : print "'%s' => '%s'" % (s, mysplit(s)) # result 'foo, bar, baz' => '['foo', 'bar', 'baz']' 'foo, "bar, baz", blurf' => '['foo', 'bar, baz', 'blurf']' 'foo, bar(baz, blurf), mumble' => '['foo', 'bar(baz, blurf)', 'mumble']' -- Cédric Lucantis -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiprecision arithmetic library question.
In article <[EMAIL PROTECTED]>, Mark Wooding <[EMAIL PROTECTED]> wrote: > Michael Press <[EMAIL PROTECTED]> wrote: > > > I already compiled and installed the GNU multiprecision library > > on Mac OS X, and link to it in C programs. > > How do I link to the library from Python? > > You know that Python already supports multiprecision integer arithmetic, > right? If you desperately want GMP, though, there's the gmpy module > (q.g.). No, I do not know that. Define desperate. Does Python support the extended Euclidean algorithm and other number theory functions? How fast does Python multiply? Not that the latter is particularly important, as C is built for speed. I've been fooling around. Ran dir(gmpy), and it does not show the full complement of GMP library functions, such as the various division functions. e.g. mpz_tdiv_qr. -- Michael Press -- http://mail.python.org/mailman/listinfo/python-list
Re: How to split a string containing nested commas-separated substrings
On Jun 18, 10:19 am, Robert Dodier <[EMAIL PROTECTED]> wrote: > Hello, > > I'd like to split a string by commas, but only at the "top level" so > to speak. An element can be a comma-less substring, or a > quoted string, or a substring which looks like a function call. > If some element contains commas, I don't want to split it. > > Examples: > > 'foo, bar, baz' => 'foo' 'bar' 'baz' > 'foo, "bar, baz", blurf' => 'foo' 'bar, baz' 'blurf' > 'foo, bar(baz, blurf), mumble' => 'foo' 'bar(baz, blurf)' 'mumble' > > Can someone suggest a suitable regular expression or other > method to split such strings? > > Thank you very much for your help. > > Robert You might look at the shlex module. It doesn't get you 100%, but its close: >>> shlex.split('foo, bar, baz') ['foo,', 'bar,', 'baz'] >>> shlex.split( 'foo, "bar, baz", blurf') ['foo,', 'bar, baz,', 'blurf'] >>> shlex.split('foo, bar(baz, blurf), mumble') ['foo,', 'bar(baz,', 'blurf),', 'mumble'] Using a RE will be tricky, especially if it is possible to have recursive nesting (which by definition REs can't handle). For a real general purpose solution you will need to create a custom parser. There are a couple modules out there that can help you with that. pyparsing is one: http://pyparsing.wikispaces.com/ Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: Ternary operator alternative in Ptyhon
kretik a écrit : I'm sure this is a popular one, but after Googling for a while I couldn't figure out how to pull this off. I'd like to short-circuit the assignment of class field values passed in this dictionary to something like this: self.SomeField = \ params.has_key("mykey") ? params["mykey"] : None) Obviously I know this is not actual Python syntax, but what would be the equivalent? I'm trying to avoid this, basically: if params.has_key("mykey"): self.SomeField = params["mykey"] else: self.SomeField = None This is not a big deal of course, but I guess my main goal is to try and figure out of I'm not missing something more esoteric in the language that lets me do this. You can also use : self.SomeField = params.has_key("mykey") and params["mykey"] or None But it's not easy to read -- Jérémie -- http://mail.python.org/mailman/listinfo/python-list
Re: Importing module PIL vs beautifulSoup.
On Jun 18, 10:18 am, Duncan Booth <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] wrote: > > I downloaded BeautifulSoup.py from > >http://www.crummy.com/software/BeautifulSoup/and being a n00bie, I > > just placed it in my Windows c:\python25\lib\ file. When I type > > "import beautifulsoup" from the interactive prompt it works like a > > charm. This seemed too easy in retrospect. > > It might be better if you put the file in \python25\lib\site-packages\ > The same import will still work, but you probably want to avoid putting > non-core files directly in \python25\lib. > > Also, it sounds like you renamed the file: "import beautifulsoup" should > fail (the file is supposed to be called BeautifulSoup.py). If you want to > be able to install other software which has been written to use > BeautifulSoup you'll need to make sure the case of the filename is correct. > > > > > Then I downloaded the PIL (Python Imaging Library) module from > >http://www.pythonware.com/products/pil/. Instead of a simple file that > > BeautifulSoup sent me, PIL is an .exe that installed itself in c: > > \python25\lib\site-packages\PIL\. However it won't load by typing > > "import pil". > > > I know I am supposed to RTFM, but a Google search has not led to the > > holy grail that Monty Python found. I realize that PIL is a package as > > opposed to a simple script (and it does not include a readme file). > > Thanks in advance for any help. > > Did you try "import PIL"? All module and package names in Python are case > sensitive. YIKES, Python is case sensitive! I knew that, says he blushing. Now it works. Thanks Duncan. Ciao, Bill -- http://mail.python.org/mailman/listinfo/python-list
Never mind folks, n00bie here forgot Python is case sensitive!
On Jun 18, 10:18 am, Duncan Booth <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] wrote: > > I downloaded BeautifulSoup.py from > >http://www.crummy.com/software/BeautifulSoup/and being a n00bie, I > > just placed it in my Windows c:\python25\lib\ file. When I type > > "import beautifulsoup" from the interactive prompt it works like a > > charm. This seemed too easy in retrospect. > > It might be better if you put the file in \python25\lib\site-packages\ > The same import will still work, but you probably want to avoid putting > non-core files directly in \python25\lib. > > Also, it sounds like you renamed the file: "import beautifulsoup" should > fail (the file is supposed to be called BeautifulSoup.py). If you want to > be able to install other software which has been written to use > BeautifulSoup you'll need to make sure the case of the filename is correct. > > > > > Then I downloaded the PIL (Python Imaging Library) module from > >http://www.pythonware.com/products/pil/. Instead of a simple file that > > BeautifulSoup sent me, PIL is an .exe that installed itself in c: > > \python25\lib\site-packages\PIL\. However it won't load by typing > > "import pil". > > > I know I am supposed to RTFM, but a Google search has not led to the > > holy grail that Monty Python found. I realize that PIL is a package as > > opposed to a simple script (and it does not include a readme file). > > Thanks in advance for any help. > > Did you try "import PIL"? All module and package names in Python are case > sensitive. -- http://mail.python.org/mailman/listinfo/python-list
SPAM
SPAM -- http://mail.python.org/mailman/listinfo/python-list
How to split a string containing nested commas-separated substrings
Hello, I'd like to split a string by commas, but only at the "top level" so to speak. An element can be a comma-less substring, or a quoted string, or a substring which looks like a function call. If some element contains commas, I don't want to split it. Examples: 'foo, bar, baz' => 'foo' 'bar' 'baz' 'foo, "bar, baz", blurf' => 'foo' 'bar, baz' 'blurf' 'foo, bar(baz, blurf), mumble' => 'foo' 'bar(baz, blurf)' 'mumble' Can someone suggest a suitable regular expression or other method to split such strings? Thank you very much for your help. Robert -- http://mail.python.org/mailman/listinfo/python-list
Re: Importing module PIL vs beautifulSoup.
[EMAIL PROTECTED] wrote: > I downloaded BeautifulSoup.py from > http://www.crummy.com/software/BeautifulSoup/ and being a n00bie, I > just placed it in my Windows c:\python25\lib\ file. When I type > "import beautifulsoup" from the interactive prompt it works like a > charm. This seemed too easy in retrospect. It might be better if you put the file in \python25\lib\site-packages\ The same import will still work, but you probably want to avoid putting non-core files directly in \python25\lib. Also, it sounds like you renamed the file: "import beautifulsoup" should fail (the file is supposed to be called BeautifulSoup.py). If you want to be able to install other software which has been written to use BeautifulSoup you'll need to make sure the case of the filename is correct. > > Then I downloaded the PIL (Python Imaging Library) module from > http://www.pythonware.com/products/pil/. Instead of a simple file that > BeautifulSoup sent me, PIL is an .exe that installed itself in c: > \python25\lib\site-packages\PIL\. However it won't load by typing > "import pil". > > I know I am supposed to RTFM, but a Google search has not led to the > holy grail that Monty Python found. I realize that PIL is a package as > opposed to a simple script (and it does not include a readme file). > Thanks in advance for any help. > Did you try "import PIL"? All module and package names in Python are case sensitive. -- http://mail.python.org/mailman/listinfo/python-list
www.nikeadishoes.com
because our company open no long time,and we have some pro in deals with oredr please make you new order to us ,i think we will have a good beginning !! Our website: www.nikeadishoes.com Choose your favorite products please trust us ,have a good beginning Email:[EMAIL PROTECTED] MSN:[EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Importing module PIL vs beautifulSoup.
I downloaded BeautifulSoup.py from http://www.crummy.com/software/BeautifulSoup/ and being a n00bie, I just placed it in my Windows c:\python25\lib\ file. When I type "import beautifulsoup" from the interactive prompt it works like a charm. This seemed too easy in retrospect. Then I downloaded the PIL (Python Imaging Library) module from http://www.pythonware.com/products/pil/. Instead of a simple file that BeautifulSoup sent me, PIL is an .exe that installed itself in c: \python25\lib\site-packages\PIL\. However it won't load by typing "import pil". I know I am supposed to RTFM, but a Google search has not led to the holy grail that Monty Python found. I realize that PIL is a package as opposed to a simple script (and it does not include a readme file). Thanks in advance for any help. -- http://mail.python.org/mailman/listinfo/python-list
ANN: eGenix mx Base Distribution 3.1.0
ANNOUNCING eGenix.com mx Base Distribution Version 3.1.0 Open Source Python extensions providing important and useful services for Python programmers. This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/eGenix-mx-Base-Distribution-3.1.0-GA.html ABOUT The eGenix.com mx Base Distribution for Python is a collection of professional quality software tools which enhance Python's usability in many important areas such as fast text searching, date/time processing and high speed data types. The tools have a proven record of being portable across many Unix and Windows platforms. You can write applications which use the tools on Windows and then run them on Unix platforms without change due to the consistent platform independent interfaces. Contents of the distribution: * mxDateTime - Date/Time Library for Python * mxTextTools - Fast Text Parsing and Processing Tools for Python * mxProxy - Object Access Control for Python * mxBeeBase - On-disk B+Tree Based Database Kit for Python * mxURL - Flexible URL Data-Type for Python * mxUID - Fast Universal Identifiers for Python * mxStack - Fast and Memory-Efficient Stack Type for Python * mxQueue - Fast and Memory-Efficient Queue Type for Python * mxTools - Fast Everyday Helpers for Python All available packages have proven their stability and usefulness in many mission critical applications and various commercial settings all around the world. * About Python: Python is an object-oriented Open Source programming language which runs on all modern platforms (http://www.python.org/). By integrating ease-of-use, clarity in coding, enterprise application connectivity and rapid application design, Python establishes an ideal programming platform for todays IT challenges. * About eGenix: eGenix is a consulting and software product company focused on providing professional quality services and products to Python users and developers (http://www.egenix.com/). NEWS The 3.1.0 release of the eGenix mx Base Distribution has a number of enhancements over the previous version 3.0.0. Apart from a few minor bug fixes, it provides a few new features: Some highlights: * mxTools now has a new mx.Tools.dlopen() function which allow loading shared libraries explicitly and from a specific path. This allows working around problems with not being able to dynamically set LD_LIBRARY_PATH on Unix platforms. * mxTools can be configured to expose a new API called mx.Tools.setproctitle() which allows setting the process title on Unix platforms. * mxBeeBase comes with a new on-disk dictionary version called BeeFixedLengthStringDict, which allows using keys with embedded \0 characters. * mxSetup, our Python distutils extension, can now build prebuilt archives that no longer require the "... build --skip ..." command to skip the build process. The uninstall command now also works for prebuilt archives and the bdist_prebuilt command has been enhanced to be able to build pure Python distributions as well. * mxSetup now also works together with setuptools to e.g. build and install the packages as eggs. Run setup.py with --use-setuptools to enable this support. For a more detailed description of changes, please see the respective package documentation on our web-site. As always, we are providing pre-compiled versions of the package for the most popular Python platforms. For all others, you can compile the package from source using "python setup.py install". DOWNLOADS The download archives and instructions for installing the packages can be found on the eGenix mx Base Distribution page: http://www.egenix.com/products/python/mxBase/ LICENSE The eGenix mx Base package is distributed under the eGenix.com Public License 1.1.0 which is a CNRI Python License style Open Source license. You can use the package in both commercial and non-commercial settings without fee or charge. The package comes with full source code SUPPORT Commercial support for these packages is available from eGenix.com. Please see http://www.egenix.com/services/support/ for details about our support offerings. Enjoy, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jun 18 2008) Python/Zope Consulting and Support ...http://www.egenix.com/ mxODBC.Zope.Database.Adapter ...
Re: Looking for lots of words in lots of files
On Jun 18, 10:29 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote: > brad wrote: > > Just wondering if anyone has ever solved this efficiently... not looking > > for specific solutions tho... just ideas. > > > I have one thousand words and one thousand files. I need to read the > > files to see if some of the words are in the files. I can stop reading a > > file once I find 10 of the words in it. It's easy for me to do this with > > a few dozen words, but a thousand words is too large for an RE and too > > inefficient to loop, etc. Any suggestions? > > Use an indexer, like lucene (available as pylucene) or a database that > offers word-indices. > > Diez I've been toying around with Nucular (http://nucular.sourceforge.net/) a bit recently for some side projects. It's pure Python and seems to work fairly well for my needs. I haven't pumped all that much data into it, though. -- http://mail.python.org/mailman/listinfo/python-list
Re: Hrounding error
> > So it seems then that python might not be very good for doing > precision floating point work, because there is a good chance its > floating points will be off by a (very small) amount? Or is there a > way to get around this and be guaranteed an accurate answer?- Hide quoted > text - > It's not a Python problem. That is just the behavior for floating- point arithmetic. casevh -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting Python exit code when calling Python script from Java program
In article <[EMAIL PROTECTED]>, > I tried using the sys.exit() method in my script and passed non -zero > values. However the value wasn't picked up the by Java > Process.exitValue() method - it kept picking up 0. On investigation > it turned out that the exit value being read is from python.exe > process, not from the Python script. I don't believe there is any such distinction. The exit status of python.exe is the exit status determined by the script. -M- -- http://mail.python.org/mailman/listinfo/python-list
Re: Hrounding error
On Jun 18, 8:02 am, "Jerry Hill" <[EMAIL PROTECTED]> wrote: > On Wed, Jun 18, 2008 at 1:47 AM, <[EMAIL PROTECTED]> wrote: > 234 - 23234.2345 > > -23000.2344 > > > This is not correct by my calculations. > > Python floating point operations use the underlying C floating point > libraries which, in turn, usually rely on the hardware's floating > point implementations. This Wikipedia article talks about how those > values are usually stored and > manipulated:http://en.wikipedia.org/wiki/IEEE_floating-point_standard > > So, which IEEE double precision floating point value would you like > instead? As far as I understand it, these are your two choices: > > 'ba490c020f76d6c0' = -23000.2344 > 'bb490c020f76d6c0' = -23000.23450002 > > Alternatively, investigate the Decimal module, but keep in mind that > it can have the same sorts of issues, just on different numbers. > Compare, for instance: > > >>> (1.0/3.0) * 3.0 > > 1.0 > > >>> from decimal import Decimal > >>> ( Decimal('1.0')/Decimal('3.0') ) * Decimal('3.0') > > Decimal("0.") > > > > -- > Jerry So it seems then that python might not be very good for doing precision floating point work, because there is a good chance its floating points will be off by a (very small) amount? Or is there a way to get around this and be guaranteed an accurate answer? -- http://mail.python.org/mailman/listinfo/python-list
The best FREE porn on the Net
http://rozrywka.yeba.pl/show.php?id=2737 -- http://mail.python.org/mailman/listinfo/python-list
The best FREE porn on the Net
http://rozrywka.yeba.pl/show.php?id=2737 -- http://mail.python.org/mailman/listinfo/python-list
Re: Does '!=' equivelent to 'is not' [drifting a little more]
Gabriel Genellina wrote: (This thread is getting way above 1cp...) What is 1cp? -- Ethan -- http://mail.python.org/mailman/listinfo/python-list
Re: 32 bit or 64 bit?
On Tue, 17 Jun 2008 08:13:40 -0400, Phil Hobbs wrote: > [EMAIL PROTECTED] wrote: [snip] >> I have a physical system set up in which a body is supposed to >> accelerate and to get very close to lightspeed, while never really >> attaining it. After approx. 680 seconds, Python gets stuck and tells >> me the object has passed lightspeed. I put the same equations in >> Mathematica, again I get the same mistake around 680 seconds. So I >> think, I have a problem with my model! Then I pump up the >> WorkingPrecision in Mathematica to about 10. I run the same equations >> again, and it works! At least for the first 10,000 seconds, the object >> does not pass lightspeed. >> I concluded that I need Python to work at a higher precision. [snip] > You need to change your representation. Try redoing the algebra using > (c-v) as the independent variable, and calculate that. Or represent the velocity as c*tanh(b), where b is the independent variable. If memory serves, this is the representation in which constant acceleration corresponds to db/dt = constant. -- To email me, substitute nowhere->spamcop, invalid->net. -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for lots of words in lots of files
Kris Kennaway wrote: If you can't use an indexer, and performance matters, evaluate using grep and a shell script. Seriously. grep is a couple of orders of magnitude faster at pattern matching strings in files (and especially regexps) than python is. Even if you are invoking grep multiple times it is still likely to be faster than a "maximally efficient" single pass over the file in python. This realization was disappointing to me :) Kris Adding to this: Then again, there is nothing wrong with wrapping grep from python and revert to a pure python 'solution' if the system has no grep. Reinventing the wheel is usually only practical if the existing ones aren't round :-) -- mph -- http://mail.python.org/mailman/listinfo/python-list
Re: go to specific line in text file
On Jun 17, 3:10 am, Patrick David <[EMAIL PROTECTED]> wrote: > > I am searching for a way to jump to a specific line in a text file, let's > say to line no. 9000. > Is there any method like file.seek() which leads me to a given line instead > of a given byte? > As others have said, no. But if you're wondering how other file formats do this, like BDB or PostgreSQL data files, which absolutely have to jump to the magical spot in the file where the data is, they keep an index at the beginning of the file that points to what byte the data they are looking for is in. So if it's really important to be able to do this, consider that. -- http://mail.python.org/mailman/listinfo/python-list
Re: print problem
On Tue, 17 Jun 2008 04:46:38 -0300, Gabriel Genellina wrote: > En Tue, 17 Jun 2008 04:10:41 -0300, Rich Healey escribió: >> Gabriel Genellina wrote: >>> En Tue, 17 Jun 2008 03:15:11 -0300, pirata <[EMAIL PROTECTED]> escribió: >>> I was trying to print a dot on console every second to indicates running process, so I wrote, for example: for i in xrange(10): print ".", time.sleep(1) Idealy, a dot will be printed out each second. But there is nothing print out until after 10 seconds, all 10 dots come out together. I've tried lose the comma in the print statement, and it works. Is that because of the print statement buffer the characters until there is a new line character? [snip] >> Or just write to sys.stdout without the print wrapper.. > > I think the output is still buffered, even if you write > directly to sys.stdout, but I don't have a Linux box to > test right now. Here (Python 2.4.3), dots written to sys.stdout are saved up and appear all at once. However, you can flush the buffer yourself by invoking sys.stdout.flush() immediately after either the "print" or the "sys.stdout.write". -- To email me, substitute nowhere->spamcop, invalid->net. -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for lots of words in lots of files
I forgot to mention another way: put one thousand monkeys to work on it. ;) RB Robert Bossy wrote: brad wrote: Just wondering if anyone has ever solved this efficiently... not looking for specific solutions tho... just ideas. I have one thousand words and one thousand files. I need to read the files to see if some of the words are in the files. I can stop reading a file once I find 10 of the words in it. It's easy for me to do this with a few dozen words, but a thousand words is too large for an RE and too inefficient to loop, etc. Any suggestions? The quick answer would be: grep -F -f WORDLIST FILE1 FILE2 ... FILE1000 where WORDLIST is a file containing the thousand words, one per line. The more interesting answers would be to use either a suffix tree or an Aho-Corasick graph. - The suffix tree is a representation of the target string (your files) that allows to search quickly for a word. Your problem would then be solved by 1) building a suffix tree for your files, and 2) search for each word sequentially in the suffix tree. - The Aho-Corasick graph is a representation of the query word list that allows fast scanning of the words on a target string. Your problem would then be solved by 1) building an Aho-Corasick graph for the list of words, and 2) scan sequentially each file. The preference for using either one or the other depends on some details of your problems: the expected size of target files, the rate of overlaps between words in your list (are there common prefixes), will you repeat the operation with another word list or another set of files, etc. Personally, I'd lean towards Aho-Corasick, it is a matter of taste; the kind of applications that comes to my mind makes it more practical. Btw, the `grep -F -f` combo builds an Aho-Corasick graph. Also you can find modules for building both data structures in the python package index. Cheers, RB -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for lots of words in lots of files
brad wrote: Just wondering if anyone has ever solved this efficiently... not looking for specific solutions tho... just ideas. I have one thousand words and one thousand files. I need to read the files to see if some of the words are in the files. I can stop reading a file once I find 10 of the words in it. It's easy for me to do this with a few dozen words, but a thousand words is too large for an RE and too inefficient to loop, etc. Any suggestions? The quick answer would be: grep -F -f WORDLIST FILE1 FILE2 ... FILE1000 where WORDLIST is a file containing the thousand words, one per line. The more interesting answers would be to use either a suffix tree or an Aho-Corasick graph. - The suffix tree is a representation of the target string (your files) that allows to search quickly for a word. Your problem would then be solved by 1) building a suffix tree for your files, and 2) search for each word sequentially in the suffix tree. - The Aho-Corasick graph is a representation of the query word list that allows fast scanning of the words on a target string. Your problem would then be solved by 1) building an Aho-Corasick graph for the list of words, and 2) scan sequentially each file. The preference for using either one or the other depends on some details of your problems: the expected size of target files, the rate of overlaps between words in your list (are there common prefixes), will you repeat the operation with another word list or another set of files, etc. Personally, I'd lean towards Aho-Corasick, it is a matter of taste; the kind of applications that comes to my mind makes it more practical. Btw, the `grep -F -f` combo builds an Aho-Corasick graph. Also you can find modules for building both data structures in the python package index. Cheers, RB -- http://mail.python.org/mailman/listinfo/python-list
Re: go to specific line in text file
Patrick David wrote: Hello NG, I am searching for a way to jump to a specific line in a text file, let's say to line no. 9000. Is there any method like file.seek() which leads me to a given line instead of a given byte? Hope for help Patrick Others have given the general answer (No), but if you are lucky enough to have FIXED length lines you can jump by just calculating the byte offset of the beginning character in line 9000 by using file.seek() and then read the bytes. You didn't say anything about the format of the file. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: dict order
On Jun 18, 4:45 pm, Kirk Strauser <[EMAIL PROTECTED]> wrote: > At 2008-06-18T10:32:48Z, [EMAIL PROTECTED] writes: > > # untested 2.5 > > for keys in dict_one.items(): > > if keys in dict_two: > > if dict_one[keys] != dict_two[keys]: > > # values are different > > else: > > # key is not present > > That fails if there is an item in dict_two that's not in dict_one. > -- > Kirk Strauser > The Day Companies True :) -- http://mail.python.org/mailman/listinfo/python-list
Re: urllib (54, 'Connection reset by peer') error
[EMAIL PROTECTED] wrote: Thanks for the help. The error handling worked to a certain extent but after a while the server does seem to stop responding to my requests. I have a list of about 7,000 links to pages I want to parse the HTML of (it's basically a web crawler) but after a certain number of urlretrieve() or urlopen() calls the server just stops responding. Anyone know of a way to get around this? I don't own the server so I can't make any modifications on that side. I think someone's already mentioned this, but it's almost certainly an explicit or implicit throttling on the remote server. If you're pulling 7,000 pages from a single server you need to be sure that you're within the Terms of Use of that service, or at the least you need to contact the maintainers in courtesy to confirm that this is acceptable. If you don't you may well cause your IP block to be banned on their network, which could affect others as well as yourself. TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: urllib (54, 'Connection reset by peer') error
Thanks for the help. The error handling worked to a certain extent but after a while the server does seem to stop responding to my requests. I have a list of about 7,000 links to pages I want to parse the HTML of (it's basically a web crawler) but after a certain number of urlretrieve() or urlopen() calls the server just stops responding. Anyone know of a way to get around this? I don't own the server so I can't make any modifications on that side. -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for lots of words in lots of files
Hi, Use a suffix tree. First make yourself a suffix tree of your thousand files and the use it. This is a classical problem for that kind of structure. Just search "suffix tree" or "suffix tree python" on google to find a definition and an implementation. (Also Jon Bentley's "Programming Pearls" is a great book to read) Regards Francis Girard 2008/6/18 brad <[EMAIL PROTECTED]>: > Just wondering if anyone has ever solved this efficiently... not looking > for specific solutions tho... just ideas. > > I have one thousand words and one thousand files. I need to read the files > to see if some of the words are in the files. I can stop reading a file once > I find 10 of the words in it. It's easy for me to do this with a few dozen > words, but a thousand words is too large for an RE and too inefficient to > loop, etc. Any suggestions? > > Thanks > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: question relateding to parsing dbf files.
At 2008-06-18T12:50:20Z, "Krishnakant Mane" <[EMAIL PROTECTED]> writes: > hello all. > I need to parse some dbf files through python. > the reason being that I have to migrate some old data from dbf files > to postgresql. > all that I need to know is if some one has got a working code sample > using dbfpy. > I found this module suitable for my work but can't figure out how to use it. > else, if there is any other module, please recommend so. > happy hacking. > Krishnakant. Does it have to by in Python? I host this project, written in C++: http://honeypot.net/project/xbasetopg . If that's too complicated, I've written a replacement in straight C but I haven't published it yet. I use these programs to sync our legacy FoxPro database to our new PostgreSQL servers on an hourly basis. Syncing 4GB of data tables about 10 minutes. -- Kirk Strauser The Day Companies -- http://mail.python.org/mailman/listinfo/python-list
Re: dict order
At 2008-06-18T10:32:48Z, [EMAIL PROTECTED] writes: > # untested 2.5 > for keys in dict_one.items(): > if keys in dict_two: > if dict_one[keys] != dict_two[keys]: > # values are different > else: > # key is not present That fails if there is an item in dict_two that's not in dict_one. -- Kirk Strauser The Day Companies -- http://mail.python.org/mailman/listinfo/python-list
Re: Hrounding error
On Wed, Jun 18, 2008 at 1:47 AM, <[EMAIL PROTECTED]> wrote: 234 - 23234.2345 > -23000.2344 > > This is not correct by my calculations. Python floating point operations use the underlying C floating point libraries which, in turn, usually rely on the hardware's floating point implementations. This Wikipedia article talks about how those values are usually stored and manipulated: http://en.wikipedia.org/wiki/IEEE_floating-point_standard So, which IEEE double precision floating point value would you like instead? As far as I understand it, these are your two choices: 'ba490c020f76d6c0' = -23000.2344 'bb490c020f76d6c0' = -23000.23450002 Alternatively, investigate the Decimal module, but keep in mind that it can have the same sorts of issues, just on different numbers. Compare, for instance: >>> (1.0/3.0) * 3.0 1.0 >>> from decimal import Decimal >>> ( Decimal('1.0')/Decimal('3.0') ) * Decimal('3.0') Decimal("0.") >>> -- Jerry -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for lots of words in lots of files
Calvin Spealman wrote: Upload, wait, and google them. Seriously tho, aside from using a real indexer, I would build a set of the words I'm looking for, and then loop over each file, looping over the words and doing quick checks for containment in the set. If so, add to a dict of file names to list of words found until the list hits 10 length. I don't think that would be a complicated solution and it shouldn't be terrible at performance. If you need to run this more than once, use an indexer. If you only need to use it once, use an indexer, so you learn how for next time. If you can't use an indexer, and performance matters, evaluate using grep and a shell script. Seriously. grep is a couple of orders of magnitude faster at pattern matching strings in files (and especially regexps) than python is. Even if you are invoking grep multiple times it is still likely to be faster than a "maximally efficient" single pass over the file in python. This realization was disappointing to me :) Kris -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for lots of words in lots of files
Upload, wait, and google them. Seriously tho, aside from using a real indexer, I would build a set of the words I'm looking for, and then loop over each file, looping over the words and doing quick checks for containment in the set. If so, add to a dict of file names to list of words found until the list hits 10 length. I don't think that would be a complicated solution and it shouldn't be terrible at performance. If you need to run this more than once, use an indexer. If you only need to use it once, use an indexer, so you learn how for next time. On Jun 18, 2008, at 10:28 AM, brad wrote: Just wondering if anyone has ever solved this efficiently... not looking for specific solutions tho... just ideas. I have one thousand words and one thousand files. I need to read the files to see if some of the words are in the files. I can stop reading a file once I find 10 of the words in it. It's easy for me to do this with a few dozen words, but a thousand words is too large for an RE and too inefficient to loop, etc. Any suggestions? Thanks -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for lots of words in lots of files
brad wrote: > Just wondering if anyone has ever solved this efficiently... not looking > for specific solutions tho... just ideas. > > I have one thousand words and one thousand files. I need to read the > files to see if some of the words are in the files. I can stop reading a > file once I find 10 of the words in it. It's easy for me to do this with > a few dozen words, but a thousand words is too large for an RE and too > inefficient to loop, etc. Any suggestions? Use an indexer, like lucene (available as pylucene) or a database that offers word-indices. Diez -- http://mail.python.org/mailman/listinfo/python-list