Re: Html or Pdf to Rtf (Linux) with Python
Hello! You might take a look at PyRTF in PyPI. It's still in beta, I think PyRTF would be the right choice, thanks. Yust had a short look at it. Lg, AXEL. -- The key words MUST, MUST NOT, REQUIRED, SHALL, SHALL NOT, SHOULD, SHOULD NOT, RECOMMENDED, MAY, and OPTIONAL in this document are to be interpreted as described in RFC 2119 [http://ietf.org/rfc/rfc2119.txt] -- http://mail.python.org/mailman/listinfo/python-list
Re: [ANN] [Hack] Import binary extensions from zipfiles, windows only
Delaney, Timothy C (Timothy) [EMAIL PROTECTED] writes: Thomas Heller wrote: zipextimporter.py contains the ZipExtImporter class which allows to load Python binary extension modules contained in a zip.archive, without unpacking them to the file system. I take it this was what you were talking about the other day when you mentioned single-file applications produced by py2exe ... It's a step in this direction only. Thomas -- http://mail.python.org/mailman/listinfo/python-list
Potential improvement on delegation via explicit calls and super
Derived classes sometimes need to delegate portions of the work in overridden methods to methods in their base classes. This was traditionally done with explicit calls in python, e.g., class Derived(Left, Right): def __init__(self, myarg, larg, rarg): Left.__init__(self, larg) Right.__init__(self, rarg) self.data = myarg print 'derived' This worked great. It was possible to grab the appropriate arguments and send them off to the right point. However, there was a problem. class Base: def __init__(self): print 'base' class Left(Base): def __init__(self, arg): Base.__init__(self) print 'left' class Right(Base): def __init__(self, arg): Base.__init__(self) print 'right' Now, when Derived(Left, Right) is initialized, Base.__init__ is called twice. Sometimes that's O.K. Usually, it's a bad thing. Along came new-style classes and 'super'. Unfortunately, super-based delegation doesn't play nicely with traditional classes. http://www.ai.mit.edu/people/jknight/super-harmful/ Moreover, it undermines any attempts to control which subset of arguments go to which base class. This second problem is serious. In real life, base classes differ from each other: I need to be able to send the right arguments to each. What I really want to do is explicitly delegate tasks to base classes, choosing the arguments to send to each, but avoid double-calls resulting from reconverging paths in the inheritance directed acyclic (pray it's acyclic) graph. I think the appended code may solve this problem, play nicely with traditional classes, and allow the coder to send the right arguments to the right base classes. However, I'm new to python so I need some help. 1) Is my thinking reasonable or is there an better way to solve the reconvergent path problem in python without undermining control over arguments? 2) What's the proper way to rewrite the appended code. I'm sure it's dreadfully inefficient. There are also probably ways to make its use more intuitive, but I'm new to the language so I don't know the tricks yet. Thanks for any tips, -Robert Dick- '''See the example at the bottom.''' import inspect def flatten_tree(tree): '''Flatten a tree represented by nested lists''' if isinstance(tree, list): return [j for i in tree for j in flatten_tree(i)] else: return (tree,) # Cache for delegation decisions. call_cache = set() def should_call(self, pos, supr): '''Examines the inheritance DAG (might work for DCGs, too... haven't checked) for 'self' to determine whether 'pos' is the leftmost derived for 'supr'. Returns bool. Caches results for performance.''' if (self.__class__, pos, supr) in call_cache: return True ct = flatten_tree(inspect.getclasstree(inspect.getmro(self.__class__), True)) # ct is a list of (class, (base classes)) tuples # Find the first instance of the supr as a base class do_call = pos is [cls for cls, bases in ct if supr in bases][0] if do_call: call_cache.add((self.__class__, pos, supr)) return do_call def delegate(self, pos, s_call, *pargs, **kargs): '''If 'pos' is the leftmost derived for 's_call' in the 'self' inheritance DAG, call s_call with 'pargs' and 'kargs'.''' if inspect.ismethoddescriptor(s_call): supr = s_call.__objclass__ else: supr = s_call.im_class if should_call(self, pos, supr): s_call(self, *pargs, **kargs) if __name__ == '__main__': class Base(object): def __init__(self): delegate(self, Base, object.__init__) print 'base' class Left(Base): def __init__(self): delegate(self, Left, Base.__init__) print 'left' class Right(Base): def __init__(self): delegate(self, Right, Base.__init__) print 'right' class Der(Left, Right): def __init__(self): delegate(self, Der, Left.__init__) delegate(self, Der, Right.__init__) print 'der' der = Der() -- http://mail.python.org/mailman/listinfo/python-list
Re: Winge IDE Issue - an suggestions?
Mike Thompson wrote: File C:\Python23\Lib\site-packages\elementtree\ElementTree.py, line 709, in _write for n in node: File C:\Python23\Lib\site-packages\elementtree\ElementTree.py, line 227, in __getitem__ return self._children[index] The exception is triggered in ElementTree but the code is fine. Something about the Wing IDE debuger is causing this exception to be thrown. note that the code is using a for-loop to process all items in a container object. the IndexError is supposed to tell the for-loop to stop; having a Python IDE report this as an error is remarkably brain-dead... (do they stop on StopIteration exceptions too? or IOError exceptions from open?) /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Why are tuples immutable?
Op 2004-12-17, Jeff Shannon schreef [EMAIL PROTECTED]: Adam DePrince wrote: And how exactly do you propose to mutate an object without changing its hash value? * Create this mutate-able object type. * Create two objects that are different with different hash values. * Mutate one so that it is the same as the other. * Compare their hash values. If the hash values are the same, you lose because you didn't keep your original promise. If the hash values are different then you just broke your object because two objects with the same value must have the same hash value, but yours are different. Correct me if I'm wrong, here, but I believe that what you're saying here (and my vague memories of the little bit that I've read about hashes) is that, for a well-behaved hash function, then A == B should imply that hash(A) == hash(B). (The reverse is *not* true, however -- hash(A) == hash(B) does not necessarily say anything about whether A == B.) If that is a correct condition for a well-behaved hash function, then it is indeed impossible to have a well-behaved hash function that can be useful in the face of object mutation. For something like a list, one can only define a poorly-behaved hash-like function. You are looking at it in a too limited way. You are not forced to have an == operator that behaves in standard ways. For instance you can have objects that are only equal if they are the same and thus can be unequal even if all components are equal. Even if To take another approach -- given some function that allows lists to (pretend to be) hashable: . key = [1,2] . d[key] = 'foo' . d[[1,2]] . key.append(3) . d[key] ??? . As I understand it, it is impossible for there to be a hash function for which both of these cases can return the same object. How about: hash = id You also make the fault that because people ask for the possibility of keys being mutable objects, that they want to mutate those object while being a key. For most uses of dicts, it is necessary that the first case be valid -- a dict isn't going to be very useful to me if I have to pass around all of the objects used as keys in order to access it. Equality-based hashes are necessary, so the second case must then be disallowed. But you should be carefull not to limit people to what you think is usefull. But isn't it a bit nonsensical that, without ever rebinding key, one can do something like . d[key] = 'foo' . frombulate(key) . d[key] Traceback (most recent call last): File interactive input, line 1, in ? KeyError: key . It is just as nonsensical that, without ever rebinding an element, one can unsort a list, or violate the heap invariant of a list. In order to maintain the logical consistency that if an object is used as a dict key, that same object should reasonably be expected to retrieve the same value, identity-based hashes are necessary. As a result, the first option must be disallowed. Then why don't we disallow lists of mutable objects to be sorted or to be made into a heap. In fact each time we have a structure that relies on some invariant among its members we should disallow mutable members because with mutable members the invariant can be violated without ever rebinding one of the elements. In either case, if it's ever possible for equality to change while identity doesn't, then somewhere along the lines one of the core requirements, the contract if you will, of a dictionary *must* be broken. And while it may be possible to get away with breaking that contract some of the time (by postulating, for example, that if one mutates a dict key then things will break), this will result in more bugs and more confusion over time. There is no way for Python to be able to behave consistently in the face of mutable dict keys, therefore (In the face of ambiguity, refuse the temptation to guess.) Python declines the temptation of making it trivial to use mutable objects as dict keys. As it turns out, python makes no difference in difficulty for making either mutable or immutable objects usable as dictionary keys. The only difference is that python only made its standard immutable types hashable and not its standard mutable objects. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: Multithreading tkinter question
Oleg Paraschenko wrote: [snip] In my case Hello works and Quit doesn't (GUI stays frozen). Linux, Python 2.3.3, pygtk-0.6.9. That's not a multithreading issue, but just the way the quit method works. Try: - import time from Tkinter import * root = Tk() b = Button(root, text='Quit') b.configure(command=root.quit) b.pack() root.mainloop() time.sleep(2) - When you click the Quit button, the GUI stays there until the time.sleep ends. root.quit just goes out of the mainloop; it doesn't destroy the widgets. To do that, you have to add an explicit root.destroy() after root.mainloop() -- - Eric Brunel eric (underscore) brunel (at) despammed (dot) com - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Step by step: Compiling extensions with MS Visual C++ Toolkit 2003 - msvccompiler-patch.txt (0/1)
Having done steps 1 to 10, I tried building Numeric-23.6. And got the following error-msg: F:\install\Numeric-23.6python setup.py build running build running build_py running build_ext building '_numpy' extension D:\Programme\Microsoft Visual C++ Toolkit 2003\bin\cl.exe /c /nologo /Ox /MD /W3 /GX /DNDEBUG -I/usr/include/atlas -IInclude -IPackages\FFT\Include -IPackages\R NG\Include -ID:\Python24\include -ID:\Python24\PC /TcSrc\_numpymodule.c /Fobuild \temp.win32-2.4\Release\Src\_numpymodule.obj _numpymodule.c d:\Python24\include\pyconfig.h(30) : fatal error C1083: Cannot open include file : 'io.h': No such file or directory error: command 'D:\Programme\Microsoft Visual C++ Toolkit 2003\bin\cl.exe' fai led with exit status 2 why? Regards Wolfgang -- http://mail.python.org/mailman/listinfo/python-list
pywhich script - where is that module?
Have you ever wondered where your python modules get imported from? Here is a little script, called pywhich, that will tell you. -- \/ \/ (O O) -- oOOo~(_)~oOOo Keith Dart [EMAIL PROTECTED] public key: ID: F3D288E4 #!/usr/bin/env python pywhich modname Tell which Python module is imported. import sys def main(argv): if len(argv) 2: print __doc__ return for modname in argv[1:]: try: mod = __import__(modname) except: print No module or package by named '%s' found. % modname else: print %15s : %s % (modname, mod.__file__) main(sys.argv) -- http://mail.python.org/mailman/listinfo/python-list
Re: Why are tuples immutable?
jfj wrote: Why can't we __setitem__ for tuples? It seems from your suggestions here that what you really want is a single sequence type, list, instead of two sequence types: tuple and list. Under your design, list would support hash, and it would be up to the programmer to make sure not to modify a list when using it as a key to a dict. The important thing to understand is that, while this is not an unreasonable design decision, it's not the design decision that's been made for Python. Reading the docs and some of GvR's comments on python-dev, my understanding is that, while a single sequence type would have sufficed, the belief was that there were two mostly non-overlapping sets of tasks that one might want to do with sequences. One set of tasks dealt with small collections of related data which may be of different types which are operated on as a group[1] (tuples), while the other set of tasks dealt with hold[ing] a varying number of objects all of which have the same type and which are operated on one-by-one[1] (lists). Now, when you use a sequence as a key to a dict, you're operating on the sequence as a group, not one-by-one. Given the above conceptions of tuple and list then, it is natural to provide tuple with hash support, while leaving it out of list. Note also that tuples being immutable also falls out of the tuple description above too. If you're operating on the sequence as a group, then there's no need for __setitem__; __setitem__ is used to operate on a sequence one-by-one. I understand that you'd like a type that is operated on one-by-one, but can also be considered as a group (e.g. is hashable). Personally, I don't have any use for such a type, but perhaps others do. The right solution in this case is not to try to redefine tuple or list, but to write a PEP[2] and suggest a new datatype that serves your purposes. I'll help you out and provide you with an implementation: =) class hashablelist(list): def __hash__(self): return hash(tuple(self)) Now all you need to do is write the Abstract, Motivation and Rationale, and persuade the people on c.l.py and python-dev that this is actually a useful addition to the language. Steve [1] http://www.python.org/doc/faq/general.html#why-are-there-separate-tuple-and-list-data-types [2] http://www.python.org/peps/pep-0001.html -- http://mail.python.org/mailman/listinfo/python-list
Re: lies about OOP
To canadians there is no outside of hockey games. Jeff Shannon wrote: Peter Hansen wrote: P.S.: I'm only half Danish, but the other half is from a particularly bloodthirsty line of Canadians. I thought it was physically impossible for Canadians to be bloodthirsty outside of hockey games... ;) Jeff Shannon Technician/Programmer Credit International -- http://mail.python.org/mailman/listinfo/python-list
Re: BASIC vs Python
On Fri, 17 Dec 2004 01:43:56 -0600, rumours say that Mike Meyer [EMAIL PROTECTED] might have written: Assembler was better - at least you had recursion with assembler. You had recursion with BASIC --what you probably mean is that you had no stacked parameters (unless you imitated that with using an indexed array). 90 rem recursion 100 print beautiful colours 110 gosub 100 -- TZOTZIOY, I speak England very best. Be strict when sending and tolerant when receiving. (from RFC1958) I really should keep that in mind when talking with people, actually... -- http://mail.python.org/mailman/listinfo/python-list
Re: Cool object trick
Except what if you want to access elements based on user input or something? you can't do var = varA obj = struct(varA = Hello) print obj.var and expect it to say Hello to you. objects contain a __dict__ for a reason :P Certainly makes writing 'print obj.spam, obj.spam, obj.eggs, obj.bacon, obj.sausages, and, obj.spam' a lot easier ;-) then why dont you have a breakfast class? if you have this many properties associated with the same thing you might as well stick them in a class anyway. [EMAIL PROTECTED] wrote: I rather like it! I prefer writing obj.spam to obj[spam]! I wonder if there is a technical downside to this use of Python? P.S. Certainly makes writing 'print obj.spam, obj.spam, obj.eggs, obj.bacon, obj.sausages, and, obj.spam' a lot easier ;-) -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Jive Sent: 17 December 2004 06:29 To: [EMAIL PROTECTED] Subject: Re: Cool object trick Kinda cool. It's occured to me that just about everything Pythonic can be done with dicts and functions. Your Obj is just a dict with an alternate syntax. You don't have to put quotes around the keys. But that's cool. class struct(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) # Indented this way, it looks like a struct: obj = struct( saying = Nee , something = different , spam = eggs ) print obj.spam # Is that really much different from this? obj2 = { saying : Nee , something : different , spam : eggs } print obj2[spam] -- http://mail.python.org/mailman/listinfo/python-list
MDaemon Warning - virus found: RETURNED MAIL: DATA FORMAT ERROR
*** WARNING ** Este mensaje ha sido analizado por MDaemon AntiVirus y ha encontrado un fichero anexo(s) infectado(s). Por favor revise el reporte de abajo. AttachmentVirus name Action taken -- mail.zip I-Worm.Mydoom.m Removed ** The original message was received at Fri, 17 Dec 2004 10:33:14 +0100 from [221.69.228.236] - The following addresses had permanent fatal errors - [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Python RSS aggregator?
Back in 2000 I made a news aggregation site (REALpolitik, http://www.realpolitik.com/) since I didn't find anything that fit my needs. (REALpolitik is unfortunately made in Perl; it was my last significant project before I started using Python for most of my work.) At the time, RSS had not reached the near-universality that it has now, so RP itself uses a combination of custom scraping and whatever XML-type feeds that were available. I've checked and all the feeds _I_ care about :-) are available in RSS now, so it would make sense to move to an RSS aggregator if it has the same features. I've looked around at some that are available, both in Python and not, and haven't found anything that had the feature set I want. One in Python would obviously be a huge benefit. I'm not looking for anything all that fancy, but there are a combination of some seemingly basic features I just can't seem to find in other aggregators. They are: - one-page display: It's awkward going back and forth between multiple feeds in a hierarchical format, and so it's much nicer if they're all presented on one page available for perusal. - filtering news items: Preferably for filtering out as well as highlighting, and also being able to selectively pass on, say, the first item in an RSS feed, since some popular feeds use that slot as an advertisement. - caching news items: I read news sporadically throughout the day, so one feature I really like is the ability to queue up new items over time, as distinguished by unique GUID. For example, if an RSS feed only provided one (unique) item at all in its feed and that was updated once a day, letting the system run for several days would collect them all, each stored uniquely and available. - recent items: When you check for news, it only shows you the news items in each category that are new since you last caught up (catching up is the equivalent of a mark all as read feature). That way, new news accumulates, and it's only news you haven't seen before. Somewhat surprisingly to me, I can't seem to find an aggregator that supports all these features (using Mozilla). Is it possible it's time for another Yet Another-type project? -- Erik Max Francis [EMAIL PROTECTED] http://www.alcyone.com/max/ San Jose, CA, USA 37 20 N 121 53 W AIM erikmaxfrancis If love be good, from whence cometh my woe? -- Chaucer -- http://mail.python.org/mailman/listinfo/python-list
Re: create lowercase strings in lists - was: (No subject)
Thanks for the help. This is the final script: #!/usr/bin/env python import os import sys import time import string import pexpect import commands # Test if the words of list2 elements appear in any order in list1 elements # disregarding case and parens # Reference list list1 = [a b C (D), D A B, A B E] # Test list list2 = [A B C D, A B D, A E F, A (E) B, A B, E A B ] def normalize(text, unwanted = (), table = string.maketrans(string.ascii_uppercase,string.ascii_lowercase)): text.translate(table,unwanted) return set(text.split()) reflist = [normalize(element) for element in list1] print reflist #This is the list of sets to test against def testmember(element): is element a member of the reflist, according to the above rules? testelement = normalize(element) #brute force comparison until match - depends on small reflist for el in reflist: if el.issuperset(testelement): return True return False for element in list2: print element, testmember(element) the trouble is it throws up the following error for set: $ ./test.py Traceback (most recent call last): File ./test.py, line 23, in ? reflist = [normalize(element) for element in list1] File ./test.py, line 20, in normalize return set(text.split()) NameError: global name 'set' is not defined when I checked http://docs.python.org/lib/genindex.html#letter-s it said that set() (built-in function) The python I use is the one that comes with cygwin. Does anybody know if the following version of python is incomplete or do I need to call built in functions in a different way? $ python Python 2.3.4 (#1, Jun 13 2004, 11:21:03) [GCC 3.3.1 (cygming special)] on cygwin Type help, copyright, credits or license for more information. Michael Spencer [EMAIL PROTECTED] wrote: Steve Holden wrote: Mark Devine wrote: Actually what I want is element 'class-map match-all cmap1' from list 1 to match 'class-map cmap1 (match-all)' or 'class-map cmap1 mark match-all done' in list 2 but not to match 'class-map cmap1'. Each element in both lists have multiple words in them. If all the words of any element of the first list appear in any order within any element of the second list I want a match but if any of the words are missing then there is no match. There are far more elements in list 2 than in list 1. sounds like a case for sets... # NB Python 2.4 ... # Test if the words of list2 elements appear in any order in list1 elements # disregarding case and parens ... # Reference list list1 = [a b C (D), ... D A B, ... A B E] # Test list list2 = [A B C D, #True ... A B D, #True ... A E F, #False ... A (E) B,#True ... A B, #True ... E A B ] ... def normalize(text, unwanted = ()): ... conv = .join(char.lower() for char in text if char not in unwanted) ... return set(conv.split()) ... reflist = [normalize(element) for element in list1] print reflist ... [set(['a', 'c', 'b', 'd']), set(['a', 'b', 'd']), set(['a', 'b', 'e'])] This is the list of sets to test against def testmember(element): ... is element a member of the reflist, according to the above rules? ... testelement = normalize(element) ... #brute force comparison until match - depends on small reflist ... for el in reflist: ... if el.issuperset(testelement): ... return True ... return False ... for element in list2: ... print element, testmember(element) ... A B C D True A B D True A E F False A (E) B True A B True E A B True Michael -- http://mail.python.org/mailman/listinfo/python-list _ Sign up for eircom broadband now and get a free two month trial.* Phone 1850 73 00 73 or visit http://home.eircom.net/broadbandoffer -- http://mail.python.org/mailman/listinfo/python-list
Re: Cool object trick
Steven Bethard wrote: Alex Stapleton wrote: you can't do var = varA obj = struct(varA = Hello) print obj.var and expect it to say Hello to you. The Bunch object from the PEP can take parameters in the same way that dict() and dict.update() can, so this behavior can be supported like: b = Bunch({varA:Hello!}) b.varA 'Hello!' or b = Bunch([(varA, Hello!)]) b.varA 'Hello!' Steve thats nothing like what i described. you are setting the variable name in your code (b.varA), not generating the variable name in a string (var = varA) (dictionary key) at run-time and fetching it from the __dict__ like i was attempting to describe. -- http://mail.python.org/mailman/listinfo/python-list
Re: create lowercase strings in lists - was: (No subject)
Mark Devine wrote: the trouble is it throws up the following error for set: $ ./test.py Traceback (most recent call last): File ./test.py, line 23, in ? reflist = [normalize(element) for element in list1] File ./test.py, line 20, in normalize return set(text.split()) NameError: global name 'set' is not defined The set type became a builtin in Python 2.4. I would suggest upgrading, but if this is not an option, you can put this at the top of the file, and it should get rid of the NameError: from sets import Set as set Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: create lowercase strings in lists - was: (No subject)
Thanks. This version is the version that comes with cygwin. They must be behind. Steven Bethard [EMAIL PROTECTED] wrote: Mark Devine wrote: the trouble is it throws up the following error for set: $ ./test.py Traceback (most recent call last): File ./test.py, line 23, in ? reflist = [normalize(element) for element in list1] File ./test.py, line 20, in normalize return set(text.split()) NameError: global name 'set' is not defined The set type became a builtin in Python 2.4. I would suggest upgrading, but if this is not an option, you can put this at the top of the file, and it should get rid of the NameError: from sets import Set as set Steve -- http://mail.python.org/mailman/listinfo/python-list _ Sign up for eircom broadband now and get a free two month trial.* Phone 1850 73 00 73 or visit http://home.eircom.net/broadbandoffer -- http://mail.python.org/mailman/listinfo/python-list
Re: Cool object trick
Alex Stapleton wrote: you are setting the variable name in your code (b.varA), not generating the variable name in a string (var = varA) (dictionary key) at run-time and fetching it from the __dict__ like i was attempting to describe. Ahh. Well if you just want to get an attribute, I don't see why you wouldn't do it the normal way: b = Bunch(varA=Hello!) getattr(b, varA) 'Hello!' That's what getattr's for. ;) No need to go poking around in __dict__. Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: BASIC vs Python
Mike Meyer wrote: BASIC as implented by Microsoft for the Apple II and the TRS 80 (among others) is simply the worst programming language I have ever encountered. Assembler was better - at least you had recursion with assembler. Basic has progressed much since you last looked at it, time to update your facts. Basic has recursion, it compiles to native code, it has objects, can be event driven and everything else you would expect of a language. Computing changes too fast to allow you to think you know it all. Keep up to date granddad. However what basic doesn't have is a portable language definition. -- http://mail.python.org/mailman/listinfo/python-list
Re: create lowercase strings in lists - was: (No subject)
I got the script working. Thanks for all your help everyone. Trouble is its not showing the correct results. Here is the script and results: #!/usr/bin/env python import os import sys import time import string import pexpect import commands from sets import Set as set # Test if the words of list2 elements appear in any order in list1 elements # disregarding case and parens # Reference list list1 = [a b C (D), D A B, A B E] # Test list list2 = [A B C D, A B D, A E F, A (E) B, A B, E A B ] def normalize(text, unwanted = (), table = string.maketrans(string.ascii_uppercase,string.ascii_lowercase)): text.translate(table,unwanted) return set(text.split()) reflist = [normalize(element) for element in list1] print reflist #This is the list of sets to test against def testmember(element): is element a member of the reflist, according to the above rules? testelement = normalize(element) #brute force comparison until match - depends on small reflist for el in reflist: if el.issuperset(testelement): return True return False for element in list2: print element, testmember(element) Here is the results: $ ./test.py [Set(['a', 'C', 'b', '(D)']), Set(['A', 'B', 'D']), Set(['A', 'B', 'E'])] A B C D False A B D True A E F False A (E) B False A B True E A B True The results should be: A B C D True A B D True A E F False A (E) B True A B False E A B True Michael Spencer [EMAIL PROTECTED] wrote: Steve Holden wrote: Mark Devine wrote: Actually what I want is element 'class-map match-all cmap1' from list 1 to match 'class-map cmap1 (match-all)' or 'class-map cmap1 mark match-all done' in list 2 but not to match 'class-map cmap1'. Each element in both lists have multiple words in them. If all the words of any element of the first list appear in any order within any element of the second list I want a match but if any of the words are missing then there is no match. There are far more elements in list 2 than in list 1. sounds like a case for sets... # NB Python 2.4 ... # Test if the words of list2 elements appear in any order in list1 elements # disregarding case and parens ... # Reference list list1 = [a b C (D), ... D A B, ... A B E] # Test list list2 = [A B C D, #True ... A B D, #True ... A E F, #False ... A (E) B,#True ... A B, #True ... E A B ] ... def normalize(text, unwanted = ()): ... conv = .join(char.lower() for char in text if char not in unwanted) ... return set(conv.split()) ... reflist = [normalize(element) for element in list1] print reflist ... [set(['a', 'c', 'b', 'd']), set(['a', 'b', 'd']), set(['a', 'b', 'e'])] This is the list of sets to test against def testmember(element): ... is element a member of the reflist, according to the above rules? ... testelement = normalize(element) ... #brute force comparison until match - depends on small reflist ... for el in reflist: ... if el.issuperset(testelement): ... return True ... return False ... for element in list2: ... print element, testmember(element) ... A B C D True A B D True A E F False A (E) B True A B True E A B True Michael -- http://mail.python.org/mailman/listinfo/python-list _ Sign up for eircom broadband now and get a free two month trial.* Phone 1850 73 00 73 or visit http://home.eircom.net/broadbandoffer -- http://mail.python.org/mailman/listinfo/python-list
Re: Step by step: Compiling extensions with MS Visual C++ Toolkit 2003 - msvccompiler-patch.txt (0/1)
[EMAIL PROTECTED] wrote: Having done steps 1 to 10, I tried building Numeric-23.6. And got the following error-msg: F:\install\Numeric-23.6python setup.py build running build running build_py running build_ext building '_numpy' extension D:\Programme\Microsoft Visual C++ Toolkit 2003\bin\cl.exe /c /nologo /Ox /MD /W3 /GX /DNDEBUG -I/usr/include/atlas -IInclude -IPackages\FFT\Include -IPackages\R NG\Include -ID:\Python24\include -ID:\Python24\PC /TcSrc\_numpymodule.c /Fobuild \temp.win32-2.4\Release\Src\_numpymodule.obj _numpymodule.c d:\Python24\include\pyconfig.h(30) : fatal error C1083: Cannot open include file : 'io.h': No such file or directory error: command 'D:\Programme\Microsoft Visual C++ Toolkit 2003\bin\cl.exe' fai led with exit status 2 why? Regards Wolfgang If you look at the instructions on : http://www.vrplumber.com/programming/mstoolkit/ It mentions that you probably need the .NET 2.0beta runtime and SDK. Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html -- http://mail.python.org/mailman/listinfo/python-list
Re: create lowercase strings in lists - was: (No subject)
If I use: if el.issubset(testelement): I get a closer anwser but the brackets cause a problem. They are optional in the test list so (D) in the test list is equal to D or (D) in the reference list. Mark Devine [EMAIL PROTECTED] wrote: I got the script working. Thanks for all your help everyone. Trouble is its not showing the correct results. Here is the script and results: #!/usr/bin/env python import os import sys import time import string import pexpect import commands from sets import Set as set # Test if the words of list2 elements appear in any order in list1 elements # disregarding case and parens # Reference list list1 = [a b C (D), D A B, A B E] # Test list list2 = [A B C D, A B D, A E F, A (E) B, A B, E A B ] def normalize(text, unwanted = (), table = string.maketrans(string.ascii_uppercase,string.ascii_lowercase)): text.translate(table,unwanted) return set(text.split()) reflist = [normalize(element) for element in list1] print reflist #This is the list of sets to test against def testmember(element): is element a member of the reflist, according to the above rules? testelement = normalize(element) #brute force comparison until match - depends on small reflist for el in reflist: if el.issuperset(testelement): return True return False for element in list2: print element, testmember(element) Here is the results: $ ./test.py [Set(['a', 'C', 'b', '(D)']), Set(['A', 'B', 'D']), Set(['A', 'B', 'E'])] A B C D False A B D True A E F False A (E) B False A B True E A B True The results should be: A B C D True A B D True A E F False A (E) B True A B False E A B True Michael Spencer [EMAIL PROTECTED] wrote: Steve Holden wrote: Mark Devine wrote: Actually what I want is element 'class-map match-all cmap1' from list 1 to match 'class-map cmap1 (match-all)' or 'class-map cmap1 mark match-all done' in list 2 but not to match 'class-map cmap1'. Each element in both lists have multiple words in them. If all the words of any element of the first list appear in any order within any element of the second list I want a match but if any of the words are missing then there is no match. There are far more elements in list 2 than in list 1. sounds like a case for sets... # NB Python 2.4 ... # Test if the words of list2 elements appear in any order in list1 elements # disregarding case and parens ... # Reference list list1 = [a b C (D), ... D A B, ... A B E] # Test list list2 = [A B C D, #True ... A B D, #True ... A E F, #False ... A (E) B,#True ... A B, #True ... E A B ] ... def normalize(text, unwanted = ()): ... conv = .join(char.lower() for char in text if char not in unwanted) ... return set(conv.split()) ... reflist = [normalize(element) for element in list1] print reflist ... [set(['a', 'c', 'b', 'd']), set(['a', 'b', 'd']), set(['a', 'b', 'e'])] This is the list of sets to test against def testmember(element): ... is element a member of the reflist, according to the above rules? ... testelement = normalize(element) ... #brute force comparison until match - depends on small reflist ... for el in reflist: ... if el.issuperset(testelement): ... return True ... return False ... for element in list2: ... print element, testmember(element) ... A B C D True A B D True A E F False A (E) B True A B True E A B True Michael -- http://mail.python.org/mailman/listinfo/python-list _ Sign up for eircom broadband now and get a free two month trial.* Phone 1850 73 00 73 or visit http://home.eircom.net/broadbandoffer -- http://mail.python.org/mailman/listinfo/python-list _ Sign up for eircom broadband now and get a free two month trial.* Phone 1850 73 00 73 or visit http://home.eircom.net/broadbandoffer -- http://mail.python.org/mailman/listinfo/python-list
setup.py - just what is it for ?
Hi - This is probably quite a stupid question but I've never understood what setup.py does. I've got a situation at the moment where I would like to use a script (which someone else has written and made available) to do CGI on a shared webserver to which I do not have shell access. The install instructions say run python setup.py but as far as I'm aware I cannot do that. There is only one script involved (except for the setup.py !) and so I'm probably just going to copy it into my cgi-bin and give it a go but I'd like to know for future reference just how bad could it be if I did this ? Are there circumstances where you must use setup.py to have any hope of the code working ? BTW here is the setup.py in question ... from distutils.core import setup classifiers = \ Development Status :: 5 - Production/Stable Environment :: Web Environment Intended Audience :: Developers License :: OSI Approved :: GNU General Public License (GPL) Operating System :: OS Independent Topic :: Internet :: WWW/HTTP Topic :: Internet :: WWW/HTTP :: Dynamic Content :: CGI Tools/Libraries import sys if sys.version_info (2, 3): _setup = setup def setup(**kwargs): if kwargs.has_key(classifiers): del kwargs[classifiers] _setup(**kwargs) setup(name=cgi_app,py_modules=[cgi_app], version=1.3, maintainer=Anders Pearson, maintainer_email=[EMAIL PROTECTED], url = http://thraxil.org/code/cgi_app/;, license = http://www.gnu.org/licenses/gpl.html;, platforms = [any], description = CGI and mod_python MVC application framework, long_description = framework for building MVC CGI and mod_python applications. based on the perl CGI::Application module but more pythonic., classifiers = filter(None, classifiers.split(\n))) ... I would appreciate any information about this (or any tips on how to deal with no shell access). thanks richard -- http://mail.python.org/mailman/listinfo/python-list
Re: create lowercase strings in lists - was: (No subject)
Mark Devine wrote: I got the script working. Thanks for all your help everyone. Trouble is its not showing the correct results. Here is the script and results: In my book it is not working then. def normalize(text, unwanted = (), table = string.maketrans(string.ascii_uppercase,string.ascii_lowercase)): text.translate(table,unwanted) Strings are immutable in Python. Make that text = text.translate(table, unwanted) This line of the script's output could have given you a clue: [Set(['a', 'C', 'b', '(D)']), Set(['A', 'B', 'D']), Set(['A', 'B', 'E'])] (I didn't look any further, so there may be other problems) Peter PS: Do us a favour and (a) don't top-post (b) use space not tabs in your source code (c) remove all text quoted from the parent that is not relevant to your current problem. -- http://mail.python.org/mailman/listinfo/python-list
Re: BASIC vs Python
Peter Hickman wrote: Mike Meyer wrote: BASIC as implented by Microsoft for the Apple II and the TRS 80 (among others) is simply the worst programming language I have ever encountered. Assembler was better - at least you had recursion with assembler. Basic has progressed much since you last looked at it, time to update your facts. Basic has recursion, it compiles to native code, it has objects, can be event driven and everything else you would expect of a language. Computing changes too fast to allow you to think you know it all. Keep up to date granddad. However what basic doesn't have is a portable language definition. May you could give us an idea of the current state of basic affairs then by translating the following example snippet: It's me wrote: I saw this code from an earlier post: lst1 = [ab, ac, ba, bb, bc] lst2 = [ac, ab, bd, cb, bb] dct1 = dict.fromkeys(lst1) print [x for x in lst1 if x not in dct1] print [x for x in lst1 if x in dct1] It's simply remarkable for somebody to be able to do it so cleanly (and so obviously) - out of the box, if you may. Sure, you can do it in Basic. Ur...sure? Yes, sure... Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: setup.py - just what is it for ?
Richard Shea wrote: Hi - This is probably quite a stupid question but I've never understood what setup.py does. I've got a situation at the moment where I would like to use a script (which someone else has written and made available) to do CGI on a shared webserver to which I do not have shell access. The install instructions say run python setup.py but as far as I'm aware I cannot do that. http://www.python.org/doc/current/inst/ There is only one script involved (except for the setup.py !) and so I'm probably just going to copy it into my cgi-bin and give it a go but I'd like to know for future reference just how bad could it be if I did this ? Are there circumstances where you must use setup.py to have any hope of the code working ? depends on the package, of course. e.g. a package that includes C extensions won't work if you don't compile the C extensions... /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Help need with converting Hex string to IEEE format float
Max M [EMAIL PROTECTED] wrote in news:41bf121e$0$280 [EMAIL PROTECTED]: ## st = '80 00 00 00' import binascii import struct s = ''.join([binascii.a2b_hex(s) for s in st.split()]) v = struct.unpack(f, s)[0] print v ## This one worked great for what I was trying to do. Thanks to everybody for your help. TTFN Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Why no list heritable type?
In article [EMAIL PROTECTED], Mike Meyer [EMAIL PROTECTED] wrote: And before Python 2.2 there was the UserList class in the standard library. Which is still there in 2.4. Shouldn't it be depreciated by this point? Apart from compatibility issues as mentioned in the UserList documentation, deriving from it will give you a classic class, whereas deriving from list will give you a new style class. There may be circumstances under which this is important (exercise left to more twisted minds than mine). Same applies to dict/UserDict. -- \S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/ ___ | Frankly I have no feelings towards penguins one way or the other \X/ |-- Arthur C. Clarke her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump -- http://mail.python.org/mailman/listinfo/python-list
Re: Efficient grep using Python?
Christos TZOTZIOY Georgiou wrote: On Thu, 16 Dec 2004 14:28:21 +, rumours say that [EMAIL PROTECTED] I challenge you to a benchmark :-) Well, the numbers I provided above are almost meaningless with such a small set (and they easily could be reverse, I just kept the convenient-to-me first run :). Do you really believe that sorting three files and then scanning their merged output counting duplicates is faster than scanning two files (and doing lookups during the second scan)? $ python Python 2.3.3 (#1, Aug 31 2004, 13:51:39) [GCC 3.3.3 (SuSE Linux)] on linux2 Type help, copyright, credits or license for more information. x=open('/usr/share/dict/words').readlines() len(x) 45378 import random random.shuffle(x) open(/tmp/A, w).writelines(x) random.shuffle(x) open(/tmp/B, w).writelines(x[:1000]) $ time sort A B B | uniq -u /dev/null real0m0.311s user0m0.315s sys 0m0.008s $ time grep -Fvf B A /dev/null real0m0.067s user0m0.064s sys 0m0.003s (Yes, I cheated by adding the F (for no regular expressions) flag :) Also you only have 1000 entries in B! Try it again with all entries in B also ;-) Remember the original poster had 100K entries! and finally destroys original line order (should it be important). true That's our final agreement :) Note the order is trivial to restore with a decorate-sort-undecorate idiom. -- Pádraig Brady - http://www.pixelbeat.org -- -- http://mail.python.org/mailman/listinfo/python-list
Re: pywhich script - where is that module?
Thomas Guettler wrote: [...] Nice, you could add it to the python cookbook. [...] Just in the case the OP doesn't know where to find the cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/ -- http://mail.python.org/mailman/listinfo/python-list
Re: BASIC vs Python
Gerhard Haering wrote: In VB6, it would an exercise of working around the limitations of the data structures. In MS Access I would probably end up with two database tables. The juxtaposition of incredibly polished and virtually unusable features is amazing. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: do you master list comprehensions?
Thought you might enjoy my super-small flatten function: (though google groups seems to be munging my whitespace today) def flatten(d): flatten([[[1,[2,3],[4,5]],6],[7]])==[1,2,3,4,5,6,7] return reduce(lambda a,b:a+b,[(type(x) in (list, tuple) \ and flatten(x) or [x]) for x in d]) -- http://mail.python.org/mailman/listinfo/python-list
Re: Efficient grep using Python?
The point is that when you have 100,000s of records, this grep becomes really slow? Any comments? Thats why I looked for python :) that would be grep -vf B A and it is a rare use of grep, indeed. -- TZOTZIOY, I speak England very best. Be strict when sending and tolerant when receiving. (from RFC1958) I really should keep that in mind when talking with people, actually... -- http://mail.python.org/mailman/listinfo/python-list
Re: setup.py - just what is it for ?
You could *try* writing a cgi which did something like os.spawnv('python', ['setup.py', 'install']) (or whatever would be right without looking up the docs)... You sometimes don't need admin rights to run setup.py I would be interested in the results. Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html -- http://mail.python.org/mailman/listinfo/python-list
Re: setup.py - just what is it for ?
You could *try* writing a cgi which did something like os.spawnv('python', ['setup.py', 'install']) (or whatever would be right without looking up the docs)... You sometimes don't need admin rights to run setup.py I would be interested in the results. Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Adding paths to sys.path permanently, and another problem...
Jeff Shannon wrote: Judging from this, I think that os.environ['USERPROFILE'] seems like it may do what you want, though os.environ['APPDATA'] might be useful as well. Of course, if you're trying to get something to work cross-platform, things may be more difficult -- but that's because Windows doesn't normally use ~ so its use is not supported very well. You may be able to create a $HOME that's equivalent to $USERPROFILE... Both problems solved! The .pth seems like the best solution for the first one, and for the expanduser(~) I just added a $HOME variable to the Environment variables of WinXP. Simple solutions. Thanks Jeff Amir -- http://mail.python.org/mailman/listinfo/python-list
Re: BASIC vs Python
Christos TZOTZIOY Georgiou [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] On Fri, 17 Dec 2004 01:43:56 -0600, rumours say that Mike Meyer [EMAIL PROTECTED] might have written: Assembler was better - at least you had recursion with assembler. You had recursion with BASIC --what you probably mean is that you had no stacked parameters (unless you imitated that with using an indexed array). 90 rem recursion 100 print beautiful colours 110 gosub 100 I think he means that you had no recursive function calls in BASIC. I suppose, to most of us, recursion doesn't mean doing things more than once, since by that definition, iteration is also recursion. Recursion generally means some type of self reference, like in functional languages, where the simplest recursion is base case/recurring step. BASIC didn't do this, without a bit of unsightly hackery. Then again, I don't believe that it was really a concern at the time, so I don't suppose its too important of an issue :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Performance (pystone) of python 2.4 lower then python 2.3 ???
Ok, here are my results, all python Versions supplied by Debian: [EMAIL PROTECTED]:~ python1.5 /usr/lib/python1.5/test/pystone.py Pystone(1.1) time for 1 passes = 1.33 This machine benchmarks at 7518.8 pystones/second [EMAIL PROTECTED]:~ python2.2 /usr/lib/python1.5/test/pystone.py Pystone(1.1) time for 1 passes = 1.03 This machine benchmarks at 9708.74 pystones/second [EMAIL PROTECTED]:~ python2.3 /usr/lib/python1.5/test/pystone.py Pystone(1.1) time for 1 passes = 0.73 This machine benchmarks at 13698.6 pystones/second [EMAIL PROTECTED]:~ python2.4 /usr/lib/python1.5/test/pystone.py Pystone(1.1) time for 1 passes = 0.66 This machine benchmarks at 15151.5 pystones/second Run on a Knoppix/Debian based Duron 700 (Sony PCG-FX201 laptop). I guess there must be differences in how your pythons got compiled, even if you didn't specifies explicitly options. Andreas Am Mo, den 13.12.2004 schrieb Lucas Hofman um 17:09: Hi, Just installed Python 2.4 on a machine (RH8.0 Linux) that also has python 2.3 and python 2.2 installed. The latter came with the linux distribution, the other are compiled from source tarballs. Comparing them gives the following unexpected result: [EMAIL PROTECTED] test]$ /usr/bin/python pystone.py Pystone(1.1) time for 5 passes = 1.86 This machine benchmarks at 26881.7 pystones/second [EMAIL PROTECTED] test]$ /usr/local/bin/python2.3 pystone.py Pystone(1.1) time for 5 passes = 1.22 This machine benchmarks at 40983.6 pystones/second This is ok, a 52% speed increase, but: [EMAIL PROTECTED] test]$ /usr/local/bin/python2.4 pystone.py Pystone(1.1) time for 5 passes = 1.31 This machine benchmarks at 38167.9 pystones/second A 7% speed DECREASE??? According to the documentation it should be a 5% increase? The machine is a 3.0 GHz Xeon box. Both python 2.3 and 2.4 where configure without any options. Anyone who understands what is going on? Regards, Lucas signature.asc Description: Dies ist ein digital signierter Nachrichtenteil -- http://mail.python.org/mailman/listinfo/python-list
decorator peculiarity
Hi, I just wrote my first decorator example - and I already love them. However I've encountered one peculiarity that strikes me odd: When one writes a decorated function like this: @decorate def foo(): pass the function decorate usually looks like this: def decorate(func): def _d(*args, **kwargs): do_something() # call func func(*args, **kwargs) return _d So the function decorator has to return a function that is bound to the name foo in the originating context (module or class) and gets the function passed as argument. But if I want my decorator to be parametrized, it looks like this: @decorate(arg) def foo(): pass def decorate(arg): def f(func): def _d(*args, **kwargs): do_something(arg) # call func func(*args, **kwargs) return _d So what happens is that an decorater with arguments is called with these, returns a callable that then is called with foo, and the result is stored under foo. Now why this layer of indirection? I would have supposed that things look like this: def decorate(func, arg): def _d(*args, **kwargs): do_something(arg) # call func func(*args, **kwargs) return _d A sideeffect of this behaviour is that for a fully keyword-argumentized function I still have to write parentheses: @decorate() def foo(): pass def decorate(arg=None): def f(func): def _d(*args, **kwargs): do_something(arg) # call func func(*args, **kwargs) return _d I don't mind the extra parentheses too much - it just made me wonder what the rationale behind this is. -- Regards, Diez B. Roggisch -- http://mail.python.org/mailman/listinfo/python-list
Re: create lowercase strings in lists - was: (No subject)
Mark Devine wrote: I got the script working. Thanks for all your help everyone. Trouble is its not showing the correct results. Here is the script and results: Well, that's a pretty unusual interpretation of the word working :-) [...] I see from later postings you are getting closer to an answer, but obviously you still have to strip out the characters that you don't want to affect the match (such as ( and )). regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 -- http://mail.python.org/mailman/listinfo/python-list
Re: Permission
The function is os.rename(old, new). If you actually tried 'os.raname' (as your post suggests) that is an illegal function. I suspect that you mistyped it in your post, but Peter's replys is correct. Always copy and paste your code and your traceback error message so it will be precise. Permisssion denied means that you don't have permission to rename this file. Normally this is a rights issue. BTW-os.rename works on XP. Larry Bates Syscon, Inc. -g00t©- wrote: --( oo )-- I don't know if there's a beginner board, just tell me if it's the place; I tried Python this weekend. I'm java coder and I was looking for handling names in os. I tried the os.raname('file.ext','nuFile.ext') and I got a Permission denied error. In the docs, it say that it should work only for UNIX, than it shouldn't work on XP (if I understood). I'm on XP, should I declare something to enable permission, or is it common error? Sorry about that newCommer question, but it would help, I'm on that problem for a while... --( oo )-- guillaumeLaBelle [alias goo©] - Architecture CAAO -- http://mail.python.org/mailman/listinfo/python-list
Re: Potential improvement on delegation via explicit calls and super
Am Fri, 17 Dec 2004 02:17:38 -0600 schrieb Robert Dick: Derived classes sometimes need to delegate portions of the work in overridden methods to methods in their base classes. This was traditionally done with explicit calls in python, e.g., class Base: def __init__(self): print 'base' class Left(Base): def __init__(self, arg): Base.__init__(self) print 'left' class Right(Base): def __init__(self, arg): Base.__init__(self) print 'right' If you can change the source of Base, I would do it like this: class Base: _init_done=0 def __init__(self): if self._init_done: return self._init_done=1 # ... do init Thomas -- Thomas Güttler, http://www.thomas-guettler.de/ -- http://mail.python.org/mailman/listinfo/python-list
Request for Help in OpenSourcing a Project
I love Python and started back when 1.52 was the popular version. Whilst learning Python, I created a website framework called [EMAIL PROTECTED], which I run at the following two sites : http://www.meeks.ca All content is done in [EMAIL PROTECTED] and static pages are created. http://www.programmedintegration.com All content is created dynamically. [EMAIL PROTECTED] is a mix between a CMS and web framework. I've been personally using it for more than 5 years, however it's never formally been completed and has a lot of rough edges. I created [EMAIL PROTECTED] to handle all data as straight text files, as my provider at the time, had no facilities for databases, so this is a definite area that [EMAIL PROTECTED] could be expanded. What I'm basically after is someone to assist in polishing up the product and ultimately releasing as OpenSource or some similar kind of license, whereby I retain copyright, but the use of the product is free. Also if anyone has any tips or advice, I'd be most grateful. I'm loathe to release the code at present, as it's really quite embarassing in places, and has a strong need for markup code to be removed from within program code and placed as separate files. Anyway if anyone is able to assist or advise, I'd be more than happy to discuss things futher. Regards Colin -- http://mail.python.org/mailman/listinfo/python-list
Re: BASIC vs Python
Richards Noah wrote: You had recursion with BASIC --what you probably mean is that you had no stacked parameters (unless you imitated that with using an indexed array). 90 rem recursion 100 print beautiful colours 110 gosub 100 I think he means that you had no recursive function calls in BASIC. I suppose, to most of us, recursion doesn't mean doing things more than once, since by that definition, iteration is also recursion. Recursion generally means some type of self reference Note that he uses gosub, not goto. The code block that starts at line 100 and ends at line 110 calls itself recursively. Works just fine in many (most?) BASIC implementations (at least until you run out of call stack). (the original BASIC was a different thing, though: quoting from the 1964 hand- book: the user must be very careful not to write a program in which GOSUB appars inside a subroutine which itself is entered via a GOSUB; it just won't work. The handbook also states that the program size is limited to two feet of teletype paper...) /F -- http://mail.python.org/mailman/listinfo/python-list
Dr. Dobb's Python-URL! - weekly Python news and links (Dec 15)
QOTW: [Python demands more thought in optimization, because i]n other languages, by the time you get the bloody thing working it's time to ship, and you don't have to bother worrying about making it optimal. -- Simon Brunning One of the best features of c.l.py is how questions phrased in the most ambiguous terms are often slowly elaborated into meaningful enquiries. -- Steve Holden Martin Bless summarizes in an extremely valuable post what you need to know to generate Python-related executable binaries targeted for Windows*. http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/73f29284d1e031c7/ John Hunter, Fredrik Lundh, Pádraig Brad, and Tim Peters work out in public on a model problem of textual analysis. http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/b009627e9a5abc64/7d75f531ba8a7fe2 Amidst the usual combination of heat and light (in this case, on commercial acceptance and applicability of OO), Mike Meyer narrates from his own experience an example of how good object orientation can be. http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/16590f4138b6a978/ gDesklets are attention-grabbing Py-scriptable desktop decorations. http://gdesklets.gnomedesktop.org/index.php Sure, a list comprehension can comprise multiple for-s. http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/ee5f7f8c227b22ff/ Mac OS X makes for highly-desired (at least by some) development hosts; moreover there are three killer features in MacPython that you can't get anywhere else ... http://mail.python.org/pipermail/pythonmac-sig/2004-December/012298.html Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djqas_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Business Forum further[s] the interests of companies that base their business on ... Python. http://www.python-in-business.org Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=pythonShowStatus=all The old Python To-Do List now lives principally in a SourceForge reincarnation.
Re: Cool object trick
Fredrik Lundh wrote: Steve Holden wrote: Certainly makes writing 'print obj.spam, obj.spam, obj.eggs, obj.bacon, obj.sausages, and, obj.spam' a lot easier ;-) Of course this whole thing of substituting attribute access for dictionary keys only works as long as the keys are strings with the same syntax as Python identifiers, so one shouldn't go completely overboard. unless you're willing to use getattr() for thos oddball cases, of course. Of course. class Dummy: ... pass ... x = Dummy() setattr(x, spamegg, hello) getattr(x, spamegg) 'hello' x.spamegg Traceback (most recent call last): File stdin, line 1, in ? AttributeError: Dummy instance has no attribute 'spam' but seriously, turning container elements into attributes should only be done if it makes sense from a design perspective. (and vice versa; you shouldn't use a dictionary if an object would make more sense -- but attribute abuse is a lot more common) Really we are talking about the outer limits here. Anyone preferring setattr(x, spamegg, hello) to x[spamegg] = hello when it isn't necessary clearly doesn't share our two principal attributes: an elegant sense of design, fine knowledge of Python and an inherent modesty. Sorry: out *three* principal attributes. Bugger, I'll come in again. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 -- http://mail.python.org/mailman/listinfo/python-list
Re: BASIC vs Python
Steve Holden wrote: Adam DePrince wrote: On Thu, 2004-12-16 at 13:36, abisofile wrote: hi I'm new to programming.I've try a little BASIC so I want ask since Python is also interpreted lang if it's similar to BASIC. Nobody is answering this question because they are shuddering in fear and revulsion. During the 1980's BASIC was the language to embedd into the ROM's of the computers of the day. This was in a misguided effort to make computers understandable to their target audience. The goal of the day was to build a system that a manager would want to buy; it was believed that the only way for a manager to see the value of a system was to make the language understandable to said manager. The expectation, of course, that the manager would sit down and play with the computer instead of delegating the tasks to somebody more qualified is somewhat misguided in hindsight. To do that, a language that closely resembled the process of micromanaging an untrained worker was employed. But that language was COBOL, not BASIC. BASIC is actually an acronym for Beginners' All-purpose Symbolic Instruction Code, which the initial implementations at Dartmouth weren't, really. The big innovation was the use of line-numbering to allow interactive editing and testing of a program. Which, now I remember, Digital Equipment extended to floating-point in their FOCAL language. I never did discover whether the number of insertions required was limited by the floating-point precision, but Focal was unique in my experience in allowing insertion of statement 1.5 between statements 1 and 2. (mumbles into beard and drools quietly in the corner). talking-to-myself-again-ly y'rs - steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 -- http://mail.python.org/mailman/listinfo/python-list
Re: Email filters in python
On Fri, 17 Dec 2004 15:07:26 GMT, sf [EMAIL PROTECTED] wrote: Would someome like to post their email filters code. Its so common that probably some standard library supports it or many would have written it already. If I have basic structure, I can take from there. http://spambayes.sourceforge.net/ -- Cheers, Simon B, [EMAIL PROTECTED], http://www.brunningonline.net/simon/blog/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Time Difference
GMane Python [EMAIL PROTECTED] wrote: I was wondering if there is an existing function that would let me determine the difference in time. To explain: Upon starting a program: startup = time.time() After some very long processing: now = time.time() print days hours minutes seconds, now - startup So, to print in a formatted way (D-H-M-S) the difference in time of startup and now. now - startup gives you the difference in seconds; turning that into (days, hours, minutes, seconds) isn't that hard (hint: lookup the divmod function in the manual). or you could use the datetime module: from datetime import datetime startup = datetime.today() now = datetime.today() print now - startup 0:00:06.625000 (see the library reference for details). /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Email filters in python
.. - open POP-SSL connection to pop.someserver.com - Get all mails and store as Unix mail file (mymails) - do not delete mails from server - close connection. .. - open mymails file - Do following for each mail in mymails file (one by one) { - get header fields: {FROM, TO, CC, Subject,... more ... } - some conditons (FROM is found my addresslist.txt but not part of my rejectlist.txt ) append that mail to some existing file. } For these two, use fetchmail and procmail. .. - open SMTP-TLS connection to smtp.someserver.com - send all mails in my unix mail file - close connection I'm not totally sure how to do this best - but here python might indeed help, using smtplib and mailbox. -- Regards, Diez B. Roggisch -- http://mail.python.org/mailman/listinfo/python-list
Re: Efficient grep using Python?
On Fri, 17 Dec 2004 14:22:34 +, rumours say that [EMAIL PROTECTED] might have written: sf: sf wrote: The point is that when you have 100,000s of records, this grep becomes really slow? There are performance bugs with current versions of grep and multibyte characters that are only getting addressed now. To work around these do `export LANG=C` first. You also should use the -F flag that Pádraig suggests, since you don't have regular expressions in the B file. In my experience grep is not scalable since it's O(n^2). See below (note A and B are randomized versions of /usr/share/dict/words (and therefore worst case for the sort method)). $ wc -l A B 45427 A 45427 B $ export LANG=C $ time grep -Fvf B A real0m0.437s $ time sort A B B | uniq -u real0m0.262s $ rpm -q grep coreutils grep-2.5.1-16.1 coreutils-4.5.3-19 sf, you better do your own benchmarks (there is quick, sample code in other posts of mine and Pádraig's) on your machine, since on my test machine the numbers are reversed re to these of Pádraig's (grep takes half the time). package versions (on SuSE 9.1 64-bit): $ rpm -q grep coreutils grep-2.5.1-427 coreutils-5.2.1-21 language: $ echo $LANG en_US.UTF-8 Caution: both solutions are interexchangeable as long as you don't have duplicate lines in the A file. If you do, use the grep version. -- TZOTZIOY, I speak England very best. Be strict when sending and tolerant when receiving. (from RFC1958) I really should keep that in mind when talking with people, actually... -- http://mail.python.org/mailman/listinfo/python-list
Re: [OT] Python IDE
Fuzzyman [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Dan Perl wrote: Mike Meyer [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Dan Perl [EMAIL PROTECTED] writes: Mike Meyer [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] A: What's the most obnoxious thing on Usenet? Q: topposting. What is Jeopardy, Alex? You got your QA mixed up. No, the QA in that order demonstrate what's wrong with top posting. mike -- Mike Meyer [EMAIL PROTECTED] http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. Yeah, you're right. . If it's a short reply to a long post - in context - top posting is often *significantly * less annoying.. Isn't there a quote that includes 'hobgobline of little minds'.. Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html That was my point. I was being sarcastic again but I didn't put a warning anymore. As I'm doing now, still posting at the bottom of a long posting. I'm not sure whether you were attacking me too (am I the little mind?) or supporting me, Fuzzy. Anyway, I think that Mike Meyer was more annoyed by my jab at US politics than by my top posting. But it was safer for him to pick on the latter. Dan -- http://mail.python.org/mailman/listinfo/python-list
Fwd: Re: create lowercase strings in lists - was: (No subject)
I got this working now. Thanks everybody for your help. _ Sign up for eircom broadband now and get a free two month trial.* Phone 1850 73 00 73 or visit http://home.eircom.net/broadbandoffer ---BeginMessage--- Happy to help. Pass it on. regards Steve Mark Devine wrote: I got it working correctly now thanks. I was on the right track it was a subset not a superset that was required in the end and all has worked out fine for me. Thank you for all your help Steve Holden [EMAIL PROTECTED] wrote: Mark Devine wrote: I got the script working. Thanks for all your help everyone. Trouble is its not showing the correct results. Here is the script and results: Well, that's a pretty unusual interpretation of the word working :-) [...] I see from later postings you are getting closer to an answer, but obviously you still have to strip out the characters that you don't want to affect the match (such as ( and )). regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 _ Sign up for eircom broadband now and get a free two month trial.* Phone 1850 73 00 73 or visit http://home.eircom.net/broadbandoffer -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 ---End Message--- -- http://mail.python.org/mailman/listinfo/python-list
RE: Cool object trick
Alex Stapleton wrote: you can't do var = varA obj = struct(varA = Hello) print obj.var and expect it to say Hello to you. Did you mean print obj.varA? I can't think of any use case for the way you wrote it, so I'm naively guessing you've got a typo. Feel free to correct me. ;) class struct(object): ... def __init__(self, **kwargs): ... self.__dict__.update(kwargs) ... var = varA obj = struct(**{str(var): Hello}) print obj.varA Hello Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: ftp
That's a good idea. Thanks! :-) -- http://mail.python.org/mailman/listinfo/python-list
Troubleshooting: re.finditer() creates object even when no match found
Hello, I really like the finditer() method of the re module. I'm having difficulty at the moment, however, because finditer() still creates a callable-iterator oject, even when no match is found. This is undesirable in cases where I would like to circumvent execution of code meant to parse out data from my finditer() object. I know that if I place a finditer() object in an iterative for loop, the loop will not execute, but is there some way I can test to see if the object contains no matches in the first place? I thought about using .next() but I don't want to lose the ability to process the first (sometimes only) match in the finditer() object. Thanks in advance, Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython question
André wrote: I needed to scale the image down to 16 by 16 on my Windows computer to make it work. Hello André, # I actually ran this code ;) import wx app = wx.PySimpleApp() class myframe(wx.Frame): def __init__(self): wx.Frame.__init__(self,None,-1,Icon Frame, size=(100,100),pos=(-1,-1)) frame = myframe() wx.InitAllImageHandlers() # this image is 32*32 on my computer image = wx.Image('c:/Python22/pycon.ico', wx.BITMAP_TYPE_ANY) image = image.ConvertToBitmap() icon = wx.EmptyIcon() icon.CopyFromBitmap(image) frame.SetIcon(icon) frame.Show() app.MainLoop() This works fine for me I am on windows 2000, and pycon.py is 32*32*24 Wonder why you had to resize? On another note, be sure to check out the tools dir in either the wxpython dir or wx dir it has a script called img2py.py. img2py.py -- Convert an image to PNG format and embed it in a Python module with appropriate code so it can be loaded into a program at runtime. The benefit is that since it is Python source code it can be delivered as a .pyc or 'compiled' into the program using freeze, py2exe, etc. Be sure to use the -i flag so it will convert it to a wxIcon Once you convert your icon to source using img2py.py you can do this: import Icon ICON = Icon.getIcon() frame.SetIcon(ICON) Hth, M.E.Farmer -- http://mail.python.org/mailman/listinfo/python-list
A completely silly question
This must be the silliest question ever: What about user input in Python? (like stdin) Where can I find it? I can't find any references to it in the documentation. Amir -- http://mail.python.org/mailman/listinfo/python-list
Re: A completely silly question
On Friday 17 December 2004 16:40, Amir Dekel wrote: This must be the silliest question ever: What about user input in Python? (like stdin) Where can I find it? I can't find any references to it in the documentation. See sys.stdin Cheers, Frans -- http://mail.python.org/mailman/listinfo/python-list
RE: A completely silly question
Title: RE: A completely silly question [Amir Dekel] #- What about user input in Python? (like stdin) #- Where can I find it? I can't find any references to it in #- the documentation. sys.stdin http://docs.python.org/lib/module-sys.html . Facundo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La información contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener información confidencial o propietaria, cuya divulgación es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no está autorizado a divulgar, copiar, distribuir o retener información (o parte de ella) contenida en este mensaje. Por favor notifíquenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magnético) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telefónica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electrónicos pueden ser alterados, motivo por el cual Telefónica Comunicaciones Personales S.A. no aceptará ninguna obligación cualquiera sea el resultante de este mensaje. Muchas Gracias. -- http://mail.python.org/mailman/listinfo/python-list
Re: A completely silly question
Amir Dekel wrote: This must be the silliest question ever: What about user input in Python? (like stdin) Where can I find it? I can't find any references to it in the documentation. Amir Simple, Simple, Simple: Var = raw_input(Some prompting text here: ) -- Harlin Seritt -- http://mail.python.org/mailman/listinfo/python-list
Re: Cool object trick
Robert Brewer wrote: Alex Stapleton wrote: you can't do var = varA obj = struct(varA = Hello) print obj.var and expect it to say Hello to you. Did you mean print obj.varA? I believe he meant that he wanted the equivalent of: getattr(obj, var) Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: BASIC vs Python
Gregor Horvath [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] It's me wrote: Absolutely *ugly*! But still, your point is well taken. Thank you for pointing this out. Adam was right: Don't do it, unless your goal is simply to embarrass and insult programmers. OK. Then please schow me, how you can create a complex form with grids, explorer like trees etc. in 2 minutes in standard python. Or make any given standard python object accessible from MS Excel in 2 minutes. -- Greg I thought we are talking about the language, are we not? -- It's me -- http://mail.python.org/mailman/listinfo/python-list
Re: lies about OOP
In article [EMAIL PROTECTED], Peter Hansen [EMAIL PROTECTED] wrote: P.S.: I'm only half Danish, but the other half is from a particularly bloodthirsty line of Canadians. Oh, you're part Quebecois? -- Aahz ([EMAIL PROTECTED]) * http://www.pythoncraft.com/ 19. A language that doesn't affect the way you think about programming, is not worth knowing. --Alan Perlis -- http://mail.python.org/mailman/listinfo/python-list
deprecate UserList? (WAS: Why no list heritable type?)
Sion Arrowsmith wrote: In article [EMAIL PROTECTED], Mike Meyer [EMAIL PROTECTED] wrote: And before Python 2.2 there was the UserList class in the standard library. Which is still there in 2.4. Shouldn't it be depreciated by this point? Apart from compatibility issues as mentioned in the UserList documentation, deriving from it will give you a classic class, whereas deriving from list will give you a new style class. There may be circumstances under which this is important (exercise left to more twisted minds than mine). Same applies to dict/UserDict. Classic classes will eventually disappear: http://www.python.org/doc/2.2.3/whatsnew/sect-rellinks.html#SECTION00031 GvR also encourages people to use new-style classes for everything: http://mail.python.org/pipermail/python-dev/2002-March/021817.html Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: Python RSS aggregator?
Erik Max Francis wrote: I've checked and all the feeds _I_ care about :-) are available in RSS now, so it would make sense to move to an RSS aggregator if it has the same features. I've looked around at some that are available, both in Python and not, and haven't found anything that had the feature set I want. One in Python would obviously be a huge benefit. http://www.nongnu.org/straw/ would be a great place to start, even if it doesn't have all of your desired features. Cheers, Evan @ 4-am -- http://mail.python.org/mailman/listinfo/python-list
Re: BASIC vs Python
Christos TZOTZIOY Georgiou [EMAIL PROTECTED] writes: On Fri, 17 Dec 2004 01:43:56 -0600, rumours say that Mike Meyer [EMAIL PROTECTED] might have written: Assembler was better - at least you had recursion with assembler. You had recursion with BASIC --what you probably mean is that you had no stacked parameters (unless you imitated that with using an indexed array). Quite right. My bad. mike -- Mike Meyer [EMAIL PROTECTED] http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python mascot proposal
EP [EMAIL PROTECTED] writes: (what is the mascot for C++?) I can't seem to find a goatse link... (But I didn't try very hard.) Nick -- # sigmask || 0.2 || 20030107 || public domain || feed this to a python print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?') -- http://mail.python.org/mailman/listinfo/python-list
Re: Request for Help in OpenSourcing a Project
www.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Re: A completely silly question
Harlin Seritt wrote: Simple, Simple, Simple: Var = raw_input(Some prompting text here: ) Frans Englich wrote: See sys.stdin What I need from the program is to wait for a single character input, something like while(getchar()) in C. All those Python modules don't make much sence to me... Amir -- http://mail.python.org/mailman/listinfo/python-list
Re: A completely silly question
Amir Dekel wrote: What I need from the program is to wait for a single character input, something like while(getchar()) in C. All those Python modules don't make much sence to me... sys.stdin.read(1) but if you're having trouble reading the module documentation, maybe you could elaborate on what's giving you trouble. The answer to 99% of questions on this list is in the documentation somewhere, so if you don't know how to read it, you're going to have trouble with Python. Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: Time Difference
GMane Python wrote: Hello I was wondering if there is an existing function that would let me determine the difference in time. To explain: Upon starting a program: startup = time.time() After some very long processing: now = time.time() print days hours minutes seconds, now - startup So, to print in a formatted way (D-H-M-S) the difference in time of startup and now. from datetime import datetime startTime = datetime.now() # processing endTime = datetime.now() print 'elapsed', endTime - startTime elapsed 0:00:09.063000 -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: BASIC vs Python
On Fri, 2004-12-17 at 10:14, Steve Holden wrote: Nobody is answering this question because they are shuddering in fear and revulsion. During the 1980's BASIC was the language to embedd into the ROM's of the computers of the day. This was in a misguided effort to make computers understandable to their target audience. The goal of the day was to build a system that a manager would want to buy; it was believed that the only way for a manager to see the value of a system was to make the language understandable to said manager. The expectation, of course, that the manager would sit down and play with the computer instead of delegating the tasks to somebody more qualified is somewhat misguided in hindsight. To do that, a language that closely resembled the process of micromanaging an untrained worker was employed. But that language was COBOL, not BASIC. BASIC is actually an acronym for It was a common theme and more than one language embraced it. The PET 20 wasn't exactly going to run COBOL any time soon. To be fair, COBOL resembled the micromanaging of a well trained worker, an accountant or actuary perhaps. Notice that today every white collar employee that can afford to keep the heat running in their office during the winter fantasizes their operation as being enterprise class? The same was true 20 years ago - but it was the mere presence of the computer that served a similar role. If you were really enterprise class, you used COBOL. And if you were in the wannabe category, you got yourself a PET 20 and told it what to do in BASIC. (mumbles into beard and drools quietly in the corner). Adam DePrince -- http://mail.python.org/mailman/listinfo/python-list
Re: A completely silly question
Amir Dekel wrote: What I need from the program is to wait for a single character input, something like while(getchar()) in C. Try the msvcrt module if you are on Windows. If you are not, remember to specify your platform next time you ask a question... All those Python modules don't make much sence to me... That's going to make it hard to program in Python, I suspect. Maybe it would be helpful to run through the tutorial, or spend more time reading the docs. -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Create linear spaced vector?
On Fri, 2004-12-17 at 13:39, kjm wrote: Hi Everyone, I am trying to port some old MatLab code to python, and am stuck on how to accomplish something. I am trying to write a generalized function that will create a linearly spaced vector, given the start and end point, and the number of entries wanted. In MatLab I have this function that I wrote: [code] function out = linearspace(x1,x2,n) out = [x1+ (0:n-2)*(x2 - x1)/(floor(n)-1) x2]; return [/code] I have the numeric package, numarray installed, and I think it should be accomplished easily, but I just can't seem to get the syntax correct with python. Any tips would be greatly appreciated. Thanks Is this want you want? #!/usr/bin/python def linear_space( start, end, count ): Returns a vector containing count evently spaced intervals (count + 1 evenly spaced points) delta = (end-start) / float(count) return [start,] + \ map( lambda x:delta*x + start, range( 1, count ) ) + [end, ] if __name__ == __main__: print linear_space( 1.0, 2.0, 10 ) Running it gives you: [1.0, 1.1001, 1.2, 1.3, 1.3999, 1.5, 1.6001, 1.7002, 1.8, 1.8999, 2.0] Adam DePrince -- http://mail.python.org/mailman/listinfo/python-list
Re: Why are tuples immutable?
Antoon Pardon wrote: Op 2004-12-17, Jeff Shannon schreef [EMAIL PROTECTED]: To take another approach -- given some function that allows lists to (pretend to be) hashable: . key = [1,2] . d[key] = 'foo' . d[[1,2]] . key.append(3) . d[key] ??? . As I understand it, it is impossible for there to be a hash function for which both of these cases can return the same object. How about: hash = id If hash equals id, then the first of those cases fails. I'm creating a new list with the same value but different. If hash *doesn't* equal id, then the second case fails. It's an either-or proposition; you *cannot* have both with mutable objects. And the proper definition of a hash requires that you have both. Now, even if hash were made to equal id... suppose I then pass that dict to a function, and I want to get the value that I've stored under [1,2]. In order to do that, I'd *also* have to pass in the *exact* list that I used as the key, because *only* that *exact* instance will hash correctly. Not only that, but if I've got a handful of such values that I want to retrieve, I'll have to pass in *all* of the lists that I used to key the dict. Any time I want to use the dict elsewhere, I need to pass not only the dict itself, but a list of keys to the dict. And then I need to know the order of the keys in that list. Ugh. I suppose I could just use keys() to get a complete list of keys from the dict itself. But still, I'd have to iterate over keys() to try to find the proper list that matches the value that I need, and then use the key to reference the dict. That leaves me with code like this: def process_dict(d): for key in d.keys(): if key == [1,2]: value1 = d[key] if key == [1,3]: value2 = d[key] if key == [2,2]: # and so on Double ugh. You also make the fault that because people ask for the possibility of keys being mutable objects, that they want to mutate those object while being a key. If mutable objects can be used as dict keys, then dicts *must* be able to sensibly handle the keys being mutated underneath of them, because it *will* happen. Your assumption that it's okay to make keys mutable, just tell programmers not to do it, is along the same lines as assuming that memory leaks in C aren't a problem because you've told programmers to free() all of the memory that they malloc()'d. In order to maintain the logical consistency that if an object is used as a dict key, that same object should reasonably be expected to retrieve the same value, identity-based hashes are necessary. As a result, the first option must be disallowed. Then why don't we disallow lists of mutable objects to be sorted or to be made into a heap. In fact each time we have a structure that relies on some invariant among its members we should disallow mutable members because with mutable members the invariant can be violated without ever rebinding one of the elements. If we have an object that, *by definition*, has some invariant that can be violated by having mutable members, then sure. But lists aren't sorted or heaped by definition. Note also that, if a list becomes unsorted or unheaped, it's fairly easy to resort or re-heapify the list. It may take some time, but nothing is lost. If a dictionary key mutates, then data *is* lost. In either case, if it's ever possible for equality to change while identity doesn't, then somewhere along the lines one of the core requirements, the contract if you will, of a dictionary *must* be broken. And while it may be possible to get away with breaking that contract some of the time (by postulating, for example, that if one mutates a dict key then things will break), this will result in more bugs and more confusion over time. There is no way for Python to be able to behave consistently in the face of mutable dict keys, therefore (In the face of ambiguity, refuse the temptation to guess.) Python declines the temptation of making it trivial to use mutable objects as dict keys. As it turns out, python makes no difference in difficulty for making either mutable or immutable objects usable as dictionary keys. The only difference is that python only made its standard immutable types hashable and not its standard mutable objects. No -- the mathematical definition of 'hashable' fails for mutable types, and Python doesn't try to pretend that it can hash mutable types. Python also provides features so that user-defined immutable types can be hashed properly, and those features can be abused to pretend to hash user-defined mutable types, but that's not the same as saying that Python is happy with mutable dictionary keys. (One can abuse __add__() to do all sorts of things other addition, too, but it would still be a stretch to say that Python supports using + to do multiplication, it just doesn't provide it on
Re: [OT] Python IDE
Q: What's the second most annoying thing to do on Usenet? A: Fail to properly trim quotes. Dan Perl [EMAIL PROTECTED] writes: Fuzzyman [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Dan Perl wrote: Mike Meyer [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Dan Perl [EMAIL PROTECTED] writes: Mike Meyer [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] A: What's the most obnoxious thing on Usenet? Q: topposting. What is Jeopardy, Alex? You got your QA mixed up. No, the QA in that order demonstrate what's wrong with top posting. Yeah, you're right. If it's a short reply to a long post - in context - top posting is often *significantly * less annoying.. When replying to a long post, you should trim the post to the relevant parts. This goes a long way towards solving that problem. Even if the relevant parts are rather long, it's still better to not top post, because that'll leave things out of order for replies. I'm not sure whether you were attacking me too (am I the little mind?) or supporting me, Fuzzy. Anyway, I think that Mike Meyer was more annoyed by my jab at US politics than by my top posting. But it was safer for him to pick on the latter. You're wrong. I don't even remember seeing any comment about american politics in your post. mike -- Mike Meyer [EMAIL PROTECTED] http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why no list heritable type?
Jeff Shannon [EMAIL PROTECTED] writes: Sion Arrowsmith wrote: Additionally, as I understand it UserList and UserDict are implemented entirely in Python, which means that there can be significant performance differences as well. Actually, UserList and UserDict are just wrappers around the builtin types. So the performance hit is one Python function call - pretty much neglible. But new code should still subclass the builtins. mike -- Mike Meyer [EMAIL PROTECTED] http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: Create linear spaced vector?
Thanks for the code snippets guys. Exactly what I needed to get going. I knew I could get the solution from matplotlib, but getting it installed using Fink (OS X) has been giving me a headache, so I thought I could just write my own function for now to get a small piece of code written The help is greatly appreciated. kjm John Hunter wrote: kjm == kjm [EMAIL PROTECTED] writes: kjm Hi Everyone, I am trying to port some old MatLab code to kjm python, and am stuck on how to accomplish something. kjm I am trying to write a generalized function that will create kjm a linearly spaced vector, given the start and end point, and kjm the number of entries wanted. kjm In MatLab I have this function that I wrote: kjm [code] kjm function out = linearspace(x1,x2,n) in matlab the builtin function to accomplish this is linspace The python package matplotlib defines a host of matlab compatible functions, including linspace def linspace(xmin, xmax, N): if N==1: return xmax dx = (xmax-xmin)/(N-1) return xmin + dx*arange(N) Note that matplotlib extends the Numeric/numarray core of matlab compatible functions (defined in MLab) to include plotting functions http://matplotlib.sourceforge.net A listing of matlab compatible functions is provided at http://matplotlib.sourceforge.net/matplotlib.pylab.html JDH -- http://mail.python.org/mailman/listinfo/python-list
Re: BASIC vs Python
Peter Otten wrote: Peter Hickman wrote: Mike Meyer wrote: BASIC as implented by Microsoft for the Apple II and the TRS 80 (among others) is simply the worst programming language I have ever encountered. Assembler was better - at least you had recursion with assembler. Basic has progressed much since you last looked at it, time to update your facts. Basic has recursion, it compiles to native code, it has objects, can be event driven and everything else you would expect of a language. Computing changes too fast to allow you to think you know it all. Keep up to date granddad. However what basic doesn't have is a portable language definition. May you could give us an idea of the current state of basic affairs then by translating the following example snippet: It's me wrote: I saw this code from an earlier post: lst1 = [ab, ac, ba, bb, bc] lst2 = [ac, ab, bd, cb, bb] dct1 = dict.fromkeys(lst1) # -- I'll assume lst2 was intended. print [x for x in lst1 if x not in dct1] print [x for x in lst1 if x in dct1] It's simply remarkable for somebody to be able to do it so cleanly (and so obviously) - out of the box, if you may. Sure, you can do it in Basic. Ur...sure? Yes, sure... In Microsoft QBasic (1987), this could be written as: DECLARE FUNCTION INARRAY% (ARR() AS STRING, X AS STRING) DIM LST1(4) AS STRING DIM LST2(4) AS STRING DIM I AS INTEGER FOR I = 0 TO UBOUND(LST1) READ LST1(I) NEXT FOR I = 0 TO UBOUND(LST2) READ LST2(I) NEXT ' Print the elements of LST1 that are NOT in LST2 FOR I = 0 TO UBOUND(LST1) IF INARRAY(LST2(), LST1(I)) = 0 THEN PRINT LST1(I); ; NEXT PRINT ' Print the elements of LST1 that are in LST2 FOR I = 0 TO UBOUND(LST1) IF INARRAY(LST2(), LST1(I)) = 1 THEN PRINT LST1(I); ; NEXT PRINT ' Elements of LST1 DATA AB, AC, BA, BB, BC ' Elements of LST2 DATA AC, AB, BD, CB, BB FUNCTION INARRAY% (ARR() AS STRING, X AS STRING) ' Return 1 if X in ARR, 0 otherwise DIM I AS INTEGER FOR I = LBOUND(ARR) TO UBOUND(ARR) IF X = ARR(I) THEN INARRAY = 1 EXIT FUNCTION END IF NEXT INARRAY = 0 END FUNCTION -- http://mail.python.org/mailman/listinfo/python-list
Re: BASIC vs Python
Adam DePrince [EMAIL PROTECTED] writes: On Fri, 2004-12-17 at 12:52, Mike Meyer wrote: Peter Hickman [EMAIL PROTECTED] writes: Basic has progressed much since you last looked at it, time to update your facts. Basic has recursion, it compiles to native code, it has objects, can be event driven and everything else you would expect of a language. What you describe isn't everything that I'd expect of a language. Again, this is what I meant when I suggested that making basic your native language limits your horizon. 1. First class functions 2. Full functional programming support ala Standard ML 3. Portability 4. Elegance Oddly enough, my second most favorite language (after Python) is Eiffel. No first class functions. They do have a first-class function-like object called an agent. But to use a standard method as an agent, you have to wrap it. Portability for the compiler I use is probably better than Python, as they try very hard to stick to ANSI C, and not use Posix features. Elegance - definitely more elegant than Python. There's a sound, logical reason for every feature of the language, and the reasoning is to help build robust, reliable code. The problem is, the only compiler that runs in my environment to date is missing most of the OS interfaces needed to do serious work. And the garbage collector sucks rocks. It's still a joy to write small programs in, but I can't use it for real work. Lastly, Mike, please refrain from argumentum ad hominem. You never know where life will bring you. Wouldn't it suck to find your dream job, only to meet Granddad at the interview? The attributions got screwed up. I'm Mike - and I didn't call anyone granddad, I was called granddad. My oldest is a bit young to have kids yet. mike -- Mike Meyer [EMAIL PROTECTED] http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: A completely silly question
Steven Bethard [EMAIL PROTECTED] writes: Amir Dekel wrote: What I need from the program is to wait for a single character input, something like while(getchar()) in C. All those Python modules don't make much sence to me... sys.stdin.read(1) That doesn't do what he wants, because it doesn't return until you hit a newline. The answer is system dependent. Or you can use massive overkill and get curses, but if you're on windows you'll have to use a third party curses package, and maybe wrap it -- Mike Meyer [EMAIL PROTECTED] http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
better lambda support in the future?
I'm wondering why python still has limited lambda support. What's stopping the developers of python to support more lisp-like lambda function? -- http://mail.python.org/mailman/listinfo/python-list
Re: A completely silly question
Amir Dekel wrote: Harlin Seritt wrote: Simple, Simple, Simple: Var = raw_input(Some prompting text here: ) Frans Englich wrote: See sys.stdin What I need from the program is to wait for a single character input, something like while(getchar()) in C. All those Python modules don't make much sence to me... Amir Amir, import tkSimpleDialog ch = tkSimpleDialog.askstring(,ch?) wes -- http://mail.python.org/mailman/listinfo/python-list
Re: A completely silly question
Amir Dekel wrote: What I need from the program is to wait for a single character input, something like while(getchar()) in C. All those Python modules don't make much sence to me... Take a look at Alan Gauld's Learning to Program (http://www.freenetpages.co.uk/hp/alan.gauld/) in the section Event Driven programming Hope it helps Marco -- http://mail.python.org/mailman/listinfo/python-list
Re: A completely silly question
Mike Meyer wrote: That doesn't do what he wants, because it doesn't return until you hit a newline. Are you sure that's not just an artifact of how your terminal buffers data for sys.stdin? $ cat temp.py import sys char = sys.stdin.read(1) while char: print char char = sys.stdin.read(1) $ cat temp.txt abc def $ python temp.py temp.txt a b c d e f Of course if the intent is to have this work with terminal input, then yes, sys.stdin.read(1) is probably not going to do the right thing... Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: better lambda support in the future?
Lambda functions will become obsolette in the nearest future. This is the PLAN. -- http://mail.python.org/mailman/listinfo/python-list
Re: BASIC vs Python
Adam DePrince wrote: Given the hardware constraints of the early 1980s, which language do you think should have been used instead of BASIC? Lisp Forth Exactly my pick -- http://mail.python.org/mailman/listinfo/python-list
Re: Create linear spaced vector?
John, Thanks for the heads up RE: scipy, I will keep my eyes on the developments. Also, thanks for the info: [quote] that the matplotlib.mlab package (where linspace and others functions reside) do not require any extension code and can be reused anywhere [/quote] I was able to get these modules into my site-packages directory, and make use of what is there. Cheers, kjm -- http://mail.python.org/mailman/listinfo/python-list
Re: better lambda support in the future?
Steven Bethard wrote: Even if you could settle the syntax issue, once you've decided that you really do need a true block in an anonymous function, you're not really saving much space by not declaring it: def f(*args): # body line 1 # body line 2 # ... # body line N x = func or f v.s. x = func or lambda *args: # body line 1 # body line 2 # ... # body line N you meant: def x(*args): # body line 1 # body line 2 # ... # body line N v.s. x = func or lambda *args: # body line 1 # body line 2 # ... # body line N right? /F -- http://mail.python.org/mailman/listinfo/python-list
Re: A completely silly question
Mike Meyer wrote: Hmm. That tells me he's probably on a Windows box, so my unix solution wouldn't do him much good. Yes, Windows...too bad -- http://mail.python.org/mailman/listinfo/python-list
Re: BASIC vs Python
not [quite] more i squared [EMAIL PROTECTED] writes: Adam DePrince wrote: Given the hardware constraints of the early 1980s, which language do you think should have been used instead of BASIC? Lisp Forth Exactly my pick Logo (my pick) has been called Lisp without the parenthesis. It has the advantage of using standard algebraic notation for formulas, instead of operator post or pre. mike -- Mike Meyer [EMAIL PROTECTED] http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why are tuples immutable?
I came in on this thread a bit late. The strictly pragmatic answer to the question in the header should be obvious. If tuples were mutable, then there would be no difference between tuples and lists, so there would be no need for tuples. Whether you think an immutable list is worth while is a different question. John Roth -- http://mail.python.org/mailman/listinfo/python-list
expression form of one-to-many dict?
So I end up writing code like this a fair bit: map = {} for key, value in sequence: map.setdefault(key, []).append(value) This code basically constructs a one-to-many mapping -- each value that a key occurs with is stored in the list for that key. This code's fine, and seems pretty simple, but thanks to generator expressions, I'm getting kinda spoiled. ;) I like being able to do something like the following for one-to-one mappings: dict(sequence) or a more likely scenario for me: dict((get_key(item), get_value(item) for item in sequence) The point here is that there's a simple sequence or GE that I can throw to the dict constructor that spits out a dict with my one-to-one mapping. Is there a similar expression form that would spit out my one-to-many mapping? Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: better lambda support in the future?
True enough, but suppose you want a hash of anonymous functions as opposed to just a lexical? This is where lambas are nice to have. Totally agreed about a small use here and there, but they do have some use in dispatch tables, as they are a lot easier to read sometimes than very long case statements.Of course, this would require multi-line lambdas to exist... --Michael I assume that the point you were trying to make is that: def f(*args): return expr is equivalent to f = lambda *args: expr ? Steve -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: expression form of one-to-many dict?
[Steven Bethard] So I end up writing code like this a fair bit: map = {} for key, value in sequence: map.setdefault(key, []).append(value) This code basically constructs a one-to-many mapping -- each value that a key occurs with is stored in the list for that key. This code's fine, and seems pretty simple, but thanks to generator expressions, I'm getting kinda spoiled. ;) I like being able to do something like the following for one-to-one mappings: dict(sequence) or a more likely scenario for me: dict((get_key(item), get_value(item) for item in sequence) The point here is that there's a simple sequence or GE that I can throw to the dict constructor that spits out a dict with my one-to- one mapping. It's a simple sequence because it's a simple task. It's even simpler than perhaps it should be, since it arbitrarily decides that, if more than one instance of some key is seen, it will only remember the value associated with the last instance of that key. Is there a similar expression form that would spit out my one-to- manymapping? There's a straightforward one-liner in 2.4 (but not notably concise), if your keys are totally ordered: from itertools import groupby d = dict((k, map(get_value, g)) for k, g in groupby(sorted(sequence, key=get_key), key=get_key)) The real purpose of that is to increase your appreciation for your original spelling 0.2 wink. -- http://mail.python.org/mailman/listinfo/python-list
Re: better lambda support in the future?
Steven Bethard wrote: You're welcome to name the function whatever you want -- notice in my example that the function is used in the statement: x = func or f If you'd prefer the statement to read: x = func or x that's also fine. Depends on what exactly 'x' is, and whether or not it really makes sense for the function I called 'f' to have the same name as the variable called 'x'. It certainly may, but since I wasn't giving real code, I didn't want to commit to that. if you write def f, f is a variable, just like x. def is an assignment statement. I'm not sure what func is supposed to be in your examples... I assume that the point you were trying to make is that: def f(*args): return expr is equivalent to f = lambda *args: expr ? def f(): ... return 1+2 ... g = lambda: 1 + 2 type(f) type 'function' type(g) type 'function' import dis dis.dis(f) 2 0 LOAD_CONST 1 (1) 3 LOAD_CONST 2 (2) 6 BINARY_ADD 7 RETURN_VALUE dis.dis(g) 1 0 LOAD_CONST 1 (1) 3 LOAD_CONST 2 (2) 6 BINARY_ADD 7 RETURN_VALUE dir(f) ['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__ge tattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__r educe__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_na me'] dir(g) ['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__ge tattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__r educe__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_na me'] f.func_name 'f' g.func_name 'lambda' /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Troubleshooting: re.finditer() creates object even when nomatch found
Chris Lasher wrote: That's odd that there's no built-in method to do this. It seems like it would be a common task. if you do this a lot, maybe you shouldn't use finditer? iterators are designed to give you the next item (if any) when you're ready to deal with it... if that's not what you want, you can use findall, search loops, scanner objects, etc. or you can implement a standard iterate ahead loop. what's your use case? /F -- http://mail.python.org/mailman/listinfo/python-list
Re: better lambda support in the future?
Michael DeHaan wrote: True enough, but suppose you want a hash of anonymous functions as opposed to just a lexical? I've seen at least one reasonable example of this kind of thing: http://mail.python.org/pipermail/python-list/2004-October/245432.html Though I haven't yet seen an example that actually required lambdas with blocks... Totally agreed about a small use here and there, but they do have some use in dispatch tables, as they are a lot easier to read sometimes than very long case statements.Of course, this would require multi-line lambdas to exist... Certainly in the example above, I'd be willing to agree that the lambdas are at least as readable as a buch of def's above would have been. I'm not sure if multi-line lambdas would be as readable though... It all depends on what syntax you write them in -- you can see the struggle I went through in my other message... Where do I put the commas in a dict? Can't be at the end of the lambda or they turn the last expression into a tuple... I resorted to putting them on a separate line, but of course there are other solutions. If you have a good example of where you'd like to use multi-line lambdas, in, say, a dispatch table, I'd like to take a look at how you'd like to write them. I'm not yet convinced that there really is a readable way to write such things... Steve -- http://mail.python.org/mailman/listinfo/python-list