Re: how can this iterator be optimized?
On Feb 14, 10:19 am, Paul McGuire wrote: > If func is expensive, you could try memoizing it. Then subsequent > "calls" just do arg lookups. Michele Simianato has posted a good > memoizing decorator on the Python wiki. > > -- Paul That's the trick! I almost forgot about that one. Thanks! -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: Levenshtein word comparison -performance issue
On Feb 13, 5:42 am, "Gabriel Genellina" wrote: > You may replace the last steps (sort + slice top 5) by heapq.nlargest - at > least you won't waste time sorting 49995 irrelevant words... > Anyway you should measure the time taken by the first part (Levenshtein), > it may be the most demanding. I think there is a C extension for this, > should be much faster than pure Python calculations. subdist: http://pypi.python.org/pypi/subdist/0.2.1 It uses a modified "fuzzy" version of the Levenshtein algorithm, which I found more useful than the strict version. The only quirk to it is that it accepts nothing but unicode. Other than that, it's a keeper. It is extremely fast. Cheers, -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: how can this iterator be optimized?
On Feb 12, 1:15 am, Steven D'Aprano wrote: > > I usually strive > > for comprehensions if a for loop can be reduced to such. > > Any particular reason? Only two. 1.) I was impressed by their clarity and conciseness when I first discovered them. 2.) I also read now and then that simple list comprehensions are faster when compared with their for-loop equivalents because of the way comprehensions are implemented under the hood. My example is a far cry from a "simple" comprehension, however. :) > If there's only one call to func(), and you ignore the (probably) fixed > cost of jumping into a generator each time, then it shouldn't make any > difference. > > If you are comparing one call to func() in a for loop versus three calls > to func() in a list comp or generator expression, then of course the for > loop will be more efficient. I agree. I would rather call func() only once per iteration in any case. I will revise it to a plain for loop with a single call. Thanks, -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: A little bit else I would like to discuss
On Feb 12, 10:39 pm, Damon wrote: > * Like R, every time there is a new version of Python, the repository > should rebuild the packages, for all supported platforms, and make > available all those that compile cleanly. R also forces you to write > properly structured documentation for every exposed function, before > the repository will accept it. A very good idea indeed. I would love to start using Py3k today, but I am still on 2.5 because I depend on win32 binaries for the majority of my library packages. I can build some myself, but not all. A repository of prebuilt binaries that stay in step with currently available language releases would be most welcome. Just my $0.02, -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: how can this iterator be optimized?
> Don't use a generator then. If you're going to finally return a list (and > sorted does exactly that), build a list right from the start: Good point. However, for the sake of argument, what if I removed the sorting requirement and simply wanted the generator? I usually strive for comprehensions if a for loop can be reduced to such. Would there be any speed advantage in this case of a comprehension-style generator vs. a for-yield loop (assuming there is a way to call func(s) once per iteration in the comprehension)? In my example, func() operates on filename strings, so it's not too bad.. but it's possible for this pattern to apply to more substantial operations. My conjecture is that higher func() loads would favor more the use of a simple for- yield loop. Cheers, Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
how can this iterator be optimized?
Hello all, I have the following function that uses an intermediate iterator "rawPairs": def MakePairs(path): import os import operator join = os.path.join rawPairs = ( (join(path, s), func(s)) for s in os.listdir(path) if func(s) is not None and func(s).endswith("some criterion") ) #Use the second item in the pair as the sort criterion result = sorted(rawPairs, key=operator.itemgetter(1)) return result where "func" is a single-argument function that returns either a string or None, but is an expensive call. I am pretty sure that the sorted() construct cannot be improved much further, but... ...does anyone have ideas on improving the "rawPairs" iterator so that it calls "func(s)" only once per iteration? Perhaps a lambda construct, but I am not sure how to go about it...? Cheers, Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: Is this a good time to start learning python?
On Mar 31, 11:40 am, Rui Maciel <[EMAIL PROTECTED]> wrote: > Recently I woke up inclined to take up the task of learning another > programming language. I've already dipped my toes in Perl (I've read online > tutorials and wrote a couple of irrelevant pet projects) but, as the > computers at my workplace only sport the python interpreter, it probably > means that learning python will end up serving me better, at least in the > short run. Plus, you know how Perl goes. > > So far the decision seems to be a no brainer. Yet, Python 3000 will arrive > in a few months. As it isn't backwards compatible with today's Python, > there is the risk that no matter what I learn until then, I will end up > having to re-learn at least a considerable part of the language. To put it > in other words, I fear that I will be wasting my time. > > At least that is what a clueless newbie believes. As this group is > frequented by people who have more insight into all things pythonesque, > what are your thoughts on this? > > Thanks for the help > Rui Maciel Think of it this way - A.) If you start learning Python 2.5 *today*, and then Python3k comes out in a few months and (at worst) breaks all your code, you will still have less code to patch than the person who learned Python 2.3 two years ago :) B.) If you start learning Python 2.5 *tomorrow*... who knows, we might not be alive tomorrow. Seize the day. Seriously, I have watched Guido's GoogleTalk on Py3k plans, and the changes are not all that scary. I'm looking forward to it. Cheers, -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: Python in High School
On Apr 1, 12:27 pm, sprad <[EMAIL PROTECTED]> wrote: > I'm a high school computer teacher, and I'm starting a series of > programming courses next year (disguised as "game development" classes > to capture more interest). The first year will be a gentle > introduction to programming, leading to two more years of advanced > topics. > > I was initially thinking about doing the first year in Flash/ > ActionScript, and the later years in Java. My reasoning is that Flash > has the advantage of giving a quick payoff to keep the students > interested while I sneak in some OOP concepts through ActionScript. > Once they've gotten a decent grounding there, they move on to Java for > some more heavy-duty programming. > > I've never used Python, but I keep hearing enough good stuff about it > to make me curious. > > So -- would Python be a good fit for these classes? Could it equal > Java as the later heavy-duty language? Does it have enough quickly- > accessible sparklies to unseat Flash? > > I want to believe. Evangelize away. I highly recommend that you read the introduction chapters in two of the books on this site: http://www.greenteapress.com/ The first book is called "How To Think Like a Computer Scientist: Learning with Python". The second book is a follow-up edition to that one, and is called "How To Think Like a (Python) Programmer". All of the books there are written by school teachers, so I think you will find valuable insight there. The same books also have a Java and a C++ flavor. All are free downloads. My very first serious look into Python came from this series, and I thoroughly enjoyed learning the basics. I think the text was so successful for me because the content is well-connected. As far as which language to choose - well, you can make the choice yourself after reading at least the introductions of all the books. If you do decide on Python, there is a library called "pygame" that may achieve your visual game programming goals. Enjoy! -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: super, decorators and gettattribute
On Jan 14, 7:53 am, Michele Simionato <[EMAIL PROTECTED]> wrote: > I really need to publish this one day or another, since these > questions > about super keeps coming out: > > http://www.phyast.pitt.edu/~micheles/python/super.html Please do. It is a very enlightening discussion, and I'm sure a bunch of folks will benefit from it. And please update it (if necessary) to the current Python version. At the time of that writing, 2.3 must have been King, but oh my, how time flies :-) Cheers, -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: for loop without variable
On Jan 10, 10:36 pm, Marty <[EMAIL PROTECTED]> wrote: > Hrvoje Niksic wrote: > > Mike Meyer <[EMAIL PROTECTED]> writes: > > >> It sounds to me like your counter variable actually has meaning, > > > It depends how the code is written. In the example such as: > > > for meaningless_variable in xrange(number_of_attempts): > > ... > > > the loop variable really has no meaning. Rewriting this code only to > > appease pylint is exactly that, it has nothing with making the code > > more readable. > > >> you've hidden that meaning by giving it the meaningless name "i". If > >> you give it a meaningful name, then there's an obvious way to do it > >> (which you listed yourself): > > >> while retries_left: > > [...] > > > This loop contains more code and hence more opportunities for > > introducing bugs. For example, if you use "continue" anywhere in the > > loop, you will do one retry too much. > > I recently faced a similar issue doing something like this: > > data_out = [] > for i in range(len(data_in)): > data_out.append([]) > > This caused me to wonder why Python does not have a "foreach" statement (and > also why has it not come up in this thread)? I realize the topic has probably > been beaten to death in earlier thread(s), but does anyone have the short > answer? But it does: data_in = (1,2,3,4,5) data_out = [] data_out += [[] for blah in data_in] print data_out [[], [], [], [], []] Cheers, -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: for loop without variable
On Jan 9, 10:55 pm, Ben Finney <[EMAIL PROTECTED]> wrote: > erik gartz <[EMAIL PROTECTED]> writes: > > The loop performs some actions with web services. The particular > > iteration I'm on isn't important to me. It is only important that I > > attempt the web services that number of times. If I succeed I > > obviously break out of the loop and the containing function (the > > function which has the loop in it) returns True. If all attempts > > fail the containing loop returns False. > > When you have iteration requirements that don't seem to fit the > built-in types (lists, dicts, generators etc.), turn to 'itertools' > http://www.python.org/doc/lib/module-itertools> in the standard > library. > > >>> from itertools import repeat > > >>> def foo(): > ... import random > ... print "Trying ..." > ... success = random.choice([True, False]) > ... return success > ... > >>> max_attempts = 10 > >>> for foo_attempt in repeat(foo, max_attempts): > ... if foo_attempt(): > ... break > ... > Trying ... > Trying ... > Trying ... > Trying ... > Trying ... > Trying ... > >>> > > Note that this is possibly more readable than 'for foo_attempt in > [foo] * max_attempts", and is more efficient for large values of > 'max_attempts' because 'repeat' returns an iterator instead of > actually allocating the whole sequence. > > > I guess based on the replies of everyone my best bet is to leave the > > code the way it is and suck up the warning from pylint. > > I think your intent -- "repeat this operation N times" -- is better > expressed by the above code, than by keeping count of something you > don't actually care about. > > > I don't want to turn the warning off because catching unused > > variables in the general is useful to me. > > Agreed. > > -- > \ "Dyslexia means never having to say that you're ysror." | > `\--anonymous | > _o__) | > Ben Finney Neat! That is the best solution I've seen so far. I should definitely dig into the itertools module more often. Cheers, -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: for loop without variable
On Jan 9, 9:49 pm, erik gartz <[EMAIL PROTECTED]> wrote: > The loop performs some actions with web services. The particular > iteration I'm on isn't important to me. It is only important that I > attempt the web services that number of times. If I succeed I > obviously break out of the loop and the containing function (the > function which has the loop in it) returns True. If all attempts fail > the containing loop returns False. Do you think you could apply something like this: def foo():print "fetching foo..." actions = (foo,)*5 for f in actions: f() fetching foo... fetching foo... fetching foo... fetching foo... fetching foo... ..but not knowing your specific implementation, I may be off the wall here. Cheers, -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: using super
On Jan 1, 12:11 am, Scott David Daniels <[EMAIL PROTECTED]> wrote: > Steven D'Aprano wrote: > > On Mon, 31 Dec 2007 16:19:11 -0800, Scott David Daniels wrote: > > >> Steven D'Aprano wrote: > >>> On Mon, 31 Dec 2007 08:03:22 -0800, Scott David Daniels wrote: > >>>> Steven D'Aprano wrote: ... > >>>>> def chain(meth): # A decorator for calling super. > >>>>> def f(self, *args, **kwargs): > >>>>> result = meth(self, *args, **kwargs) > >>>>> S = super(self.__class__, self) > >>>> This line is the problem. The class parameter needs to be the class > >>>> (B in this case) in which the chaining method is defined, not that of > >>>> the object itself. > >>> One minor correction: the class parameter needs to be the class > >>> *itself*, not the class *name* (which would be the string "B"). > >> Point taken. > > >>> I don't quite understand your description though. What do you mean "the > >>> chaining method is defined"? chain() is defined outside of a class. > >> The class where f (the chaining method) is defined; equivalently, the > >> class in which the @chain is used. > > > So why doesn't self.__class__ work? That's the class in which @chain is > > used. > > OK, here's a simple 3-class example: > > class A(object): > def meth(self): print 'A.meth:', self.__class__, '---' > def pn(self): return '' > > class B(A): > def meth(self): > super(B, self).meth() > print 'B.meth:', self.__class__, super(B, self).pn() > def pn(self): return '' > > class C(B): > def meth(self): > super(C, self).meth() > print 'C.meth:', self.__class__, super(C, self).pn() > def pn(self): return '' > > c = C() > c.meth() > # Figure out why it printed what it did. > > # If not clear yet, how about this: > for class_ in C, B: > print class_.__name__, super(class_, c).pn() > > # And a bigger example (re-using A) to show why we > class B0(A): > def meth(self): > super(B0, self).meth() > print 'B0.meth:', self.__class__, super(B0, self).pn() > def pn(self): return '' > > class B1(B0): > def meth(self): > super(B1, self).meth() > print 'B1.meth:', self.__class__, super(B1, self).pn() > def pn(self): return '' > > class B2(B0): > def meth(self): > super(B2, self).meth() > print 'B2.meth:', self.__class__, super(B2, self).pn() > def pn(self): return '' > > class C1(B1, B2): > def meth(self): > super(C1, self).meth() > print 'C1.meth:', self.__class__, super(C1, self).pn() > def pn(self): return '' > > class D1(C1): > def meth(self): > super(D1, self).meth() > print 'D1.meth:', self.__class__, super(D1, self).pn() > def pn(self): return '' > > d = D1() > d.meth() > # Figure out why it printed what it did. > > for class_ in D1, C1, B1, B2, B0: > print class_.__name__, super(class_, d).pn() > # Now (after much cogitation) might that do it? > > # finally, just a fillip, predict this before you run it: > class E(D1, C): > def meth(self): > super(E, self).meth() > print 'E.meth:', self.__class__, super(E, self).pn() > def pn(self): return '' > > e = E() > e.meth() > for class_ in E, D1, C1, B1, B2, B0, C, B: > print class_.__name__, super(class_, e).pn() > > > I can clearly see that it doesn't work, I just don't understand why. I'd > > be inclined to chalk it up to super() being a mysterious black box that > > makes no sense *wink* > > super (and mro) work to get to all the superclasses in an order that > produces subtypes before their supertypes. The diamond inheritance > examples "show" why its needed. > > -Scott Cool, thanks for posting this example and clearing that up. Several times in the past I have used super(self.__class__, cls) instead of super(Klass_obj, cls), without a clue that it would wreck the subclasses. My beginner's thought at the time was that it would provide more flexibility.. Good thing I haven't had to subclass them..yet :) Cheers, -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: using super
On Jan 2, iu2 <[EMAIL PROTECTED]> wrote: > I missed new style classes though... Now I know how to use them (not > fully), but I must say it has been difficult. I'll appreciate some > good documentation about them. > > Thanks > iu2 This is a decent start: http://www.python.org/doc/newstyle/ Cheers, -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's great, in a word
On Jan 7, 8:09 am, [EMAIL PROTECTED] wrote: > I'm a Java guy who's been doing Python for a month now and I'm > convinced that > > 1) a multi-paradigm language is inherently better than a mono-paradigm > language > > 2) Python writes like a talented figure skater skates. > > Would you Python old-timers try to agree on a word or two that > completes: > > The best thing about Python is ___. > > Please, no laundry lists, just a word or two. I'm thinking "fluid" or > "grace" but I'm not sure I've done enough to choose. Here's a new word - ...its humanicity factor. That definition, according to me, is: "its ability to let you *quickly* formulate and solve your problem in the way that YOU see it, not as the computer sees it." Did programmers stop writing programs on punch cards because they ran out of punch paper? Cheers, -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: "Python" is not a good name, should rename to "Athon"
Matt Nordhoff <[EMAIL PROTECTED]> wrote: <..snip..> > Great, now the Google results will just be filled with AMD typoes. :-P Clever! But "typoes" is a typo :-P >From m-w.com: typo Function: noun Inflected Form(s): plural: typos Etymology: short for typographical (error) Date: 1878 : an error (as of spelling) in typed or typeset material === But seriously guys (and gals, if any?), this has to be the most senseless thread I have seen.. tum-dee-dum... the OP must have been "counting flowers on the wall"... If the OP's advice is to be followed - what shall we do, pray tell, with the names of all the existing lovely libraries and apps that we are so used to? Surely they all have to be changed over to keep up with such progress?! Numpy => NumAth? wxPython => wxAthon? PyAlaMode => AthAlaMode? etc. FWIW, an ASP is also a snake...but that's another discussion. Shall we start one? I think NOT.. This has been an entertaining break from the ordinary, but let's get back to something more useful. Cheers, -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: Lib for audio?
On Nov 29, 7:04 am, Dave <[EMAIL PROTECTED]> wrote: > I need to read microphone input and determine frequency. Is there a lib > for that? > > Thanks, > Dave How about PyMedia? It has input reading capability from any sound device that your system supports, as well as frequency analysis based on real-time sampling. It's well worth taking a look: http://pymedia.org/ Cheers, -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: MP3 and ID3 library/module recommendations
I use PyMedia and mutagen. I've found PyMedia to be excellent for creating custom mp3 files from line input and performing frequency/energy analysis. I can't say that I've tried to convert other audio formats to MP3 with it, but I'm sure it's possible. I was able to get a working binary of v1.3.7.3 for win32 and python 2.5 directly from the author, since I have no way to compile it from the source that's posted on the project website. If you need it, let me know. On the other hand, mutagen is a good lightweight utility for extracting and modifying all kinds of audio metadata. On mp3's, that includes track duration, all ID3 info, bitrate, sample rate, etc. It provides an easy dictionary-like interface. It supports a number of audio formats, but I don't believe it has conversion capability. Cheers, -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: where do I need to "tab"?
Tab is not the issue here. By my powers of deduction, I can see that you are running this code in Python version previous to 2.5, because the construct "true_clause if condition else false_clause" did not exist until 2.5. It's a neat little construct, I highly recommend you upgrade now :) -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: interesting puzzle......try this you will be rewarded...
On Sep 7, 5:08 am, "Andreas Tawn" <[EMAIL PROTECTED]> wrote: > > Maybe http://www.pythonchallenge.com/? That's the one, thanks! --- -- http://mail.python.org/mailman/listinfo/python-list
Re: interesting puzzle......try this you will be rewarded...
Woody! :)) -- http://mail.python.org/mailman/listinfo/python-list
Re: interesting puzzle......try this you will be rewarded...
I got to 14 :) It's rather silly. I remember seeing a more elaborate puzzle that involved coding, cryptography knowledge, etc. to get through it. But what was the link, I forget now... -- http://mail.python.org/mailman/listinfo/python-list
Re: GUI and distrubution
On Aug 24, 12:53 pm, anders <[EMAIL PROTECTED]> wrote: > I have looked att Python onwww.showmedo.com > And after this i start testing writing som program i Python. > But... > > So how is the preferably way to distribute software written i Python > i am NOT into hiding stuff, more a easy way of giving eg friends > a copy of the program without having them installtion a lott > och other stuff. > > My next question is witch is the best GUI to use, also consider > the delivery question above. > > // Anders Indeed a popular set of questions; but what is your platform? Without that information, I'll just give you my biased opinion: wxPython GUI toolkit, py2exe for distribution, and WiX or Inno Setup for the installer. Now, you guess what my platform is ;-) Once you get comfortable writing a few py2exe setup scripts, try Andrea Gavana's GUI2Exe - it makes the distribution process a bit less painful. Of course, you're welcome to search for other stuff as suggested by the other responses. Cheers, Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: py2exe/distutils: how to include a tree of files?
On Aug 24, 4:55 pm, Grant Edwards <[EMAIL PROTECTED]> wrote: > I'm packaging up a python program and need to include an entire > directory tree in the distribution. the data_files=[] option to > setup() is fine for individual files, but what do I do when I > need to include an entire directory tree? > > On a more general note, I'm having trouble finding much > documentation on py2exe at all. There's a wiki page at > py2exe.org, but it's pretty superficial. It mentions looking > at the distutils documentation for details, but I've no idea > how distutils relates to py2exe or where in the distutils > documentation to look for py2exe stuff (I don't see anything > that looks familiar in the distutils docs). > > There must be some py2exe documentation somewhere... > > [http://sourceforge.net/projects/py2exe/hasn't been updated in > 5 years, is there any reason why it's still around?] > > -- > Grant Edwards grante Yow! LBJ, LBJ, how many > at JOKES did you tell today??! >visi.com Grant, Any os.walk() loop that you can conceive which will generate a list of the kind [(dir1, pathList1), (dir2, pathList2), etc...] will work. Each subdir of your top-level tree has to be listed this way with the accompanying pathList of the subdir's files. I did this once for a 'samples' directory tree that I packaged with an app: #sample data files sampleDir = r'.\\samples' for root, dirs, files in os.walk(sampleDir): sampleList = [] if files: for filename in files: #ignore SVN dirs if ".svn" not in root: sampleList.append(os.path.join(root, filename)) if sampleList: dataFiles.append((root, sampleList)) On a side note, I've discovered that matplotlib since 0.90 or maybe earlier has specifically added a matplotlib.get_py2exe_datafiles() function to add its necessary data files in this way. Wouldn't it be nice if py2exe had something simple like that built in... Have you tried GUI2Exe? I've found its interface quite easy to use. It doesn't recurse into a dir tree (feature request?), but it makes the selection process at least half as painful. The py2exe docs leave something more to be desired. I found more tips and help via Google, ASPN, and on this list. Good luck, Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: How to optimise this code?
David, If your true design intent is to run X number of test cases, unittest is the biggest bang for your buck, like shown by Peter's example. You just subclass unittest.TestCase, and def your test methods in the class body; they will simply be executed in the order you list them. It's just nice how it works that way. Otherwise, the function factory approach like Hrvoje's functionToCall = getattr(self, "testCase%s" % tc) is the best optimization. Cheers, -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie question: how to get started?
On Jun 16, 11:10 pm, walterbyrd <[EMAIL PROTECTED]> wrote: > Here are two very well regarded online books - both free: > > http://www.diveintopython.org/ > > http://www.ibiblio.org/obp/thinkCSpy/ I second that advice, especially the latter text. It's an excellent resource for any beginner in Python, whether he/she has previous programming background or not. -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: interating over single element array
Thank you both for clearing that up. -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: interating over single element array
"Terry Reedy" <[EMAIL PROTECTED]> wrote: > Any what if 'filelist' is any iterable other than a string or list? Your > code is broken, and unnecessarily so. So I would call the parameter > 'files' and test for isinstance(files, str) #or basestring. And wrap if it > is. Can you give an example of such an iterable (other than a tuple)? I'd certainly like to fix my 'fix' to work for a more general case. Regards, -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: interating over single element array
On Jun 8, 11:54 am, "T. Crane" <[EMAIL PROTECTED]> wrote: > >> any suggestions are appreciated, > > > Yes, don't try iterating over objects that are not iterable. ;-) > > Ah, yes... I hadn't thought of that :) > > thanks, > trevis > > > > > What you *can* do is iterating over lists, tuples or other iterables with > > just one element in them. Try ``a = [1]``. > > > Ciao, > > Marc 'BlackJack' Rintsch You can also do this (if tuples are okay in your case): a = 1, The comma turns 'a' into a tuple (1,) which is both iterable and has a length of 1. I have run into this issue before with a function that took a list of filenames (strings), and needed to iterate over the list to operate on the input files. For the case when the input would be a single file, I needed to turn the input string into an iterable such that the 'for' loop would not iterate on the filename characters (a rather undesirable gotcha, you understand :-) ). So I solved my problem like this: def loadfiles(filelist): if not isinstance(filelist, list): filelist = filelist, for filename in filelist: f = open(filename,'r') #do interesting stuff with file, etc... ..and it's been working very well. Cheers, -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: creating lists based on parsed items
> This would be a RTFM moment :) defaultdict is not a built-in, it is part > of the collections module. Bingo! I should have read higher up in the manual tree :) Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: creating lists based on parsed items
> If you are using Python 2.5, use a defaultdict instead, the very first > example looks like what you want. > <http://docs.python.org/lib/defaultdict-objects.html> > > -- > Gabriel Genellina Uh-oh.. I am using Python 2.5 on WinXP, but when I tried the examples in the manual, I got a "NameError: name 'defaultdict' is not defined". What am I missing in my Python installation? -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: Which class's comparison function is called?
Try adding the following diagnostic messages to your __eq__ class definitions, and see if it will dispel the confusion for the four equality tests you have tried: class A: def __init__(self,a): self.a = a def __eq__(self, other): print "(A) self:%r, other:%r" %(self.__class__, other.__class__) return self.a == other.a class B: def __init__(self,b): self.b = b def __eq__(self, other): print "(B) self:%r, other:%r" %(self.__class__, other.__class__) return self.b == other.b You are correct, Python evaluates the expressions from left to right. > A(1) == B(1) > ---> AttributeError: B instance has no attribute a The left instance's __eq__ method is invoked, which says, "is the value of self.a equal to the value of other.a ?"; and the answer is, "other has no attribute a to compare with self.a!" so you get an exception. > B(1) == A(1) > ---> AttributeError: A instance has no attribute b Same case as the first, but the instances have switched places... > A(1) == 3 > ---> AttributeError: 'int' object has no attribute a Same case as the first, but 'other' is now an object of type 'int', which inherently has no attribute 'a'. A similar effect will manifest when you will try to do: B(1) == 3 ---> AttributeError: 'int' object has no attribute 'b' > 3 == A(1) > ---> AttributeError: 'int' object has no attribute a > > Can someone explain this? I expected 3 == A(1) to use the __eq__ > function defined for 'int' objects. This last one is interesting. The '__eq__' method is not defined for 'int' objects. The '==' operator tests for value equivalence. As before, the left side is evaluated first, and evaluates to a simple integer value. No special methods are called. Now, the right side's value is evaluated. Since equality is being tested, the right side's __eq__ method is called, with the (self, other) arguments being (, 3) respectively. Since 'int' is the 'other' argument in this case, it again results in the exception "no attribute 'a' ". The last of the four tests that you have mentioned is giving you the trouble, right? Perhaps the solution is to add type-checking to the __eq__ method? (untested) def __eq__(self, other): if isinstance(other, int): tmp = other else: tmp = other.a # (other.b in class B definition) return self.a == tmp # (self.b in class B definition) Cheers, -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: NOOOOB
On May 22, 5:44 pm, [EMAIL PROTECTED] wrote: > On May 22, 6:29 am, jolly <[EMAIL PROTECTED]> wrote: > > > Hey guys, > > > I want to begin python. Does anyone know where a good starting point > > is? > > > Thanks, > > Jem > > I really liked How to Think Like a Computer Scientist learning with > python foound athttp://www.ibiblio.org/obp/thinkCSpy/. Unlike most > paper books you'd be hard pressed to find typos (that at this level of > programming you wouldn't notice) there. Also if you want another > source of info trywww.diveintopython.org. You can find the book on > the store shelves, but why pay when you can get it for free of the > net. You can view it as HTML or download the .pdf. I agree with the previous post on the "Think Like a CS" book. It is excellent text for getting your feet wet in Python, whether you have had previous programming experience or not. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to use private method in a class
On May 21, 9:49 pm, "wang frank" <[EMAIL PROTECTED]> wrote: > Hi, > > I am trying to write a python class with a new data type such as: > class Cc14: >def __init__(self, realpart, imagpart): > self.r=realart > self.i=imagpart > >def __saturator(x): > return x+1 >def out(self,x): > return Cc14(__saturator(x.r), __saturator(x,i)) > > When I use the method out such as: > z.out > > Python complains: > > global name '_Cc14_saturator' is not defined. > > Is the way put two underscore in front of the definitio making the method > becomes private? > > Why in the same clase, I could not use the __saturator method? > > Thanks > > Frank > It seems you have several issues here: (1) To avoid syntax errors, self.r=realart should be: self.r=realpart (2) Your __saturator method definition needs the reference to self: def __saturator(self, x): (3) And lastly, the body of the out() method needs two corrections: return Cc14(self.__saturator(x.r), self.__saturator(x.i)) Is it really necessary to "privatize" the saturator method? In Python, all class methods are public and visible by default. A method name __methodname in a class "foo" turns into "_foo__methodname" in an instance of the class. This is known as name mangling. It is simply a convention supported by Python when a class attribute name begins with two underscores. It prevents a programmer from calling something like C.__saturator(arg), but still allows calling C._Cc14__saturator(arg). IMHO, you could just leave the saturator definition as "def saturator(self, x):" Anyway, in your case the 3 fixes above will allow you now to do this: >>>C = Cc14(2,3) >>>result = C.out(C) >>>result.r, result.i (3, 4) Which is beginning to look like your design intent.. Cheers, -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: A few questions
> After this I went to the tutorial and started trying out some of the > examples. I pasted the code to separate text files and then ran them > through a Terminal window. This stuff is freaking cool!!! Now I > just have to figure out how this all works! > "wxPython in Action" is a decent book for learning wxPython: http://www.manning.com/rappin/ As with any GUI toolkit, there is a learning curve until you get used to how the components work together. But there is enough hands-on material to get started with simple GUI apps. > Anyway, I had one more quick question... in order to run wxPython > apps, do I have to have MacPython, etc. loaded on each Mac (or PC) in > order for it to run any apps I write? Or is there a way to compile > the code to where I can distribute an app I write and the other users > don't need to load anything in order to run the app? Again, I can't speak for Macs, but I know that for Windows there is one package suitably called "py2exe", available from http://www.py2exe.org/ which allows you to freeze your code and distribute it to multiple users as an executable file plus some extra baggage files containing bytecode and necessary DLL's, including the Python interpreter itself. This way, the end user does not need to install Python, wxPython, or any other Python libraries used by your project, nor does the end user even need to know anything about Python. Pros? The app is ready to run as shipped. Cons? Relatively large size of the distributable package - a typical simple GUI app is 6MB+ when packaged this way. Although... with the acres of storage space available on today's media, this is hardly a problem. :) -- http://mail.python.org/mailman/listinfo/python-list
Re: A few questions
> 2. Is there a good book to start with while learning Python? I'm > currently reading 'Python Essential Reference' by David M. Beazley. > So far it looks like a pretty good book, but would like more > tutorials to work with (I've also been reading through the tutorials > at 'python.org' which has some excellent stuff!). Take a walk through the text "How to Think Like a Computer Scientist": http://www.ibiblio.org/obp/thinkCSpy/ It's medium-paced, well-organized, and - quite importantly IMHO - builds well on knowledge acquired in the previous chapters as it progresses. There are plenty of hands-on examples; and really, the text was written by a high school teacher for a CS curriculum, so it's structured more like a tutorial. I found it to be priceless when I first got interested in Python, and I would highly recommend it to any newbie, whether with previous programming experience or not, but who has never laid eyes on Python before. As I think back on it, the book gives you just enough information to make you hungry for more - and indeed, after reading it I had enough insight to explore Python on my own and started writing useful programs by myself. > > 3. Currently, I write most of my code with Xcode (on the Mac > platform) using Applescript. This gives me GUI capabilities. Is > there anything you'd recommend that I could use for Python that would > give me a GUI interface? I'd like this to be able to work for both > the Mac and Windows platforms. I've been reading a little about > 'Claro Graphics Toolkit' and 'PyGUI'... would you recommend either of > those? I'll be writing code on a Mac so I need something that will > run on that system. > Try wxPython. I've seen it run on a Mac with OS X and Windows simultaneously, where the operating systems were switched from one to the other at the touch of a button, and the GUI had a very native look in either platform (mind you, the app was running exactly the same code in both cases!). I write my code on a win32 box, so I have no further pointers for you regarding a Mac. -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
How to cleanly pause/stop a long running function?
Suppose I have a function that may run for a long time - perhaps from several minutes to several hours. An example would be this file processing function: import os def processFiles(startDir): for root, dirs, files in os.walk(startDir): for fname in files: if fname.lower().endswith(".zip"): # ... do interesting stuff with the file here ... Imagine that there are thousands of files to process. This could take a while. How can I implement this so that the caller can pause or interrupt this function, and resume its program flow? Doing a Ctrl+C interrupt would be a not-so-clean-way of performing such a thing, and it would quit the application altogether. I'd rather have the function return a status object of what it has accomplished thus far. I have heard about threads, queues, and asynchronous programming, but am not sure which is appropriate for this and how to apply it. Perhaps the above function should be a method of a class that inherits from the appropriate handler class? Any help will be appreciated. -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic question
On May 12, 12:18 pm, "Cesar G. Miguel" <[EMAIL PROTECTED]> wrote: > I've been studying python for 2 weeks now and got stucked in the > following problem: > > for j in range(10): > print j > if(True): >j=j+2 >print 'interno',j > > What happens is that "j=j+2" inside IF does not change the loop > counter ("j") as it would in C or Java, for example. > > Am I missing something? > > []'s > Cesar What is your real intent here? This is how I understand it after reading your post: you want to create a loop that steps by an increment of 2. If that's the case, then: >>> for j in range(0,10,2): ... print j ... 0 2 4 6 8 would be a simple result. Cheers, -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: chdir()
On May 8, 3:54 pm, HMS Surprise <[EMAIL PROTECTED]> wrote: > Tried executing os.chdir("c:\twill") from a python Tk shell and got > the error message: > > WindowsError: [Error 123] The filename, directory name, or volume > label syntax is incorrect: 'c:\twill'. > > I have the directory exists as I copied the name from the explorer > window that was open to it. > > What is wrong with the syntax? > > thanks, > > jh Use os.chdir(r"c:\twill") instead. The "\t" character is the escape character for a tab. You can avoid such a faux pas by using the raw string construct of the form r"some string". Otherwise, any backslashes in in your string will be interpreted as escape characters. -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: How to check if a string is empty in python?
> How do you know that s is a string? It's a presumption based on the original problem statement. The example shown is a simple T/F check, which happens to determine the "emptiness" of strings. If type checking is absolutely necessary, one could use if isinstance(s, basestring): if s: print "not empty" else: print "empty" -- http://mail.python.org/mailman/listinfo/python-list
Re: How to check if a string is empty in python?
A simple if s: print "not empty" else: print "empty" will do. -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: ScrolledText?
Ah.. wx is wxPython in this case, a GUI toolkit like Tkinter, but based on wxWidgets. I don't know if Tk has a text control with a method similar to the AppendText method I showed here.. I used to have the exact same problem as you until I discovered that AppendText always kept the text box scrolled at the bottom :) How about this: >>>help(Tkinter.Text.see) Help on method see in module Tkinter: see(self, index) unbound Tkinter.Text method Scroll such that the character at INDEX is visible. It may be what you're looking for if you use 'end' for index ...? -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: ScrolledText?
Would this work? self.text = wx.TextCtrl(panel, style=wx.TE_MULTILINE) ... line = '\n' + "Hello world!" self.text.AppendText(line) -- http://mail.python.org/mailman/listinfo/python-list
Re: Removing the continous newline characters from the pythong string
What was I thinking? split() will only work if you have no other whitespace characters in the string. A regex like "[\n\r]+" is indeed much more appropriate and robust. Cheers -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: Removing the continous newline characters from the pythong string
why not use split: >>>s = " >>>a\n\n\n\n\n\n\n\n\nsss\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nvsa\n\n\n\nasf... >>>\n\nafs" >>>s.split() ['a', 'sss', '', 'vsa', 'asf...', 'afs'] -- http://mail.python.org/mailman/listinfo/python-list
Re: My Python annoyances
> Everyone know that programming is supposed to be a dark art, nearly > impossible to learn. Computer code is supposed to be something > impossible to read to the common person and yet reveal their secrets > to the initiated - just remember the code displayed in the Matrix... Hmm, on my PyCon mug there are words "Python: so easy...even your BOSS can use it!" Thankfully, my boss doesn't know the difference between directories and files, so I can easily succeed in making him think that Python really IS a black art :) Cheers -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting started with python
On Apr 14, 8:46 pm, "Eric" <[EMAIL PROTECTED]> wrote: > Hello, after reading some of the book Programming Python it seems that > python is something I would like to delve deeper into. The only thing > is, I have no idea what I should try and write. So I was hoping that > someone here could help point me to a group/project that would be a > good starting place for a person with limited python knowledge, but > that is willing to learn whatever is necessary. I'm hoping that with a > goal I can start to learn python instead of just playing around with > it. Thanks. Eric, You will certainly appreciate how concise and easy Python is. I am also relatively new to Python (started about a year ago), and I'd rather not go back to any other language! Why would I want to torment my not-so-quick typing fingers?? :) I'm a self-learner. I learn by reading, by example, and by doing. Here is a list of suggestions. Start with simple things, grow confident, and move on to more interesting stuff as you progress: At the Python command line, type "import this" to see the basic ideas behind Python development. It begins with "Beautiful is better than ugly." - a nice thought. 1. First of all, read the publication "How to Think Like a Computer Scientist: Learning with Python" by Allen B. Downey et al. I have found this little gem to be very, very useful when I first got interested in Python and thought to myself, "how do I go about learning this, where do I start??". Highly recommended. I read it from start to finish in a couple of days and started making useful scripts right after that. The author actually implements a simple card game toward the end of the book, using all the knowledge from the previous chapters. The text is available at: http://www.ibiblio.org/obp/thinkCSpy/ 2. Play with Python from the command line first, using PyShell, PyCrust, or any of its other siblings that come with the wxPython package (a GUI toolkit - see #8 below). You will find the code completion feature and the syntax helper quite useful. 3. Tinker around with the builtin modules. There's a lot of built-in functionality in Python right out of the box. Try the "os" and "sys" modules to experiment with filesystem handling. Try reading and writing text files, as this is quite a common task with a variety of applications. Try the "struct" module for binary file processing. Try the "urllib" and "urllib2" modules for loading and processing Web pages... I could go on, but you get the idea. 4. If you have a text processing background, dip your hand in regular expressions with the "re" module. Maybe you have a need for extracting some statistical data from a financial report, and this might be one way to do it. 5. If you have a mathematical background, download and install the NumPy or SciPy package and do some wild matrix math! 6. I have recently tinkered with the Pymedia package, perhaps you want to try it later on. It is a nice tool for dealing with audio - for recording, encoding, decoding, spectrum analysis, etc. In just a few hours, I came up with a nice voice-activated MP3 sound recorder application. 7. If you feel brave and want to work with Windows COM client/server stuff (assuming Windows is your platform), get the PythonWin package, also known as "win32com" and try to read/write Excel, Word files, etc., or whatever 8. Last but certainly not least, once you feel comfortable with basic Python, try GUI development. Several gui toolkits are out there. wxPython is a good one to start with, though you may find some others to your liking. 9. If you have previous programming experience, try taking an application you've developed before and port it to Python. See how much your code base shrinks compared to its C++ or Java counterpart :) But really, do it just to understand Python on a deeper level. Instead of thinking in the old way, try to think in the Pythonic way. A nice example of this is iteration. Where an iteration counter variable is required in most other languages, Python inherently supports iteration in sequence objects like lists, strings, and dictionary keys; so the syntax is simpler in most cases. -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: Extract zip file from email attachment
> > Could the file like object still be encoded in MIME or something? > Yes it is. You don't need to seek(0). Try this: decoded = email.base64mime.decode(part.get_payload()) fileObj.write(decoded) -Basilisk96 -- http://mail.python.org/mailman/listinfo/python-list
Re: Generic logic/conditional class or library for classification of data
Thanks for the help, guys. Dictionaries to the rescue! Steven, it's certainly true that runtime creation of attributes does not fit well here. At some point, an application needs to come out of generics and deal with logic that is specific to the problem. The example I gave was classification of books, which is relatively easy to understand. The particular app I'm working with deals with specialty piping valves, where the list of rules grows complicated fairly quickly. So, having said that "attributes are not known at design time", it seems that dictionaries are best for the generic core functionality: it's easy to iterate over arbitrary "key, value" pairs without hiccups. I can even reference a custom function by a key, and call it during the iteration to do what's necessary. The input/output dictionaries would dictate that behavior, so that would be the implementation-specific stuff. Easy enough, and the core functionality remains generic enough for re-use. Michael, I looked at the sample snippets at that link, and I'll have to try it out. Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Generic logic/conditional class or library for classification of data
This topic is difficult to describe in one subject sentence... Has anyone come across the application of the simple statement "if (object1's attributes meet some conditions) then (set object2's attributes to certain outcomes)", where "object1" and "object2" are generic objects, and the "conditions" and "outcomes" are dynamic run- time inputs? Typically, logic code for any application out there is hard-coded. I have been working with Python for a year, and its flexibility is nothing short of amazing. Wouldn't it be possible to have a class or library that can do this sort of dynamic logic? The main application of such code would be for classification algorithms which, based on the attributes of a given object, can classify the object into a scheme. In general, conditions for classification can be complex, sometimes involving a collection of "and", "or", "not" clauses. The simplest outcome would involve simply setting a few attributes of the output object to given values if the input condition is met. So each such "if-then" clause can be viewed as a rule that is custom-defined at runtime. As a very basic example, consider a set of uncategorized objects that have text descriptions associated with them. The objects are some type of tangible product, e.g., books. So the input object has a Description attribute, and the output object (a categorized book) would have some attributes like Discipline, Target audience, etc. Let's say that one such rule is "if ( 'description' contains 'algebra') then ('discipline' = 'math', 'target' = 'student') ". Keep in mind that all these attribute names and their values are not known at design time. Is there one obvious way to do this in Python? Perhaps this is more along the lines of data mining methods? Is there a library with this sort of functionality out there already? Any help will be appreciated. -- http://mail.python.org/mailman/listinfo/python-list