Re: [Tutor] OT: we won't eat VB programmers for lunch [Was: How doImake Python draw?]
Nathan, I tried to send you a reply about using the 'turtle' module to do your graphics, did you receive it? I sent it from the gane news archive server and its not there and I haven't seen it on the group so I'm wondering if it ever actually went anywhere?... Alan G. - Original Message - From: "Nathan Pinno" <[EMAIL PROTECTED]> To: "luke" <[EMAIL PROTECTED]>; <[EMAIL PROTECTED]>; "Tutor" Sent: Thursday, July 28, 2005 1:36 AM Subject: Re: [Tutor] OT: we won't eat VB programmers for lunch [Was: How doImake Python draw?] > Now that's worth the mention of VB. Glad I have Python, or many of > my ideas would stay in my head...hehehe > - Original Message - > From: "luke" <[EMAIL PROTECTED]> > To: <[EMAIL PROTECTED]>; "Tutor" > Sent: Wednesday, July 27, 2005 6:28 PM > Subject: Re: [Tutor] OT: we won't eat VB programmers for lunch [Was: > How doI make Python draw?] > > >> hehe. >> <3 malbolge. >> >> Yeah, I actually learned basic as my first language... >> I don't mind it. >> I just don't like it all that much. >> >> ___ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] My first recursive function...
Hi all, Spen too much time coding in VBA, so I'm now paranoid about any code I write. Just playing with my first recursive function, and just wanted your experienced opinions on whether it's likely to blow up in my face, as it all seems to work fine out of the gates, and that makes me a little paranoid. For a given list - x = [ ['tag', 'CYP'], ['level', '1.000'], ['value', '3.286'], ['extra', [ ['country', 'CYP'], ['date', [ ['year', '1431'], ['month', 'april'], ['day', '1'] ] ], ['location', '370'], ['success', 'yes'] ] ] ] My data will always be in format [key:info], the question is whether or not value is a list of [key:info]s also. I then want to turn this into a nested dictionary. So, the given function... def isNested(data): dic = {} for (key, info) in data: if isinstance(info], list) and isinstance(info[0], list): dic[key] = isNested(info) else: dic[key] = info return dic ...seems to work alright, but as I've already run astray of the the isNested(data, dic = {} ) gotcha, I'm just covering my bases here. Are there any other pitfalls with recursion I need to watch for? (I'm also expecting the occasional list that is simply a list of strings, hence the and clause in the isinstance check.) If it's all good, then I'm stoked, as I was writing some very unPythonic code before this. (I had one of those moments when you stare at your code, realise it looks ugly and complicated, and realise that means you're doing it the wrong way. File > New time, I call it.) Thanks for any feedback, Liam -- 'There is only one basic human right, and that is to do as you damn well please.And with it comes the only basic human duty, to take the consequences.' ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] My first recursive function...
Liam Clarke wrote: > Just playing with my first recursive function, and just wanted your > experienced opinions on whether it's likely to blow up in my face, > as it all seems to work fine out of the gates, and that makes me a > little paranoid. > > For a given list - > > x = [ ['tag', 'CYP'], > ['level', '1.000'], > ['value', '3.286'], > ['extra', [ ['country', 'CYP'], ['date', [ ['year', '1431'], > ['month', 'april'], ['day', '1'] ] ], ['location', '370'], ['success', > 'yes'] ] ] ] > > My data will always be in format [key:info], the question is whether or > not value is a list of [key:info]s also. I then want to turn this into > a nested dictionary. [key, info] you mean... > So, the given function... > > def isNested(data): > dic = {} > for (key, info) in data: > if isinstance(info], list) and isinstance(info[0], list): > dic[key] = isNested(info) > else: > dic[key] = info > > return dic > > ...seems to work alright, but as I've already run astray of the the > isNested(data, dic = {} ) gotcha, I'm just covering my bases here. Looks good to me other than the name :-) I would call it toDict() or toNestedDict() maybe; IMO a function named isXXX should just return True or False. > Are there any other pitfalls with recursion I need to watch for? > (I'm also expecting the occasional list that is simply a list of > strings, hence the and clause in the isinstance check.) The biggest pitfall I can think of is that you get into an infinite recursion. This can happen when the recursive call for some reason uses the same arguments as were passed to the caller, or when the exit condition is never met. I think you're fine on both counts here. Does this mean you gave up on pyparsing Dict? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] My first recursive function...
Liam Clarke gmail.com> writes: > Are there any other pitfalls with recursion I need to watch for? Not just infinite recursion, but recursion that exceeds the maximum recursion depth (1000 on my system). You can add a counter parameter to your recursive function and stop recursing if the function finds it has called itself too many times - helps against infinite recursion too. >>> def a(i): ... i += 1 ... if i < 500: ... a(i) >>> a(0) If you try the function above without the if condition, it will generate a RuntimeError. Yours, Andrei ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] My first recursive function...
[key, info] you mean... Oops. That'd be the one. Looks good to me other than the name :-) I would call it toDict() or toNestedDict() maybe; IMO a function named isXXX should just return True or False. Yah, it started off as a boolean return, and then I decided to go for the big one, so to speak, having heard recursion spoken in hushed awe and/or spat out like a swear word. > Are there any other pitfalls with recursion I need to watch for?> (I'm also expecting the occasional list that is simply a list of > strings, hence the and clause in the isinstance check.)The biggest pitfall I can think of is that you get into an infinite recursion. This can happen when the recursive call for some reason uses the same arguments as were passed to the caller, or when the exit condition is never met. I think you're fine on both counts here. Ah, cool. Now I can run this over my full data set and see what interesting exceptions and errors I get. Does this mean you gave up on pyparsing Dict? To some extent. I could use it, but to be honest, the my limited understanding means the effort:effect ratio doesn't make it worth my while. The author of pyparsing helped me out amazingly, my parse time for a full set of data dropped from nearly 6 hours (!) to 3 minutes once he straightened out my grammar, and I think I've taken enough of his time as it is. My problem is a lot of repeated items like merchant = { tag = LAT,...}so to utilise a pp Dict, I'd have to implement functions into the grammar to pop the the tag name to use as a dictionary key, and I'd rather not mess with the grammar any further, in case I break it, or slow it down. :S My understanding of pyparsing is basic, to say the least, so I'm following the path of least resistance here, as I get a list returned which is (now) simple enough to turn into a dictionary. There's some non-consistent 'special cases' in the data structure, which I can handle a lot simpler when I've written the function which is creating my dictionary. Regards, Liam Clarke ___Tutor maillist - Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor-- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Select rows and columns in excel
Danny and John, Thanks for the pointers. As I am leaving the project where I need to do this tomorrow, I don't think I will have time to do this, but thanks for the help anyway. DavidDanny Yoo <[EMAIL PROTECTED]> wrote: On Wed, 27 Jul 2005, David Holland wrote:> I know how to open files in python, however what I want to do is select> some information from an excel spreadsheet and save it as a .dat file.Hi David,Excel spreadsheets are a bit more difficult to work with. They're notplain text files, but have their own internal binary format, so you'llprobably need a library to deal with them. Many people deal with Excel byeither converting the files to something plain-textish, like the 'csv'format, or they get Python to talk to Excel directly.If you can output your excel spreadsheet in 'csv' format, then Python's'csv' module should be useful:http://www.python.org/doc/lib/module-csv.htmland doing the selection should just be a matter of skipping enough rows,in the file, and then paying attention to the part! icular column you want.But if you want to go another route --- to talk closely with Excel ---that might take some more involvement, since it's so tightly bound withWindows programming. The book "Python Programming on Win32" has achapter on how to talk to Excel through Python:http://www.oreilly.com/catalog/pythonwin32/and if you're interested in this approach, you may want to talk with thepython-win32 folks:http://mail.python.org/mailman/listinfo/python-win32Hope this helps! How much free photo storage do you get? Store your holiday snaps for FREE with Yahoo! Photos. Get Yahoo! Photos___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Basic class inheritance
I have this class: >>> class A: ... def __init__(self, blank=False, editable=True, name='foo'): ... self.blank = blank ... self.editable = editable ... self.name = name ... >>> a = A() >>> a.blank, a.editable, a.name (False, True, 'foo') All as expected. Now I want that another class, call it B, inherits all behaviours/attributes except for the attribute blank, that now I want to be False. This should be possible overriding __init__ method no? >>> class B(A): ... def __init__(self, blank=True, editable=True, name='foo'): ... self.blank = blank ... self.editable = editable ... self.name = name ... >>> b = B() >>> b.blank, b.editable, b.name (True, True, 'foo') However, is it possible to achieve this without rewrite the whole __init__ method, but just overriding parts of it? For __init__ very long it would be an unuseful duplication of code.., so I'm sure there is a trivial solution! Can you help to figure it out? Thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] python learning
hi, 1)OB I'm learning for almost a year and half python. this is my first language. I'm fine with classes, definition... But now I'm trying to understand better things as: static method class method and the use of metaclass. Does some one of you knows about a compilations of small snippets showing how things works! an url ? because I'm trying to work with sqlobject, and I have to tell my self that I'm far away of a good comprehension of it.. : ( 2) Sometimes, I do think that it will help a lot, to have such compilations. So that people can scan it, test them very easily. Such snippet shall have some use of them (case that work, case that do not work) some explanation in which can we can use them and so on. For example, what I've learned recently. module.py class test(object): def __init__(self): self.dico={} def setname(self,name, value): self.dico[name]=value def dico(self): return printDico testInstance=test()# * setname=testInstance.setname # ** dico=testInstance.dico # *** in the python interpreter. import module module.setname('key1','value1') module.dico() del module # so I've supposed that the garbage collector will destruct this. from module import dico dico() # tintintammm and badaboum there are still there So I imagine, that when you import this module. ``testInstance'' is created in the object space, but it is not assigned to the namespace. So the only way to destruct such module, will be within the module. I found that such module act has a singleton Ced. -- Cedric BRINER Geneva - Switzerland ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Basic class inheritance
Negroup - wrote: > I have this class: > class A: > > ... def __init__(self, blank=False, editable=True, name='foo'): > ... self.blank = blank > ... self.editable = editable > ... self.name = name > ... > a = A() a.blank, a.editable, a.name > > (False, True, 'foo') > > All as expected. > > Now I want that another class, call it B, inherits all > behaviours/attributes except for the attribute blank, that now I want > to be False. > > This should be possible overriding __init__ method no? > class B(A): > > ... def __init__(self, blank=True, editable=True, name='foo'): > ... self.blank = blank > ... self.editable = editable > ... self.name = name > ... > b = B() b.blank, b.editable, b.name > > (True, True, 'foo') > > However, is it possible to achieve this without rewrite the whole > __init__ method, but just overriding parts of it? The usual way to do this is to forward to the __init__() method of the superclass for the common part. In your case you are just specializing the default arguments so all you have to do is pass the args to A.__init__(): class B(A): def __init__(self, blank=True, editable=True, name='foo'): A.__init__(self, blank, editable, name) Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Basic class inheritance
> > However, is it possible to achieve this without rewrite the whole > > __init__ method, but just overriding parts of it? > > The usual way to do this is to forward to the __init__() method of the > superclass for the common part. In your case you are just specializing the > default arguments so all you have to do is pass the args to A.__init__(): > > class B(A): > def __init__(self, blank=True, editable=True, name='foo'): > A.__init__(self, blank, editable, name) > I thought such kind of thing should be writted like: class A(object): def __init__(self, blank=False, editable=True, name='foo'): self.blank = blank self.editable = editable self.name = name class B(A): def __init__(self, blank=True, editable=True, name='foo'): super(B, self).__init__(blank, editable, name) Ced. -- Cedric BRINER Geneva - Switzerland ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Basic class inheritance
Cedric BRINER wrote: >>>However, is it possible to achieve this without rewrite the whole >>>__init__ method, but just overriding parts of it? >> >>The usual way to do this is to forward to the __init__() method of the >>superclass for the common part. In your case you are just specializing the >>default arguments so all you have to do is pass the args to A.__init__(): >> >>class B(A): >> def __init__(self, blank=True, editable=True, name='foo'): >>A.__init__(self, blank, editable, name) >> > > > I thought such kind of thing should be writted like: > class A(object): > def __init__(self, blank=False, editable=True, name='foo'): > self.blank = blank > self.editable = editable > self.name = name > > class B(A): > def __init__(self, blank=True, editable=True, name='foo'): > super(B, self).__init__(blank, editable, name) Yes, that is the more modern way to do it for new-style classes. In the original example, class A does not inherit from object so I used the older style. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Basic class inheritance
[cut] > > Yes, that is the more modern way to do it for new-style classes. In the > original example, class A does not inherit from object so I used the older > style. > Thanks guys for your answers, it's clear (even if I wouldn't be able to figure it out by my own). About old style/new style classes, do you suggest some *simple* reading? Documents found here http://www.python.org/doc/newstyle.html are too technical for me now.. TIA ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] dictionary question
The following code: print str(dict(a=1,b=2,c=-1)) print str(dict(a=1,c=-1,b=2)) print str(dict(c=-1,a=1,b=2)) print str(dict(b=2,a=1,c=-1)) print str(dict(b=2,c=-1,a=1)) print print str(dict(a=1,b=2,c=23)) print str(dict(a=1,c=23,b=2)) print str(dict(c=23,a=1,b=2)) print str(dict(b=2,a=1,c=23)) print str(dict(b=2,c=23,a=1)) print print str(dict(a=1,b=2,c='booga')) print str(dict(a=1,c='booga',b=2)) print str(dict(c='booga',a=1,b=2)) print str(dict(b=2,a=1,c='booga')) print str(dict(b=2,c='booga',a=1)) Produces: {'a': 1, 'c': -1, 'b': 2} {'a': 1, 'c': -1, 'b': 2} {'a': 1, 'c': -1, 'b': 2} {'a': 1, 'c': -1, 'b': 2} {'a': 1, 'c': -1, 'b': 2} {'a': 1, 'c': 23, 'b': 2} {'a': 1, 'c': 23, 'b': 2} {'a': 1, 'c': 23, 'b': 2} {'a': 1, 'c': 23, 'b': 2} {'a': 1, 'c': 23, 'b': 2} {'a': 1, 'c': 'booga', 'b': 2} {'a': 1, 'c': 'booga', 'b': 2} {'a': 1, 'c': 'booga', 'b': 2} {'a': 1, 'c': 'booga', 'b': 2} {'a': 1, 'c': 'booga', 'b': 2} Could I rely on creating hashes to use as keys in bsddb this way? If I create a dictionary with the same keys, will it str the same way? Thanks! -- *** See there, that wasn't so bad. *** ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Problem with pgbd & datetime
On Wed, Jul 27, 2005 at 07:13:49PM -0400, Don Parris wrote: > pg/pgdb are both part of the PyGreSQL distribution. You can choose > whichever you want to use, but pgdb supports the 2.0 API, whereas > (according to the readme) pg does not. I will try pg when I get back > to my box tonight, but would prefer to use pgdb. I use pgdb as well, for the same reason. > All of this should have been configured properly when I installed > SUSE Linux 9.2 last Fall. The MySQLdb module works fine - the pgdb > should as well. Perhaps I should post this over on the DB Sig list. Debian lists a package called python-egenix-mxdatetime as a dependency for python-pygresql, and that in turn depends on python-egenix-mxtools. I believe you need to install these modules for pygresql to work, as mxDateTime is not the same as datetime. The site for mxDateTime is http://www.egenix.com/files/python/mxDateTime.html if you need to install it manually, but there should be a SUSE package for it. *Quick look through SUSE site.* Yep, here it is: http://www.novell.com/products/linuxpackages/professional/python-egenix-mx-base.html I hope that gets it working. gsf ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dictionary question
David Driver wrote: > If I > create a dictionary with the same keys, will it str the same way? This behaviour is not guaranteed and I wouldn't depend on it. It can break if any other operations have happened on the dict; for example >>> d=dict(a=1,b=2,c=23) >>> str(d) "{'a': 1, 'c': 23, 'b': 2}" >>> for i in range(100): ... d[i]=i ... >>> for i in range(100): ... del d[i] ... >>> str(d) "{'c': 23, 'b': 2, 'a': 1}" The order could also change between Python versions if the internal implementation of dict changes. How about >>> str(sorted(d.items())) "[('a', 1), ('b', 2), ('c', 23)]" Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] matplotlib (pylab) backends
On Wed, 27 Jul 2005, Pujo Aji wrote: > I write a program which launch pylab from windows GUI (using wxpython). > I found some problem here. > > If I use the default backends program in matplotlibrc which is TkAgg > I have this result: > 1. I click button the plot is showed > 2. I close the plot > 3. I click the button to show the plot the second time. it shows the > plot but I can't closed it (it hangs. Hi Pujo, Without seeing what you've actually written, I'm not sure how effectively we can help you here. If you can, point us to code that we can use to reliably reproduce your problem. Otherwise, we really can't say at all what's happening here. If I were forced to guess, I guess that some resource is not being properly set to the initial state when the plot is first closed. Since many of us here have little experience with the matplotlib package, you may want to check with someone on the matplotlib-users mailing list to see if someone there can help you: http://lists.sourceforge.net/lists/listinfo/matplotlib-users ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How do I make Python draw?
I found my message to Nathan, looks like I pressed the wrong reply button in the Outlook Express newsreader. I thought I'd forward it to the list since: a) we don't often discuss the turtle module and b) I ask a question at the end that I'd like an answer to! :-) Alan G. - Original Message - From: "Alan G" <[EMAIL PROTECTED]> To: "Nathan Pinno" <[EMAIL PROTECTED]> Sent: Wednesday, July 27, 2005 10:15 PM Subject: Re: How do I make Python draw? How do I make Python draw a shape? e.g. a triangle Is there a specific module that I have to call, or what is the command(s)? There are several options, most involve using a GUI framework to create a Canvas widget and drawing inside that. However for your purposes a more interesting route might be to try the Python turtle module, it does the GUI bits for you and allows you to draw graphics by commanding a 'turtle' pen to move on the screen. If you know logo or any other turtle implementation it will be easy, if not an interesting lrearning experience and a fairly easy wauy of drawing basic geometric shapes... You can play with turtle by importing it at a >>> prompt and issueing commands. Here is a session to draw an equilateral triangle: import turtle as t p = t.Pen() p.reset() p.down() for side in range(3): ...p.forward(100) ...p.left(120) ... And attached is a jpeg of the resultant canvas. (The righward horizontal line seems to be a buglet in the module - does anyone know how to get rid of it?) HTH, Alan G. <> ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] try except continue
hey guys, so I've been trying to get my head around the try except statement in Python, and ideally what I'd like is for my procedural program, when it runs through its steps and encounters an error, to log the error and pick up where it left off and keep going. According to this link, 'continue' is allowed within an except or finally: http://python.active-venture.com/ref/continue.html I tried to run the following code, expecting to catch a NameError and continuing on: def someFunc00(): someModulo = 6%2 print someModulus def someFunc01(): print "yeah!" def someFunc02(): print "baby let's go" def someFunc03(): someInt = 2+2 print "someInt is: ", someInt def someProcedure(): someFunc00() someFunc01() someFunc02() someFunc03() # copy and paste the following into IDLE, which on my machine often #crashes for an unknown reason, so I've taken to creating a harness that #imports the required library and then runs the desired programs to test #the desired behavior if __name__ == "__main__": import testTryCatch try: testTryCatch.someProcedure() except: print "encountered error" continue but I get the following error: SyntaxError: 'continue' not properly in loop What am I doing wrong ? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Basic class inheritance
>> Now I want that another class, call it B, inherits all >> behaviours/attributes except for the attribute blank, that now I >> want >> to be False. > class B(A): > def __init__(self, blank=True, editable=True, name='foo'): >A.__init__(self, blank, editable, name) except that instead of passimng blank to A.__init__ you should pass False. That way blank will always be False as required! ie: A.__init__(self, False, editable, name) HTH, Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] try except continue
On Thu, 28 Jul 2005 [EMAIL PROTECTED] wrote: > import testTryCatch > try: > testTryCatch.someProcedure() > except: > print "encountered error" > continue > > but I get the following error: > > SyntaxError: 'continue' not properly in loop > > What am I doing wrong ? Hi Tpc, What did you expect to happen when we hit the continue statement? It'll help to know what you wanted to happen, so that we can better understand the problem. According to: http://www.python.org/doc/ref/continue.html 'continue' is only effective if we're in a loop, so the error message is perfectly true. So I think we need to know more about what you are trying to do. Best of wishes! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Basic class inheritance
Alan G wrote: >>> Now I want that another class, call it B, inherits all >>> behaviours/attributes except for the attribute blank, that now I want >>> to be False. > > >> class B(A): >> def __init__(self, blank=True, editable=True, name='foo'): >>A.__init__(self, blank, editable, name) > > > except that instead of passimng blank to A.__init__ you should pass False. > That way blank will always be False as required! ie: > > A.__init__(self, False, editable, name) It's not really clear what the OP wants - whether blank should always be False, or have a default value of False. Actually the example shows blank having a default value of True for B's which makes more sense than the text since the default value of blank for A's is False. Anyway, if you want to change the default value do it the way I showed originally (above); if you want blank to always be False (or True) you should remove the parameter from the definition of B.__init__() like this: class B(A): def __init__(self, editable=True, name='foo'): A.__init__(self, True, editable, name) Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] range()-like function to generate aa, ... az, ..., zz ?
I'm looking for a range()-like function which could generate a list of character-oriented tokens, like to iterate over all two-character sequences like: pseudorange('aa', 'zz') would generate: aa, ab, ..., az, ba, ..., za, ..., zz range() doesn't do character iteration, and I'm sure I could write a dumb function to do it, but was wondering if there was something more generic -- e.g., later I might want pseudorange('aaa', 'mmm') Anyway, is there a function to iterate through a range of character strings similar to this? Thanks. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] range()-like function to generate aa, ... az, ..., zz ?
On Thu, 2005-07-28 at 13:59 -0400, Chris Shenton wrote: > I'm looking for a range()-like function which could generate a list of > character-oriented tokens, like to iterate over all two-character > sequences like: > > pseudorange('aa', 'zz') would generate: > aa, ab, ..., az, ba, ..., za, ..., zz > > range() doesn't do character iteration, and I'm sure I could write a > dumb function to do it, but was wondering if there was something more > generic -- e.g., later I might want > > pseudorange('aaa', 'mmm') > > Anyway, is there a function to iterate through a range of character > strings similar to this? > > Thanks. My small controbution to PyTuyo: >>> twoLetterSequence = [ "%c%c" % (x, y) for x in range(ord('a'), ord('z')+1) for y in range(ord('a'), ord('z')+1)] Ziyad. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Regular expression error
Hello, I'm using regular expressions to check if arguments of a function are valid. When I run the code below, I get an error. Basically, what the regular expression "should" expect is either an integer, or an integer followed by a letter (string). I convert the tested argument to a string to make sure. Below is the code. # Create regular expression to match oPattern = re.compile( r"(\d+|\d+\D)", re.IGNORECASE ) # Iterate provided arguments for oArg in aArgs: # Attempt to match the argument to the regular expression oMatch = re.match( str( oArg ), 0 ) The error I get is this: #ERROR : Traceback (most recent call last): # File "
Re: [Tutor] Regular expression error
Bernard Lebel wrote: > Hello, > > I'm using regular expressions to check if arguments of a function are > valid. When I run the code below, I get an error. > > Basically, what the regular expression "should" expect is either an > integer, or an integer followed by a letter (string). I convert the > tested argument to a string to make sure. Below is the code. > > > > # Create regular expression to match > oPattern = re.compile( r"(\d+|\d+\D)", re.IGNORECASE ) This will match a string of digits followed by any non-digit, is that what you want? If you want to restrict it to digits followed by a letter you should use r"(\d+|\d+[a-z])" Also this will match something like 123A456B, if you want to disallow anything after the letter you need to match the end of the string: r"(\d+|\d+[a-z])$" > > # Iterate provided arguments > for oArg in aArgs: > > # Attempt to match the argument to the regular expression > oMatch = re.match( str( oArg ), 0 ) The problem is you are calling the module (re) match, not the instance (oPattern) match. re.match() expects the second argument to be a string. Just use oMatch = oPattern.match( str( oArg ), 0 ) The hint in the error is "expected string or buffer". So you are not giving the expected argument types which should send you to the docs to check... Kent > > > > The error I get is this: > > #ERROR : Traceback (most recent call last): > # File "
Re: [Tutor] Regular expression error
On 7/28/05, Kent Johnson <[EMAIL PROTECTED]> wrote: > This will match a string of digits followed by any non-digit, is that what > you want? If you want to restrict it to digits followed by a letter you > should use > r"(\d+|\d+[a-z])" > > Also this will match something like 123A456B, if you want to disallow > anything after the letter you need to match the end of the string: > r"(\d+|\d+[a-z])$" Nice, thanks a bunch. > The problem is you are calling the module (re) match, not the instance > (oPattern) match. re.match() expects the second argument to be a string. Just > use > oMatch = oPattern.match( str( oArg ), 0 ) > > The hint in the error is "expected string or buffer". So you are not giving > the expected argument types which should send you to the docs to check... > > Kent You're right. Thanks for the heads up. Bernard ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] try except continue
hi Danny, well from my previous message: ideally what I'd like is for my procedural program, when it runs through its steps and encounters an error, to log the error and pick up where it left off and keep going. so for the execution of someProcedure(), I want it to print the error and continue running through the rest of someProcedure(). Is this possible ? On 7/28/05, Danny Yoo <[EMAIL PROTECTED]> wrote: > > > Hi Tpc, > > What did you expect to happen when we hit the continue statement? It'll > help to know what you wanted to happen, so that we can better understand > the problem. > > > According to: > > http://www.python.org/doc/ref/continue.html > > 'continue' is only effective if we're in a loop, so the error message is > perfectly true. So I think we need to know more about what you are trying > to do. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] try except continue
> program, when it runs through its steps and encounters an error, to > log > the error and pick up where it left off and keep going. According > to this > link, 'continue' is allowed within an except or finally: Thats true but only if the try block is inside a loop. Consider: error = True def f(): if error: raise ValueError else: print 'In f()' def g(): print 'In g()' while True: try: f() g() except ValueError: error = False continue continue will cause the *next* iteration of the loop to start. Thus the first time round the error is raised in f() and the code jumps to the except clause and from there back to the top of the loop, effectively missing g() out, then next time through no error is raised so both f() and g() are called. If you really want to ignore the error and move to the next line you have to do a try:except on every line (or function call) try: f() except: pass try: g() except: pass Or put the functions in a list if their parameter lists are null or identical: funcs = [f,g] for func in funcs: try: func() except: continue But all of that's bad practice since who knows what nasties you might be allowing through. Its usually possible to structure code to avoid such horrors! HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] range()-like function to generate aa, ... az, ..., zz ?
Is this what you want? >>> import string >>> ltrs = string.lowercase >>> [''.join([a,b]) for a in ltrs for b in ltrs] HTH, Alan G. - Original Message - From: "Chris Shenton" <[EMAIL PROTECTED]> To: Sent: Thursday, July 28, 2005 6:59 PM Subject: [Tutor] range()-like function to generate aa, ... az, ..., zz ? > I'm looking for a range()-like function which could generate a list > of > character-oriented tokens, like to iterate over all two-character > sequences like: > > pseudorange('aa', 'zz') would generate: > aa, ab, ..., az, ba, ..., za, ..., zz > > range() doesn't do character iteration, and I'm sure I could write > a > dumb function to do it, but was wondering if there was something > more > generic -- e.g., later I might want > > pseudorange('aaa', 'mmm') > > Anyway, is there a function to iterate through a range of character > strings similar to this? > > Thanks. > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How do I make Python draw?
Quoting Alan G <[EMAIL PROTECTED]>: > I found my message to Nathan, looks like I pressed the wrong > reply button in the Outlook Express newsreader. I thought I'd > forward it to the list since: > a) we don't often discuss the turtle module and Wow, I never knew this existed... > > (The righward horizontal line seems to be a buglet in the module > > - does anyone know how to get rid of it?) I don't get that --- when I run that code, I just get a triangle only... -- John. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] try except continue
On Thu, 28 Jul 2005 [EMAIL PROTECTED] wrote: > ideally what I'd like is for my procedural program, when it runs through > its steps and encounters an error, to log the error and pick up where it > left off and keep going. > > so for the execution of someProcedure(), I want it to print the error > and continue running through the rest of someProcedure(). Is this > possible ? Hi Tpc, I think there's some confusion about the role of 'continue'; it's doesn't have anything to do with exception handling. The following example might help: ## >>> def showDivision(n): ... try: ... for i in range(10): ... print i, i / n ... except ZeroDivisionError: ... print "Huh?!" ... print "All done!" ... >>> showDivision(5) 0 0 1 0 2 0 3 0 4 0 5 1 6 1 7 1 8 1 9 1 All done! >>> showDivision(0) 0 Huh?! All done! >>> ## Does this help to clear thing up? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Problem with pgbd & datetime
On 7/28/05, Gabriel Farrell <[EMAIL PROTECTED]> wrote: > On Wed, Jul 27, 2005 at 07:13:49PM -0400, Don Parris wrote: > > pg/pgdb are both part of the PyGreSQL distribution. You can choose > > whichever you want to use, but pgdb supports the 2.0 API, whereas > > (according to the readme) pg does not. I will try pg when I get back > > to my box tonight, but would prefer to use pgdb. > > I use pgdb as well, for the same reason. > > > All of this should have been configured properly when I installed > > SUSE Linux 9.2 last Fall. The MySQLdb module works fine - the pgdb > > should as well. Perhaps I should post this over on the DB Sig list. > > Debian lists a package called python-egenix-mxdatetime as a dependency > for python-pygresql, and that in turn depends on > python-egenix-mxtools. I believe you need to install these modules > for pygresql to work, as mxDateTime is not the same as datetime. The > site for mxDateTime is > http://www.egenix.com/files/python/mxDateTime.html if you need to > install it manually, but there should be a SUSE package for it. > *Quick look through SUSE site.* Yep, here it is: > http://www.novell.com/products/linuxpackages/professional/python-egenix-mx-base.html > > I hope that gets it working. > > gsf > ___ I would have thought it would be part of the SUSE install. Thanks for the URL. I've downloaded the egenix package from their website, and will try to get it installed this evening. Don -- DC Parris GNU Evangelist http://matheteuo.org/ [EMAIL PROTECTED] "Hey man, whatever pickles your list!" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] try except continue
hi Alan and Danny, I think I understand what you guys are saying. I don't believe I am ignoring the error. Ideally what I'd like is for the procedural program to run through its steps and if it encounters an error, to log the error and pick up where it left off and keep going. I gather you think that is bad practice, but how bad ? If I log the error so that I can go back and decipher what input caused, say, the UnboundLocalError, and keep running the rest of my program, then I feel that is better than running through the program and upon encountering an error, stopping the program dead in its tracks. My program parses documents from two different sources, and currently if the template for one source changes, then the other source's documents are not parsed. What I'd like is if an error is encountered, the input (document) that caused the error is logged, and the rest of the documents are parsed without stopping the "assembly line." I see the continue statement as a way for me to do this, and thus intimately linked with exception handling. I have a hard time figuring out why you think this is bad practice. On 7/28/05, Danny Yoo <[EMAIL PROTECTED]> wrote: > Hi Tpc, > > I think there's some confusion about the role of 'continue'; it's doesn't > have anything to do with exception handling. > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] try except continue
> I see the continue statement as a way for me to do this, and thus > intimately linked with exception handling. Hi Tpc, I think you're getting too caught up with the word "continue" and its concept as you use it in human language, rather than what it really does in the Python language. I should have written an example of 'continue' usage to make things more explicit. Here is a simple example: ### """Filters empty lines out of standard input.""" import sys for line in sys.stdin: if not line.strip(): continue print line ## This is a small program that filters out empty lines from standard input. The 'continue' statement causes us to immediately jump back to the beginning of the loop and to keep going. In Python, continue is intrinstically tied with Python's looping operations (while/for). http://www.python.org/doc/ref/continue.html It has very little to do with exception handling, except where the footnotes mentions certain artificial limitations in using it within an exception-handling block. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor