From tpc at csua.berkeley.edu Wed Sep 1 08:35:02 2004 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Wed Sep 1 08:35:07 2004 Subject: [Tutor] list of floats, strange behavior Message-ID: <20040831233251.F17091-100000@localhost.name> hi everybody, I was wondering if someone could help me understand why IDLE seems to expand the largest value in a series of floating points I decided to put in a list: >>> list01 = [.1028, .1248, .0998, .1101, .1062] >>> list01.sort() >>> list01 [0.0998, 0.1028, 0.1062, 0.1101, 0.12479999999999999] I don't particularly want that value expanded like that. From python at bernardlebel.com Wed Sep 1 10:18:34 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Wed Sep 1 10:18:55 2004 Subject: [Tutor] list of floats, strange behavior References: <20040831233251.F17091-100000@localhost.name> Message-ID: <005001c48ffc$4abe42d0$0d01a8c0@studioaction.local> Hi, In the tutorial (I think) from the Python docs there is an explanation about this problem, wich is inherent to floating point numbers in computers. Very interesting read. Cheers Bernard ----- Original Message ----- From: To: Sent: Wednesday, September 01, 2004 8:35 AM Subject: [Tutor] list of floats, strange behavior > > hi everybody, I was wondering if someone could help me understand why IDLE > seems to expand the largest value in a series of floating points I decided > to put in a list: > > >>> list01 = [.1028, .1248, .0998, .1101, .1062] > >>> list01.sort() > >>> list01 > [0.0998, 0.1028, 0.1062, 0.1101, 0.12479999999999999] > > I don't particularly want that value expanded like that. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > From kent_johnson at skillsoft.com Wed Sep 1 13:02:02 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Sep 1 13:02:11 2004 Subject: [Tutor] Drive listing In-Reply-To: <000701c48f9e$40dac3a0$96c48f52@allmycore> References: <000701c48f9e$40dac3a0$96c48f52@allmycore> Message-ID: <6.1.0.6.0.20040901065949.028f3710@mail4.skillsoft.com> You need win32all, get it here http://starship.python.net/crew/mhammond/ Then see here http://groups.google.com/groups?selm=mailman.1011113008.15423.python-list%40python.org and here http://insom.me.uk/blog/Tech/Python/getdrives.writeback Kent At 11:05 PM 8/31/2004 +0200, Ole Jensen wrote: >How is it possiple to list the drives on a current system? is there som >module that will output this some thing like listdrives() ? I have >browsed the Global Module Index for relating functions but haven't found >anything. > >Or would I need to create my own function? something similiar to. > >Not testet: >from os.path import exists >from string import ascii_lowercase as lcase > >def drive(): > for i in lcase: > drive = i + ':/' > drives = [] > if exists(drive): > drives.append(drive) > return drives > > >Ole Jensen > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From padmaja at agere.com Wed Sep 1 13:50:28 2004 From: padmaja at agere.com (Jayanthi, Satya Padmaja (Satya Padmaja)) Date: Wed Sep 1 13:50:38 2004 Subject: [Tutor] Python - TCL Interaction Message-ID: Hi : I am using Tkinker to interface Python to TCL. I am able to call tcl APIs, pass the input parameters as strings to the TCL APIs, fetch the return values from the TCL APIs etc... From the python code. Now, the problem is I have to pass a two dimensional list (the elements of the list are also lists) to the tcl file. How can I do it ? If I simply use the "%s" option, the error that is thrown is "_tkinter.TclError: invalid command name "'apple',"" import Tkinter root = Tkinter.Tk() root.tk.eval('source test_tcl_file.tcl') arr = [["apple", "mango", "orange"], ["rose", "jasmine", "marigold"]] root.tk.eval('test_tcl_func %s', %(list)) I have tried many tricks.Tried setting the array in the python file etc. root.tk.eval('global arr; lappend arr %s' %(s)). But nothing works. Can anyone of you please help me ? Thanks and Regards, Padmaja -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040901/b3378d2c/attachment.htm From python at pointcontrol.com Wed Sep 1 14:09:04 2004 From: python at pointcontrol.com (Barry Tice) Date: Wed Sep 1 14:09:07 2004 Subject: [Tutor] list of floats, strange behavior In-Reply-To: <005001c48ffc$4abe42d0$0d01a8c0@studioaction.local> References: <20040831233251.F17091-100000@localhost.name> <005001c48ffc$4abe42d0$0d01a8c0@studioaction.local> Message-ID: <1094040543.2430.5.camel@localhost.localdomain> Yes, the explanation of floating-point rounding errors is in Appendix B of the tutorial. The long and short of it is, floating point numbers are stored as binary fractions. Consider that in a base-three number system, the number that in decimal we refer to as 1/3 would be 0.1. In decimal, it's 0.3333333333(etc.). There is no exact value in base 10 for something that's easy to represent in base 3. Similarly, there are many things that can be represented in base 10 that can't be exactly specified in binary, base 2. (0.1, for example.) So based on the underlying C representation, Python makes its best guess and comes up with the closest number it can. -- b.r.t. On Wed, 2004-09-01 at 03:18, Bernard Lebel wrote: > Hi, > > In the tutorial (I think) from the Python docs there is an explanation about > this problem, wich is inherent to floating point numbers in computers. > Very interesting read. > > > Cheers > Bernard > > ----- Original Message ----- > From: > To: > Sent: Wednesday, September 01, 2004 8:35 AM > Subject: [Tutor] list of floats, strange behavior > > > > > > hi everybody, I was wondering if someone could help me understand why IDLE > > seems to expand the largest value in a series of floating points I decided > > to put in a list: > > > > >>> list01 = [.1028, .1248, .0998, .1101, .1062] > > >>> list01.sort() > > >>> list01 > > [0.0998, 0.1028, 0.1062, 0.1101, 0.12479999999999999] > > > > I don't particularly want that value expanded like that. > > From alan.gauld at blueyonder.co.uk Wed Sep 1 14:23:54 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Sep 1 14:23:07 2004 Subject: [Tutor] list of floats, strange behavior References: <20040831233251.F17091-100000@localhost.name> Message-ID: <03be01c4901e$8c11c550$6401a8c0@xp> > hi everybody, I was wondering if someone could help me understand why IDLE > seems to expand the largest value in a series of floating points It doesn't expand the largest value as such it just expands to the best accuracy that it can provide. YThis is a problem with the way computers store floating point numbers. Its related to the fact that one third in decimal is 0.3333333...forever. In other words you can't exactly represent it in decimal. The same happens in binary. However if you want to print it out you have lots of options for tidying it up. The default print will tidy it a bit, and for more control you can use the format string: >>> print "%7.5f" % 0.12479999999999999 0.12480 ie 7 characters long with 5 decimal places... > >>> list01 > [0.0998, 0.1028, 0.1062, 0.1101, 0.12479999999999999] Trying print: >>> print list01[-1] 0.1248 HTH, Alan G From blk20 at cam.ac.uk Wed Sep 1 14:33:30 2004 From: blk20 at cam.ac.uk (blk20) Date: Wed Sep 1 14:25:16 2004 Subject: [Tutor] Introduction In-Reply-To: <1094040543.2430.5.camel@localhost.localdomain> References: <20040831233251.F17091-100000@localhost.name> <005001c48ffc$4abe42d0$0d01a8c0@studioaction.local> <1094040543.2430.5.camel@localhost.localdomain> Message-ID: <1094042010.2348.99.camel@localhost> Hi there, my name is Bernhard Krieger. I am a social anthropologist undertaking research on free software and people involved in free software. I want to start programming and was pointed to python as a good beginner's language. I am reading 'Learning Python' by Mark Luty and David Ascher. It is fascinating, even it sometimes takes me a while to keep all the information;) Is there anything else you would recommend me to learn Python? Cheers, --Bernhard From python at pointcontrol.com Wed Sep 1 14:37:57 2004 From: python at pointcontrol.com (Barry Tice) Date: Wed Sep 1 14:38:04 2004 Subject: [Tutor] Introduction In-Reply-To: <1094042010.2348.99.camel@localhost> References: <20040831233251.F17091-100000@localhost.name> <005001c48ffc$4abe42d0$0d01a8c0@studioaction.local> <1094040543.2430.5.camel@localhost.localdomain> <1094042010.2348.99.camel@localhost> Message-ID: <1094042276.2430.12.camel@localhost.localdomain> Guido's Python tutorial is a good place to start, though I imagine it's probably less complete than any book you purchased. From there, reading through the reference manual for the modules you expect to use the most, while keeping the interpreter running for experiments, will teach you a great deal. I've always found the best way to learn a language is to have a project you want to do and dive in and get your hands dirty. This sometimes involves coming up with smaller projects to accomplish first -- say if your main project requires XML, you might want to have a smaller starter-project devoted to working out the intricacies of XML before you spend too much time going in a misguided direction on your main project. -- b.r.t. On Wed, 2004-09-01 at 07:33, blk20 wrote: > Hi there, > > my name is Bernhard Krieger. I am a social anthropologist undertaking > research on free software and people involved in free software. > > I want to start programming and was pointed to python as a good > beginner's language. I am reading 'Learning Python' by Mark Luty and > David Ascher. It is fascinating, even it sometimes takes me a while to > keep all the information;) > > Is there anything else you would recommend me to learn Python? > > Cheers, > --Bernhard > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From T.Chern at unibas.ch Wed Sep 1 14:52:57 2004 From: T.Chern at unibas.ch (Tzu-Ming Chern) Date: Wed Sep 1 14:53:06 2004 Subject: [Tutor] Suggestions as to how to read a file in paragraphs Message-ID: Dear Python tutors, What is a more efficient way to read a file and split it into paragraphs and just print those paragraphs which match a particular condition? The inefficient way is to read the whole file into one string and then split it, but this becomes problematic with larger files. Any suggestions on a more efficient approach or is there a module available? Cheers, tzuming From adam at monkeez.org Wed Sep 1 14:54:28 2004 From: adam at monkeez.org (adam) Date: Wed Sep 1 14:54:31 2004 Subject: [Tutor] String to integer? Message-ID: <27761.217.206.168.163.1094043268.spork@webmail.monkeez.org> I have a list which holds all the letters of the alphabet. I want to create a button (wxPython) for each of these letters and then give the button an ID (count - which is an integer). However, I would like the ID to be driven by the list (which is string). See code below. What's the easiest way of creating an integer which is based on a value of a letter? I really don't mind if it was based on the ascii code, or another equivalent. Thanks in advance. Adam alphabet = ['a','b','c','d','e' ... and so on. for i in alphabet: count = count + 1 bmp = wxBitmap('alphabet_graphics/' + i + '.bmp', wxBITMAP_TYPE_BMP) self.grafic =wxBitmapButton(self, count,bmp,wxPoint(160,20), wxSize(bmp.GetWidth()+10,bmp.GetHeight()+10)) self.sizer2.Add(self.grafic,1,wxEXPAND) EVT_BUTTON(self, count, self.ButtonPushed) From python at bernardlebel.com Wed Sep 1 15:00:36 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Wed Sep 1 15:00:44 2004 Subject: [Tutor] String to integer? References: <27761.217.206.168.163.1094043268.spork@webmail.monkeez.org> Message-ID: <00b201c49023$ad72bf10$0d01a8c0@studioaction.local> Personally I'd consider using a dictionary for that. Assign the letter (the key) to the number (the value). Cheers Bernard ----- Original Message ----- From: "adam" To: Sent: Wednesday, September 01, 2004 2:54 PM Subject: [Tutor] String to integer? > I have a list which holds all the letters of the alphabet. I want to > create a button (wxPython) for each of these letters and then give the > button an ID (count - which is an integer). However, I would like the ID > to be driven by the list (which is string). See code below. > > What's the easiest way of creating an integer which is based on a value of > a letter? I really don't mind if it was based on the ascii code, or > another equivalent. > > Thanks in advance. > > Adam > > alphabet = ['a','b','c','d','e' ... and so on. > for i in alphabet: > count = count + 1 > bmp = wxBitmap('alphabet_graphics/' + i + '.bmp', wxBITMAP_TYPE_BMP) > self.grafic =wxBitmapButton(self, count,bmp,wxPoint(160,20), > wxSize(bmp.GetWidth()+10,bmp.GetHeight()+10)) > self.sizer2.Add(self.grafic,1,wxEXPAND) > EVT_BUTTON(self, count, self.ButtonPushed) > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From python at bernardlebel.com Wed Sep 1 15:16:31 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Wed Sep 1 15:16:39 2004 Subject: [Tutor] Listing function arguments Message-ID: <00cb01c49025$e6b81570$0d01a8c0@studioaction.local> Hello, Is there a way to list the arguments that a variable is accepting? For instance, the first line of a function looks like this: def cmcopy( aClients = [], sSource = '', sTarget = '', iSource = 0 ): So I'd like to know the argument names, for 1- Know the order at wich the arguments must be passed 2- Know what variables to supply for arguments I don't know if I missed something in the documentation... Thanks Bernard From kent_johnson at skillsoft.com Wed Sep 1 15:16:48 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Sep 1 15:16:52 2004 Subject: [Tutor] Introduction In-Reply-To: <1094042010.2348.99.camel@localhost> References: <20040831233251.F17091-100000@localhost.name> <005001c48ffc$4abe42d0$0d01a8c0@studioaction.local> <1094040543.2430.5.camel@localhost.localdomain> <1094042010.2348.99.camel@localhost> Message-ID: <6.1.0.6.0.20040901091604.0287c620@mail4.skillsoft.com> You can read my recommendations here: http://personalpages.tds.net/~kent37/Python/PythonResources.html Kent At 02:33 PM 9/1/2004 +0200, you wrote: >Hi there, > >my name is Bernhard Krieger. I am a social anthropologist undertaking >research on free software and people involved in free software. > >I want to start programming and was pointed to python as a good >beginner's language. I am reading 'Learning Python' by Mark Luty and >David Ascher. It is fascinating, even it sometimes takes me a while to >keep all the information;) > >Is there anything else you would recommend me to learn Python? > >Cheers, >--Bernhard > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From bwinton at latte.ca Wed Sep 1 15:27:12 2004 From: bwinton at latte.ca (Blake Winton) Date: Wed Sep 1 15:27:15 2004 Subject: [Tutor] String to integer? In-Reply-To: <27761.217.206.168.163.1094043268.spork@webmail.monkeez.org> References: <27761.217.206.168.163.1094043268.spork@webmail.monkeez.org> Message-ID: <4135CE30.3090207@latte.ca> adam wrote: > What's the easiest way of creating an integer which is based on a value of > a letter? I really don't mind if it was based on the ascii code, or > another equivalent. >>> ord('a') 97 >>> chr(97) 'a' >>> ord('ab') Traceback (most recent call last): File "", line 1, in ? TypeError: ord() expected a character, but string of length 2 found (Putting on my user-hat for a second, you _really_ want 26 buttons on a single form?!? That's probably going to be confusing to look at. Is there another way you could get the user's input?) Later, Blake. From kent_johnson at skillsoft.com Wed Sep 1 15:30:12 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Sep 1 15:30:15 2004 Subject: [Tutor] Suggestions as to how to read a file in paragraphs In-Reply-To: References: Message-ID: <6.1.0.6.0.20040901091752.0287c390@mail4.skillsoft.com> You could read the file by lines and accumulate lines in a list until you find a paragraph break. Then look at the accumulated lines and see if you want to print it. Something like this (assuming a blank line is a paragraph break): linesInPara = [] for line in f: if not line.strip(): processParagraph(linesInPara) linesInPara = [] else: linesInPara.append(line) if linesInPara: processParagraph(linesInPara) At 02:52 PM 9/1/2004 +0200, Tzu-Ming Chern wrote: >Dear Python tutors, > >What is a more efficient way to read a file and split it into paragraphs >and just print those paragraphs which match a particular condition? > >The inefficient way is to read the whole file into one string and then >split it, but this becomes problematic with larger files. Any suggestions >on a more efficient approach or is there a module available? > >Cheers, >tzuming > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From rha207 at yahoo.com Wed Sep 1 16:46:14 2004 From: rha207 at yahoo.com (Ron A) Date: Wed Sep 1 16:46:17 2004 Subject: [Tutor] help with __str__ Message-ID: <20040901144614.79255.qmail@web50906.mail.yahoo.com> In the small program below, I assume that rep is concantenated when a new object is created (instantiated?). If so, it seems that if you put a print statement in the string method it should be printed out when an object is created but it's not. I'm a little confused. Is there somewhere that explains this in a simple way so even I can understand it? class Names(object): def __init__(self, first, last): self.first = first self.last = last print self.first def __str__(self): rep = self.first + " " + self.last return rep Ron A _______________________________ Do you Yahoo!? Win 1 of 4,000 free domain names from Yahoo! Enter now. http://promotions.yahoo.com/goldrush From kent_johnson at skillsoft.com Wed Sep 1 17:15:06 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Sep 1 17:15:15 2004 Subject: [Tutor] help with __str__ In-Reply-To: <20040901144614.79255.qmail@web50906.mail.yahoo.com> References: <20040901144614.79255.qmail@web50906.mail.yahoo.com> Message-ID: <6.1.0.6.0.20040901110953.0287b058@mail4.skillsoft.com> Ron, In Python, expressions are not evaluated until the flow of control actually reaches them. Names.__str__() will not be called until a Names object is printed. You can demonstrate this by changing the value of first or last: >>> class Names: ... def __init__(self, first, last): ... self.first = first ... self.last = last ... def __str__(self): ... rep = self.first + ' ' + self.last ... return rep ... >>> n=Names('Kent', 'Johnson') >>> print n Kent Johnson >>> n.first = 'Joe' >>> print n Joe Johnson (In your code, if you change "print self.first" to "print self" in __init__(), then __str__ will be called when the object is created.) Kent At 07:46 AM 9/1/2004 -0700, Ron A wrote: >In the small program below, I assume that rep is >concantenated when a new object is created >(instantiated?). >If so, it seems that if you put a print statement in >the string method it should be printed out when >an object is created but it's not. I'm a little >confused. Is there somewhere that explains this in a >simple way so even I can understand it? > >class Names(object): > def __init__(self, first, last): > self.first = first > self.last = last > print self.first > > def __str__(self): > rep = self.first + " " + self.last > return rep > >Ron A > > > >_______________________________ >Do you Yahoo!? >Win 1 of 4,000 free domain names from Yahoo! Enter now. >http://promotions.yahoo.com/goldrush >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From H.FANGOHR at soton.ac.uk Wed Sep 1 17:21:17 2004 From: H.FANGOHR at soton.ac.uk (Hans Fangohr) Date: Wed Sep 1 17:21:47 2004 Subject: [Tutor] assigning __doc__ strings (manually) Message-ID: Greetings, I am facing the following problem and would like some advise: I have two functions, say for simplicity, real_f and f: def real_f(x): """this is my doc-string""" return x**2, x**3 def f(x): return real_f(x)[0] The actual work is done in real_f() and some users might be interested in x**3 and x**2. However, most of the users will only care about x**2 and are happy to use the function f() for this. (In the actual program I am working on there is of course more work involved than just computing x**2 and x**3 ...) Since the main computation is done in real_f(), I thought I'd create a doc-string in real_f() that explains the computation being implemented etc (as done above). The function f() does basically the same as real_f() and should provide the same docstring as real_f(). To avoid copying the information, I thought I could do this when defining f(): def f(x): real_f.__doc__ return real_f(x)[0] which -- I was hoping -- would provide real_f.__doc__ in f.__doc__. However, f.__doc__ is None. Can this be solved? Or am I on the wrong track here? Looking forward to hearing from you, Hans From my.mailing.lists at noos.fr Wed Sep 1 17:23:32 2004 From: my.mailing.lists at noos.fr (nik) Date: Wed Sep 1 17:23:51 2004 Subject: [Tutor] problem with threads and C app Message-ID: <4135E974.2030402@noos.fr> hi, I'm trying to call some python methods from C, where the python module is running some threads. The python code seems to be working when I call the methods from the python command line, but when called from my C app, the thread doesn't seem to be created. The code is below, and if it worked, I'd expect the text 'tested' to appear if the thread was created (plus changes to the global variable i). However, nothing appears... the python code is; import thread i = 0 myLock = thread.allocate_lock() def test(): global i, orderListLock, clientLock print "tested" myLock.acquire() i = 50 myLock.release() def initialiseModule(): global i, clientLock # thread.start_new_thread(test,()) <- original plan was to create thread here print "started" for a in range(200): pass myLock.acquire() print i # is = 50 if I run from command line, but = 0 by running C app myLock.release() thread.start_new_thread(test,()) and the C code is; int main(int argc, char ** argv) { PyObject * module; PyObject * function; PyObject * result; Py_Initialize(); char *path, *newpath; // allows locating module in current folder path=Py_GetPath(); newpath=strcat(path, ":."); PySys_SetPath(newpath); free(newpath); module = PyImport_ImportModule("testThread"); function = PyObject_GetAttrString(module, "initialiseModule"); result = PyObject_CallFunction(function, NULL, NULL); Py_Exit(0); } Can anyone see what I'm doing wrong? thanks, nik From kent_johnson at skillsoft.com Wed Sep 1 17:31:38 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Sep 1 17:31:44 2004 Subject: [Tutor] assigning __doc__ strings (manually) In-Reply-To: References: Message-ID: <6.1.0.6.0.20040901112937.0283aac8@mail4.skillsoft.com> You can assign f.__doc__ after f is defined: >>> def real_f(x): ... """this is my doc-string""" ... return x**2, x**3 ... >>> def f(x): ... return real_f(x)[0] ... >>> f.__doc__ = real_f.__doc__ >>> f.__doc__ 'this is my doc-string' Kent At 04:21 PM 9/1/2004 +0100, Hans Fangohr wrote: >Greetings, > >I am facing the following problem and would like some advise: > >I have two functions, say for simplicity, real_f and f: > >def real_f(x): > """this is my doc-string""" > return x**2, x**3 > >def f(x): > return real_f(x)[0] > > >The actual work is done in real_f() and some users might be interested >in x**3 and x**2. However, most of the users will only care about x**2 >and are happy to use the function f() for this. > >(In the actual program I am working on there is of course more work >involved than just computing x**2 and x**3 ...) > >Since the main computation is done in real_f(), I thought I'd create a >doc-string in real_f() that explains the computation being implemented >etc (as done above). > >The function f() does basically the same as real_f() and should >provide the same docstring as real_f(). To avoid copying the >information, I thought I could do this when defining f(): > >def f(x): > real_f.__doc__ > > return real_f(x)[0] > > >which -- I was hoping -- would provide real_f.__doc__ in >f.__doc__. However, f.__doc__ is None. > >Can this be solved? Or am I on the wrong track here? Looking forward >to hearing from you, > >Hans > > > > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From bvande at po-box.mcgill.ca Wed Sep 1 12:11:19 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed Sep 1 18:11:48 2004 Subject: [Tutor] assigning __doc__ strings (manually) In-Reply-To: References: Message-ID: <4135A047.4010100@po-box.mcgill.ca> Hans Fangohr said unto the world upon 2004-09-01 17:21: > Greetings, > > I am facing the following problem and would like some advise: > > I have two functions, say for simplicity, real_f and f: > > def real_f(x): > """this is my doc-string""" > return x**2, x**3 > > def f(x): > return real_f(x)[0] > > > The actual work is done in real_f() and some users might be interested > in x**3 and x**2. However, most of the users will only care about x**2 > and are happy to use the function f() for this. > > (In the actual program I am working on there is of course more work > involved than just computing x**2 and x**3 ...) > > Since the main computation is done in real_f(), I thought I'd create a > doc-string in real_f() that explains the computation being implemented > etc (as done above). > > Hans > Hi Hans, I get that your code description was simplified, but I've a question and possibly a suggestion about it. (All this is orthogonal to your posted question.) From what you say, it seems like you are expecting most of the time the function f() will be the one used, and real_f() will be directly called much less often. As you describe your setup, f() essentially runs real_f() and throws away half the work it produces. (Are there needed side-effects to the "thrown-away" part of real_f() that you didn't mention?) In that context, wouldn't it be more efficient to put the computational work in f() directly and have real_f() call f() and then itself do the other needed work? I mean something like def f(x): return x**2 def real_f(x): return f(x), x**3 (Obviously the names you posted are no longer the ones to use in that f() now really does something itself, but I'm keeping your names structure.) It won't matter much for such simple computations as the toy ones of your post, and I get the "premature optimization is the root of all evil" point. But still, to this relative newcomer's mind, your structure seems undesirable. So, this is either a request for an explanation of what is wrong with what I say, or a helpful observation. I leave it to those higher up the pythonic peaks to determine which ;-) Best to all, Brian vdB From adam at monkeez.org Wed Sep 1 19:49:48 2004 From: adam at monkeez.org (Adam) Date: Wed Sep 1 19:49:56 2004 Subject: [Tutor] String to integer? In-Reply-To: <4135CE30.3090207@latte.ca> References: <27761.217.206.168.163.1094043268.spork@webmail.monkeez.org> <4135CE30.3090207@latte.ca> Message-ID: <41360BBC.9040500@monkeez.org> Blake Winton wrote: > adam wrote: > >> What's the easiest way of creating an integer which is based on a >> value of >> a letter? I really don't mind if it was based on the ascii code, or >> another equivalent. > > > >>> ord('a') > 97 > >>> chr(97) > 'a' > >>> ord('ab') > Traceback (most recent call last): > File "", line 1, in ? > TypeError: ord() expected a character, but string of length 2 found > > (Putting on my user-hat for a second, you _really_ want 26 buttons on a > single form?!? That's probably going to be confusing to look at. Is > there another way you could get the user's input?) > > Later, > Blake. Blake, As this is an application designed to teach kids the alphabet, then yes, putting 26 buttons on the screen is pretty desirable. Adam -- site: http://www.monkeez.org wiki: http://wiki.monkeez.org From project5 at redrival.net Wed Sep 1 19:58:36 2004 From: project5 at redrival.net (Andrei) Date: Wed Sep 1 19:59:31 2004 Subject: [Tutor] Re: Listing function arguments References: <00cb01c49025$e6b81570$0d01a8c0@studioaction.local> Message-ID: <1mt20uc7pj4t6$.b8pimx4duso2$.dlg@40tude.net> Bernard Lebel wrote on Wed, 1 Sep 2004 15:16:31 +0200: > For instance, the first line of a function looks like this: > def cmcopy( aClients = [], sSource = '', sTarget = '', iSource = 0 ): > > So I'd like to know the argument names, for > 1- Know the order at wich the arguments must be passed > 2- Know what variables to supply for arguments > > I don't know if I missed something in the documentation... 1. Yep, you missed the help() function. If you type in the interactive interpreter help(myfunction), you'll get the declaration of myfunction plus the docstring of that function (if it's present). There are also IDE's which give you auto-complete proposals. 2. That's what the docstrings are for, given the fact that Python has no type declarations. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From juicebypi216 at yahoo.com Wed Sep 1 20:05:44 2004 From: juicebypi216 at yahoo.com (Bryan) Date: Wed Sep 1 20:05:47 2004 Subject: [Tutor] Editing files through Python In-Reply-To: <6.1.0.6.0.20040830144818.04897338@mail.mric.net> Message-ID: <20040901180544.52078.qmail@web51002.mail.yahoo.com> Hi Bob, I've been playing around with the advice you was sent me and have become a little confused about the ideas of the input_file (r) and the output_file (w). Can they be the same file? Do I have to close the input file before writing to the output file? Does this example show what always has to be done when using input and output files? Here is the program I wrote following your example, and an error that always appears, relating to the input file, that is perplexing me. I think it probably has a simple solution, but I just don't understand enough about input and output files to figure it out. Is there anything in the Python tutorial or elsewhere that I can read more about reading and writing to input and output files. Here is the program: input_file = file('C:\BryFolder\coherence.dat', 'r') lines = input_file.readlines() output_file = file('C:\BryFolder\coherence.dat', 'w') for line in lines: nums = line.split(" ") retain = nums[:5] new_line = ", ".join(retain)+"\n" output_file.write(new_line) output_file.close() Here is the error: Traceback (most recent call last): File "C:\BryFolder\cohprog3.py", line 1, in ? input_file = file('C:\BryFolder\kt.1.24.data.036rd.test.dat', 'r') # substitute your path to the file IOError: [Errno 2] No such file or directory: 'C:\\BryFolder\\kt.1.24.data.036rd.test.dat' Thanks for the help Bryan Bob Gailer wrote:At 01:38 PM 8/30/2004, Bryan wrote: > >I am a beginner in Python, and this is my first time using this list so I >hope my question is acceptable. We are here to help, but not just give answers. However your request seems to me to merit a program, which I hope you will study to enhance your understanding of Python. Please ask more questions., >Basically, my goal is to read data files that are already on my hard drive >into Python, and then edit them, deleting unneccesary portions of data. > >I have already figured out how to read the files into Python, I just >cannot figure out how to edit them. Here are the difficulties: > >How do I delete, cut, or paste portions of the data I am reading and how >do I tell the program to jump to that specific portion of data that I want >to alter? The usual approach is to read the file into a Python variable, process the variable and write a new file (which can have the same name as the input file, rather than to attempt to manipulate the file itself. It is a LOT easier this way. > Here is a somewhat complicated example, similar to what I want to do - > >I have two rows of numbers, as shown below. Each row has 10 numbers >(hopefully they will show up as two rows of numbers in the email (1-10 and >11-20). > >1, 2, 3, 4, 5, 6, 7, 8, 9, 10 >11, 12, 13, 14, 15, 16, 17, 18, 19, 20 > >What commands might I use to automatically go through each row, deleting >the 6th through 10th numbers in each row (6-10 in the first row and 16-20 >in the second row). I have written a complete program, just to avoid any ambiguities. input_file = file('num.txt', 'r') # substitute your path to the file lines = input_file.readlines() # list of lines output_file = file('num.txt', 'w') # substitute your path to the file for line in lines: nums = line.split(", ") # assumes numbers separated by ", ", gives list of numbers retain = nums[:5] # keep first 5 numbers new_line = ", ".join(retain)+"\n" # reassemble into a line output_file.write(new_line) # write to file output_file.close() Please note this depends on consistent number separators. If the separators vary, then the approach gets more complex. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell --------------------------------- Do you Yahoo!? Yahoo! Mail - 50x more storage than other providers! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040901/5463e69a/attachment.htm From kent_johnson at skillsoft.com Wed Sep 1 20:28:23 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Sep 1 20:28:35 2004 Subject: [Tutor] Re: Listing function arguments In-Reply-To: <1mt20uc7pj4t6$.b8pimx4duso2$.dlg@40tude.net> References: <00cb01c49025$e6b81570$0d01a8c0@studioaction.local> <1mt20uc7pj4t6$.b8pimx4duso2$.dlg@40tude.net> Message-ID: <6.1.0.6.0.20040901142512.02879870@mail4.skillsoft.com> The help function gets its juice from the inspect module and the docstrings: >>> def foo(a=None, b=''): ... pass ... >>> help(foo) Help on function foo in module __main__: foo(a=None, b='') >>> import inspect >>> inspect.getargspec(foo) (['a', 'b'], None, None, (None, '')) >>> inspect.formatargspec(*inspect.getargspec(foo)) "(a=None, b='')" Inspect is looking at attributes of the function object, you can look at the module source for details. Pretty amazing what you can find out just by digging into an object! Kent At 07:58 PM 9/1/2004 +0200, Andrei wrote: >Bernard Lebel wrote on Wed, 1 Sep 2004 15:16:31 +0200: > > > For instance, the first line of a function looks like this: > > def cmcopy( aClients = [], sSource = '', sTarget = '', iSource = 0 ): > > > > So I'd like to know the argument names, for > > 1- Know the order at wich the arguments must be passed > > 2- Know what variables to supply for arguments > > > > I don't know if I missed something in the documentation... > >1. Yep, you missed the help() function. If you type in the interactive >interpreter help(myfunction), you'll get the declaration of myfunction plus >the docstring of that function (if it's present). There are also IDE's >which give you auto-complete proposals. > >2. That's what the docstrings are for, given the fact that Python has no >type declarations. > >-- >Yours, > >Andrei From flaxeater at yahoo.com Wed Sep 1 20:32:53 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Wed Sep 1 20:32:56 2004 Subject: [Tutor] String to integer? Message-ID: <20040901183253.25312.qmail@web52609.mail.yahoo.com> Blake Winton wrote: > adam wrote: > >> What's the easiest way of creating an integer which is based on a >> value of >> a letter? I really don't mind if it was based on the ascii code, or >> another equivalent. > > > >>> ord('a') > 97 > >>> chr(97) > 'a' > >>> ord('ab') > Traceback (most recent call last): > File "", line 1, in ? > TypeError: ord() expected a character, but string of length 2 found > > (Putting on my user-hat for a second, you _really_ want 26 buttons on > a single form?!? That's probably going to be confusing to look at. > Is there another way you could get the user's input?) > Well how about using hash() for getting your integers. This way it can be a string of any length. This is kinda neat I will probably always use this method from here on out. However I do not know if wxwidgets can accept negative id's which has does return but that's not the end of the world. It can be worked around. >>> hash('a') -468864544 >>> help(hash) Help on built-in function hash: hash(...) hash(object) -> integer Return a hash value for the object. Two objects with the same value have the same hash value. The reverse is not necessarily true, but likely. >>> hash('b') -340864157 >>> b='b' >>> hash(b) -340864157 _______________________________ Do you Yahoo!? Express yourself with Y! Messenger! Free. Download now. http://messenger.yahoo.com From python at bernardlebel.com Wed Sep 1 21:38:01 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Wed Sep 1 20:35:37 2004 Subject: [Tutor] Re: Listing function arguments References: <00cb01c49025$e6b81570$0d01a8c0@studioaction.local><1mt20uc7pj4t6$.b8pimx4duso2$.dlg@40tude.net> <6.1.0.6.0.20040901142512.02879870@mail4.skillsoft.com> Message-ID: <001301c4905b$32ff6ac0$2901a8c0@atyss> Once again, thanks a heap everyone for the help, most useful. Bernard From jeff at ccvcorp.com Wed Sep 1 21:12:46 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed Sep 1 21:12:45 2004 Subject: [Tutor] String to integer? In-Reply-To: <27761.217.206.168.163.1094043268.spork@webmail.monkeez.org> References: <27761.217.206.168.163.1094043268.spork@webmail.monkeez.org> Message-ID: <41361F2E.5090709@ccvcorp.com> adam wrote: > I have a list which holds all the letters of the alphabet. I want to > create a button (wxPython) for each of these letters and then give the > button an ID (count - which is an integer). However, I would like the ID > to be driven by the list (which is string). See code below. > > What's the easiest way of creating an integer which is based on a value of > a letter? I really don't mind if it was based on the ascii code, or > another equivalent. The potential gotcha here, that hasn't been being addressed, is that if you're using these integers as IDs inside wxPython then you need to be careful to select numbers that won't conflict with *other* IDs. One way of doing this would be to select a base ID, near the beginning of a range that you know is clear, and then defining each button's ID to be base_id + ord(char). However, there's rarely any need, in wxPython, to explicitly specify widget IDs. You're better off using either wxNewId() (or just passing in -1). If you need the ID for something, you can get it with wxWidget.GetId(). This does mean that you need to keep object references to your widgets, but that's probably a good idea anyhow -- you can easily set up a dictionary which maps a letter to a wxButton instance, and store that dictionary either on your parent window or in the wxApp instance... Jeff Shannon Technician/Programmer Credit International From jeff at ccvcorp.com Wed Sep 1 21:29:42 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed Sep 1 21:28:29 2004 Subject: [Tutor] Editing files through Python In-Reply-To: <20040901180544.52078.qmail@web51002.mail.yahoo.com> References: <20040901180544.52078.qmail@web51002.mail.yahoo.com> Message-ID: <41362326.90703@ccvcorp.com> Bryan wrote: > Hi Bob, > > I've been playing around with the advice you was sent me and have become > a little confused about the ideas of the input_file (r) and the > output_file (w). Can they be the same file? Do I have to close the > input file before writing to the output file? Does this example show > what always has to be done when using input and output files? > > Here is the program I wrote following your example, and an error that > always appears, relating to the input file, that is perplexing me. I > think it probably has a simple solution, but I just don't understand > enough about input and output files to figure it out. Is there anything > in the Python tutorial or elsewhere that I can read more about reading > and writing to input and output files. First, read the error message carefully. No such file or directory: C:\\BryFolder\\kt.1.24.data.036rd.test.dat This error is coming from the operating system underneath Python, and is saying that it can't find that file. Are you sure that this file already exists? You will have a difficult time reading from a file you haven't created yet. ;) Now, to answer your actual question -- you (generally) can't have more than one active filehandle to a given file at once. This means that, if you open the file for reading, then you need to close it before you reopen it for writing. > input_file = file('C:\BryFolder\coherence.dat', 'r') > lines = input_file.readlines() # add following line: input_file.close() > output_file = file('C:\BryFolder\coherence.dat', 'w') > for line in lines: > nums = line.split(" ") > retain = nums[:5] > new_line = ", ".join(retain)+"\n" > output_file.write(new_line) > output_file.close() Keep in mind that the first thing that happens when you open the file for writing is that, if it already exists, the contents are discarded. This means that, if something does go wrong, you could lose all data in the file. If you have copies of the data elsewhere, this may not matter, but it might be a bit safer to write to a different file, just in case. (Writing to a different file would also make it a bit clearer whether a given file had already been processed or not...) There *is* also a read/write file mode, where you can have a single file object that can be both read from and written to. This can be a bit tricky, though -- writing is always "replace" rather than "insert", and it's usually necessary to seek() a particular location before writing and flush() after writing, even if you think that you're already at the right location in the file. (There's some "fun" side-effects of the underlying C library's file-buffering scheme...) And in your case, it would have little benefit anyhow -- you don't want to leave part of the file as it is, so you might as well let open() truncate the file to nothing for you instead of doing it yourself. Jeff Shannon Technician/Programmer Credit International From adam at monkeez.org Wed Sep 1 21:28:33 2004 From: adam at monkeez.org (Adam) Date: Wed Sep 1 21:29:01 2004 Subject: [Tutor] String to integer? In-Reply-To: <00b201c49023$ad72bf10$0d01a8c0@studioaction.local> References: <27761.217.206.168.163.1094043268.spork@webmail.monkeez.org> <00b201c49023$ad72bf10$0d01a8c0@studioaction.local> Message-ID: <413622E1.2020300@monkeez.org> Bernard Lebel wrote: > Personally I'd consider using a dictionary for that. Assign the letter (the > key) to the number (the value). > > > Cheers > Bernard > Bernard, The dictionary worked a treat (although I had to spend half an hour working it out). Many thanks Adam -- site: http://www.monkeez.org wiki: http://wiki.monkeez.org From python at bernardlebel.com Wed Sep 1 23:22:05 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Wed Sep 1 22:19:44 2004 Subject: [Tutor] String to integer? References: <27761.217.206.168.163.1094043268.spork@webmail.monkeez.org><00b201c49023$ad72bf10$0d01a8c0@studioaction.local> <413622E1.2020300@monkeez.org> Message-ID: <002201c49069$bcf7aa90$2901a8c0@atyss> Hi Adam, Sorry for the learning curve, I should have mentioned that the tutorial that comes with the documentation covers dictionaries. That would have saved you some time I guess. My bad. Cheers Bernard ----- Original Message ----- From: "Adam" Cc: Sent: Wednesday, September 01, 2004 8:28 PM Subject: Re: [Tutor] String to integer? > Bernard Lebel wrote: > > > Personally I'd consider using a dictionary for that. Assign the letter (the > > key) to the number (the value). > > > > > > Cheers > > Bernard > > > > Bernard, > > The dictionary worked a treat (although I had to spend half an hour > working it out). > > Many thanks > > Adam > > > -- > site: http://www.monkeez.org > wiki: http://wiki.monkeez.org > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From alan.gauld at blueyonder.co.uk Wed Sep 1 22:38:31 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Sep 1 22:37:39 2004 Subject: [Tutor] Python - TCL Interaction References: Message-ID: <03eb01c49063$a55aa640$6401a8c0@xp> > I am using Tkinker to interface Python to TCL. I am able > to call tcl APIs, While this is possoble its not really a "documented feature" of Tkinter. ie it's not normal practice! > Now, the problem is I have to pass a two dimensional list Whatever you pass to tk.eval needs to be in Tcl speak. arr = [["apple", "mango", "orange"], ["rose", "jasmine", "marigold"]] root.tk.eval('test_tcl_func %s', %(list)) So you can't pass a Python list as a Python list, it will be interpreted as a Tcl bracketed expression. Instead you will need to convert the Python list into a Tcl style list expressed as a string. So the question is how would you create a multi dimensional array/list in Tcl? How do you convert a Python list into that structure? It's basically a string formatting exercise. So I'd aim to do it in stages: Basic Tcl List building code: "set L [list 1 2 3]" Python: L1 = [1, 2, 3] L2 = [4, 5, 6] tclstr = 'set L1 [list ' for elem in L1: tclstr += (str(elem) + ' ') tclstr2 = "sel L2 [list " for elem in L2: tclstr += (str(elem) + ' ') tclstr = tclstr1 + ';' + tclstr2 + ';' + 'set L [list L1 L2]' Tk.eval(tclstr) Or something like that, I haven't tested it :-) Would it really be much harder to convert the Tcl code to Python? Alan G. From alan.gauld at blueyonder.co.uk Wed Sep 1 22:41:37 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Sep 1 22:40:44 2004 Subject: [Tutor] Introduction References: <20040831233251.F17091-100000@localhost.name><005001c48ffc$4abe42d0$0d01a8c0@studioaction.local><1094040543.2430.5.camel@localhost.localdomain> <1094042010.2348.99.camel@localhost> Message-ID: <03f401c49064$13af9560$6401a8c0@xp> > I want to start programming and was pointed to python as a good > beginner's language. I am reading 'Learning Python' by Mark Luty and > David Ascher. It is fascinating, even it sometimes takes me a while to > keep all the information;) If you've never programmed before I'd recommend running through one of the non-programmers intros first, then go back to Lutz. It will be faster I think in the long term. There is a list of non programmers intros on the Python site, I am, of course, biased towards my own :-) Also don;t neglect the official tutor that comes with Python, but like Lutz it assumes some previous experience in other languages. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From alan.gauld at blueyonder.co.uk Wed Sep 1 22:47:33 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Sep 1 22:46:40 2004 Subject: [Tutor] Suggestions as to how to read a file in paragraphs References: Message-ID: <03fb01c49064$e81b2940$6401a8c0@xp> > What is a more efficient way to read a file and split it into paragraphs > and just print those paragraphs which match a particular condition? First, do you need the efficiency? Is it actually causing a problem just now? > The inefficient way is to read the whole file into one string and then > split it, but this becomes problematic with larger files. You are going to have to read the whole file anyhow so this might well be an efficient route provided you have enough RAM. > Any suggestions on a more efficient approach or is there a module available? Lots of modules might help (re, parser, string, fileinput etc) but nothing specifically for splitting text files by paragraph. (And how do you define a paragraph separator? Is it a blank line or is it an indented first line? Both are valid...) My case study topic in my tutorial does separate by blank lines but it makes no attempt to optimise efficiency. For moderate length files (a few hundred lines) it is adequate. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From kent_johnson at skillsoft.com Wed Sep 1 22:46:38 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Sep 1 22:46:52 2004 Subject: [Tutor] Python - TCL Interaction In-Reply-To: References: Message-ID: <6.1.0.6.0.20040901164528.029b87e0@mail4.skillsoft.com> I'm curious, can you tell us why you are using this architecture? Why not use Tcl/Tk or Tkinter/Python? Thanks, Kent At 05:20 PM 9/1/2004 +0530, Jayanthi, Satya Padmaja (Satya Padmaja) wrote: >content-class: urn:content-classes:message >Content-Type: multipart/alternative; > boundary="----_=_NextPart_001_01C49019.E02077E0" >Content-Transfer-Encoding: 7bit > >Hi : > >I am using Tkinker to interface Python to TCL. I am able to call tcl APIs, >pass the input parameters as strings to the TCL APIs, fetch the return >values from the TCL APIs etc... From the python code. > >Now, the problem is I have to pass a two dimensional list (the elements of >the list are also lists) to the tcl file. How can I do it ? If I simply >use the "%s" option, the error that is thrown is "_tkinter.TclError: >invalid command name "'apple',"" > > import Tkinter > > root = Tkinter.Tk() > root.tk.eval('source test_tcl_file.tcl') > > arr = [["apple", "mango", "orange"], ["rose", "jasmine", > "marigold"]] > root.tk.eval('test_tcl_func %s', %(list)) > >I have tried many tricks.Tried setting the array in the python file etc. >root.tk.eval('global arr; lappend arr %s' %(s)). But nothing works. Can >anyone of you please help me ? > >Thanks and Regards, >Padmaja > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From alan.gauld at blueyonder.co.uk Wed Sep 1 22:48:46 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Sep 1 22:47:54 2004 Subject: [Tutor] String to integer? References: <27761.217.206.168.163.1094043268.spork@webmail.monkeez.org> Message-ID: <040001c49065$13c6aa60$6401a8c0@xp> > What's the easiest way of creating an integer which is based on a value of > a letter? I really don't mind if it was based on the ascii code, or > another equivalent. ASCII code is found from ord(char). Seems as good a planas any :-) Alan G. From alan.gauld at blueyonder.co.uk Wed Sep 1 22:56:53 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Sep 1 22:56:00 2004 Subject: [Tutor] Listing function arguments References: <00cb01c49025$e6b81570$0d01a8c0@studioaction.local> Message-ID: <040701c49066$3603d020$6401a8c0@xp> > Is there a way to list the arguments that a variable is accepting? > > For instance, the first line of a function looks like this: > def cmcopy( aClients = [], sSource = '', sTarget = '', iSource = 0 ): > > So I'd like to know the argument names, for > 1- Know the order at wich the arguments must be passed > 2- Know what variables to supply for arguments Lets get our terminology straight first. aClients, aSource etc are the parameter names of the function cmcopy If I do: L = [1,2,3] s = 'fred' t = 'tom' src = 42 cmcopy(L,s,t,src) The variable names are: L, s, t, src but the *arguments* are just the values that those variables hold and they are assined the temporary names aClients, sSource, sTarget, iSource for the duration of the function call. Thus if I do: cmcopy([1,2,3],'fred','tom',42) There are no argument names, but the argument values are: [1,2,3,], 'fred','tom',42 Almost exactly as they were above (except that the lists are not also referenced by the variables!) Which names do you want? And what dso you think you can do with them? If we know what you are trying to achieve we might be able to offer a better solution. :-) Alan G. From T.Chern at unibas.ch Wed Sep 1 22:56:49 2004 From: T.Chern at unibas.ch (Tzu-Ming Chern) Date: Wed Sep 1 22:56:57 2004 Subject: [Tutor] Suggestions as to how to read a file in paragraphs In-Reply-To: <03fb01c49064$e81b2940$6401a8c0@xp> Message-ID: Hi Alan, > First, do you need the efficiency? Is it actually causing a problem > just now? Before yes, but not now. The efficiency is needed when very large files are needed and not enough RAM is available to process huge files (eg. > 3 million lines) > Lots of modules might help (re, parser, string, fileinput etc) but > nothing > specifically for splitting text files by paragraph. (And how do you > define a paragraph separator? Is it a blank line or is it an indented > first line? Both are valid...) Depending on the biological sequence files, the paragraph separator could be a "//" or newlines or any string really. I know in perl there is an input record separator which by default is the newline and one can specify this to a specific delimiter. Is there one in python? Apologies for the confusion! cheers, tzuming From alan.gauld at blueyonder.co.uk Wed Sep 1 23:01:31 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Sep 1 23:00:38 2004 Subject: [Tutor] Suggestions as to how to read a file in paragraphs References: <6.1.0.6.0.20040901091752.0287c390@mail4.skillsoft.com> Message-ID: <041e01c49066$dbd74a40$6401a8c0@xp> > You could read the file by lines and accumulate lines in a list until you > find a paragraph break. Then look at the accumulated lines and see if you > want to print it. Something like this (assuming a blank line is a paragraph > break): Thats what I do in my cae study but its almost certainly slower than reading the entire file in one gulp then splitting by '\n\n' (ie a blank line) to get a list of paragraphs. But if memory is tight a loop with xreadlines() is probably best. OTOH I haven't benchmarked any of this :-) Alan G. From bill at celestial.net Wed Sep 1 23:00:37 2004 From: bill at celestial.net (Bill Campbell) Date: Wed Sep 1 23:00:43 2004 Subject: [Tutor] Suggestions as to how to read a file in paragraphs In-Reply-To: <03fb01c49064$e81b2940$6401a8c0@xp> References: <03fb01c49064$e81b2940$6401a8c0@xp> Message-ID: <20040901210037.GA3584@alexis.mi.celestial.com> On Wed, Sep 01, 2004, Alan Gauld wrote: >> What is a more efficient way to read a file and split it into >paragraphs >> and just print those paragraphs which match a particular condition? > >First, do you need the efficiency? Is it actually causing a problem >just now? This sounds like somebody who is accustomed to perl's ability to tweak a variable causing the read operation to suck in paragraph at a time. Every time I've wanted to use this in perl, I've had to either go back to the perlvars documentation or find an existing program that used it to figure out what the variable name is. Bill -- INTERNET: bill@Celestial.COM Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ Many companies that have made themselves dependent on [the equipment of a certain major manufacturer] (and in doing so have sold their soul to the devil) will collapse under the sheer weight of the unmastered complexity of their data processing systems. -- Edsger W. Dijkstra, SIGPLAN Notices, Volume 17, Number 5 From alan.gauld at blueyonder.co.uk Wed Sep 1 23:21:20 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Sep 1 23:20:27 2004 Subject: [Tutor] help with __str__ References: <20040901144614.79255.qmail@web50906.mail.yahoo.com> Message-ID: <042301c49069$a05c5cf0$6401a8c0@xp> > In the small program below, I assume that rep is > concantenated when a new object is created > (instantiated?). rep only exists while __str__ is being executed which is during a print operation. If it weren't then the print would only ever show the values the object had when created which is not what most users would expect! > If so, it seems that if you put a print statement in > the string method it should be printed out when > an object is created but it's not. If you print self then Names.__str__() will be called but if you print self.first then self.first.__str__() will be called which is not defined in the code you show us. > confused. Is there somewhere that explains this in a > simple way so even I can understand it? Its almost as you think it is but you aren't doing what you think you are doing! :-) You are printing out self.first. It is whatever oject you pass in and print will use whatever string representation it has. If you want to call your __str__ method you must print an instance of the Names class, ie self. > class Names(object): > def __init__(self, first, last): > self.first = first > self.last = last > print self.first > > def __str__(self): > rep = self.first + " " + self.last > return rep HTH, Alan G. From python at bernardlebel.com Thu Sep 2 00:32:30 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Wed Sep 1 23:30:13 2004 Subject: [Tutor] Listing function arguments References: <00cb01c49025$e6b81570$0d01a8c0@studioaction.local> <040701c49066$3603d020$6401a8c0@xp> Message-ID: <000c01c49073$94639710$2901a8c0@atyss> Hi Alan, I was simply looking at listing the function parameter names, nothing more. :-) I wanted to know what the funciton uses for paramter names, so I can assign values to variables of the same name and pass them to the function. In the example I gave I provide default values for these arguments, but sometimes you want to know before hand what to supply to the function. However, unless you're working in PythonWin, it's not obvious. Anyway the tips given by Kent and Andrei are exactly what I wanted: help( myfunction ) Cheers Bernard ----- Original Message ----- From: "Alan Gauld" To: "Bernard Lebel" ; Sent: Wednesday, September 01, 2004 9:56 PM Subject: Re: [Tutor] Listing function arguments > > Is there a way to list the arguments that a variable is accepting? > > > > For instance, the first line of a function looks like this: > > def cmcopy( aClients = [], sSource = '', sTarget = '', iSource = > 0 ): > > > > So I'd like to know the argument names, for > > 1- Know the order at wich the arguments must be passed > > 2- Know what variables to supply for arguments > > Lets get our terminology straight first. > > aClients, aSource etc are the parameter names of the function cmcopy > > If I do: > > L = [1,2,3] > s = 'fred' > t = 'tom' > src = 42 > cmcopy(L,s,t,src) > > The variable names are: L, s, t, src > but the *arguments* are just the values that those variables hold > and they are assined the temporary names > > aClients, sSource, sTarget, iSource > > for the duration of the function call. > > > Thus if I do: > > cmcopy([1,2,3],'fred','tom',42) > > There are no argument names, but the argument values are: > [1,2,3,], 'fred','tom',42 > > Almost exactly as they were above (except that the lists are not > also referenced by the variables!) > > Which names do you want? And what dso you think you can do with them? > If we know what you are trying to achieve we might be able to offer > a better solution. :-) > > Alan G. > > > From alan.gauld at blueyonder.co.uk Wed Sep 1 23:48:58 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Sep 1 23:48:06 2004 Subject: [Tutor] Editing files through Python References: <20040901180544.52078.qmail@web51002.mail.yahoo.com> Message-ID: <045401c4906d$7c5d2290$6401a8c0@xp> > I've been playing around with the advice you was sent me > and have become a little confused about the ideas of the > input_file (r) and the output_file (w). Can they be the > same file? No. Actually what's being suggested is what Microsoft Word (and almost all other programs) do. They copy the original file(foo.doc) to a temp file (~foo.doc) and open the temporary copy and read it. When you do a save they overwrite the original file and rename ~foo.doc to foo.bak. Or some similar sequence, basically they create a new file so that they don't corrupt the original until an explicit save is done. It just looks like to the user as if it is opening and modifying the original file, in fact it is making copies and operating on two different files. (actually 3 if you include an auto-save recovery version!) > Do I have to close the input file before writing to the > output file? Not if you use the model above - ie operate on a copy of the original and don't overwrite it until you are ready. > Here is the program I wrote following your example, > and an error that always appears, relating to the input file, > that is perplexing me. This bit has been answered already :-) > IOError: [Errno 2] No such file or directory: 'C:\\BryFolder\\kt.1.24.data.036rd.test.dat' Alan G. From alan.gauld at blueyonder.co.uk Wed Sep 1 23:59:00 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Sep 1 23:58:07 2004 Subject: [Tutor] Suggestions as to how to read a file in paragraphs References: Message-ID: <047401c4906e$e36b7850$6401a8c0@xp> > Depending on the biological sequence files, the paragraph separator could > be a "//" or newlines or any string really. I know in perl there is an > input record separator which by default is the newline and one can specify > this to a specific delimiter. Is there one in python? OK, awk can do that trick too. Unfortunately I don't know of any way to do it in Python, I think you either need to check each line in a for/readline() loop or use a regex to extract the paras with findall() - which brings more memory issues with it... or use multiple applications of string.split() on the file.read() string. No simple answers for big files I'm afraid, and I checked the fileinput module and it has no way of defining a split either, and is slow anyway if speed is already an issue. Alan G. From bigapple631 at optonline.net Thu Sep 2 00:52:53 2004 From: bigapple631 at optonline.net (jason hochstein) Date: Thu Sep 2 00:56:04 2004 Subject: [Tutor] saving program Message-ID: <008201c49076$6a3c3d90$bc4ebb18@hochstein> good afternoon. I was wondering if there was a way to make a program save the info it gives so when you open it again it displays the information that was last inputed into the program. So you don't have to start fresh everytime you start the program. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040901/1873f311/attachment.htm From isrgish at fastem.com Thu Sep 2 02:29:47 2004 From: isrgish at fastem.com (Isr Gish) Date: Thu Sep 2 02:30:02 2004 Subject: [Tutor] Editing files through Python Message-ID: <20040902003000.739A11E4002@bag.python.org> Hi Bryan, -----Original Message----- >From: "Bryan" >Sent: 9/1/04 2:05:44 PM >To: "Bob Gailer", "tutor@python.org" >Subject: Re: [Tutor] Editing files through Python > >Hi Bob, > [snip some text] >Here is the program: > >input_file = file('C:\BryFolder\coherence.dat', 'r') >lines = input_file.readlines() >output_file = file('C:\BryFolder\coherence.dat', 'w') >for line in lines: > nums = line.split(" ") > retain = nums[:5] > new_line = ", ".join(retain)+"\n" > output_file.write(new_line) >output_file.close() > >Here is the error: > >Traceback (most recent call last): > File "C:\BryFolder\cohprog3.py", line 1, in ? > input_file = file('C:\BryFolder\kt.1.24.data.036rd.test.dat', 'r') # substitute your path to the file >IOError: [Errno 2] No such file or directory: 'C:\\BryFolder\\kt.1.24.data.036rd.test.dat' > It seems that the file you give in the program is not the same file thatbis showing in the error. What the acttual error is saying, is that there is no such file. (which is brobebly related with that that you have a different file in the error) All the best, Isr >Thanks for the help >Bryan > > > > > >Bob Gailer wrote:At 01:38 PM 8/30/2004, Bryan wrote: >> >>I am a beginner in Python, and this is my first time using this list so I >>hope my question is acceptable. > >We are here to help, but not just give answers. However your request seems >to me to merit a program, which I hope you will study to enhance your >understanding of Python. Please ask more questions., > >>Basically, my goal is to read data files that are already on my hard drive >>into Python, and then edit them, deleting unneccesary portions of data. >> >>I have already figured out how to read the files into Python, I just >>cannot figure out how to edit them. Here are the difficulties: >> >>How do I delete, cut, or paste portions of the data I am reading and how >>do I tell the program to jump to that specific portion of data that I want >>to alter? > >The usual approach is to read the file into a Python variable, process the >variable and write a new file (which can have the same name as the input >file, rather than to attempt to manipulate the file itself. It is a LOT >easier this way. > >> Here is a somewhat complicated example, similar to what I want to do - >> >>I have two rows of numbers, as shown below. Each row has 10 numbers >>(hopefully they will show up as two rows of numbers in the email (1-10 and >>11-20). >> >>1, 2, 3, 4, 5, 6, 7, 8, 9, 10 >>11, 12, 13, 14, 15, 16, 17, 18, 19, 20 >> >>What commands might I use to automatically go through each row, deleting >>the 6th through 10th numbers in each row (6-10 in the first row and 16-20 >>in the second row). > >I have written a complete program, just to avoid any ambiguities. > >input_file = file('num.txt', 'r') # substitute your path to the file >lines = input_file.readlines() # list of lines >output_file = file('num.txt', 'w') # substitute your path to the file >for line in lines: >nums = line.split(", ") # assumes numbers separated by ", ", gives list >of numbers >retain = nums[:5] # keep first 5 numbers >new_line = ", ".join(retain)+"\n" # reassemble into a line >output_file.write(new_line) # write to file >output_file.close() > >Please note this depends on consistent number separators. If the separators >vary, then the approach gets more complex. > >Bob Gailer >bgailer@alum.rpi.edu >303 442 2625 home >720 938 2625 cell > > > > >--------------------------------- >Do you Yahoo!? >Yahoo! Mail - 50x more storage than other providers! From flaxeater at yahoo.com Thu Sep 2 04:20:25 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Thu Sep 2 04:20:28 2004 Subject: [Tutor] saving program Message-ID: <20040902022025.30672.qmail@web52608.mail.yahoo.com> jason hochstein wrote: >THANKS. GOOD JOB HELPING > > > > Sorry I was not trying to be snide. I meant this however. It can be a very complex thing, and it depends alot on how you structure the solution. If i where to do it I would serilize(persist) objects. However there are just tons of ways to do this. __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From str_kbs at sancharnet.in Wed Sep 1 04:23:46 2004 From: str_kbs at sancharnet.in (General Electronics,Phaltan) Date: Thu Sep 2 04:24:43 2004 Subject: [Tutor] help-Please help me to read Text From JPEG file Message-ID: <000001c49095$91365380$c762013d@h5e1d0> Hi, Please help me to write python code to read Text from JPEG file and store to standard TEXT file. Thanks Arvind Sidhaye From str_kbs at sancharnet.in Wed Sep 1 04:25:44 2004 From: str_kbs at sancharnet.in (General Electronics,Phaltan) Date: Thu Sep 2 04:24:49 2004 Subject: [Tutor] help-Please help me to write ODBC connection application Message-ID: <000101c49095$93ee2080$c762013d@h5e1d0> Hi, I have 'MYDATA' as DSN in my ODBC. How can i write code to read tables from this DSN. I am not famiilier with Python code. Arvind Sidhaye From dyoo at hkn.eecs.berkeley.edu Thu Sep 2 07:34:12 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Sep 2 07:34:23 2004 Subject: [Tutor] assigning __doc__ strings (manually) In-Reply-To: Message-ID: > Since the main computation is done in real_f(), I thought I'd create a > doc-string in real_f() that explains the computation being implemented > etc (as done above). [text cut] Hi Hans, Kent's solution, to manually assign to the function's __doc__ attribute, after the function is defined, should do the trick. The reason that: > def f(x): > real_f.__doc__ > return real_f(x)[0] didn't work is because Python looks for the first line in a function for a real string literal, and not just any expression that could be evaluated as a string. This is consistant with the way that Python doesn't do any evaluation of functions unless they're explicitely called. For example: ### >>> def testEvaluation(): ... print x ... ### would be invalid if 'x' weren't defined. But since Python doesn't evaluate function bodies on definition time, we're still fine until we actually start trying to use it: ### >>> testEvaluation() Traceback (most recent call last): File "", line 1, in ? File "", line 2, in testEvaluation NameError: global name 'x' is not defined ### As soon as we define an 'x', we're ok: ### >>> x = "hello sailor" >>> testEvaluation() hello sailor ### Anyway, I'd better try to tie this back to the original question. *grin* When we look at: > def f(x): > real_f.__doc__ > return real_f(x)[0] we now know that Python's not allowed to actually try evaluating expressions like 'real_f.__doc__'. At most, Python can do a quick scan for string literals, like: ### def f(x): "this is some docstring." return real_f(x)[0] ### For this reason, Python's automatic detection of documentation strings is limited to paying attention to literal strings, since finding those is technically trivial. It's easy to do, and doesn't really violate the "don't try to evaluate the function body until we're called" rule that functions follow. Hope that made some sense. *grin* Good luck! From dyoo at hkn.eecs.berkeley.edu Thu Sep 2 07:42:01 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Sep 2 07:42:07 2004 Subject: [Tutor] saving program In-Reply-To: <20040902022025.30672.qmail@web52608.mail.yahoo.com> Message-ID: [some text cut] > It [saving program state] can be a very complex thing, and it depends > alot on how you structure the solution. If i where to do it I would > serilize(persist) objects. However there are just tons of ways to do > this. Hi Jason, Python comes with a Standard Library module called 'shelve' that acts like a dictionary, but is actually backed by a disk: http://www.python.org/doc/lib/module-shelve.html There are other serialization systems available, but for simple things, 'shelve' seems to be a nice way to save the state of your program. Try 'shelve' out; if you have questions, please feel free to bring them up. Good luck! From dyoo at hkn.eecs.berkeley.edu Thu Sep 2 07:44:48 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Sep 2 07:44:59 2004 Subject: [Tutor] help-Please help me to read Text From JPEG file In-Reply-To: <000001c49095$91365380$c762013d@h5e1d0> Message-ID: On Wed, 1 Sep 2004, General Electronics,Phaltan wrote: > Please help me to write python code to read Text from JPEG file and > store to standard TEXT file. Hi Arvind, The question you're asking is slightly odd. JPEGs are binary: for the most part, they're not supposed to have text (except possibly some metadata). What are you trying to do? It might help if you could tell us why you're trying to do this. Are you trying to rewrite the standard 'strings' Unix shell command? Good luck to you. From dyoo at hkn.eecs.berkeley.edu Thu Sep 2 07:58:41 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Sep 2 07:58:58 2004 Subject: [Tutor] help-Please help me to write ODBC connection application In-Reply-To: <000101c49095$93ee2080$c762013d@h5e1d0> Message-ID: On Wed, 1 Sep 2004, General Electronics,Phaltan wrote: > I have 'MYDATA' as DSN in my ODBC. How can i write code to read tables from > this DSN. Hi Arvind, Wait, wait: you're using some terms that may not be familiar to folks here on the Tutor list. DSN... ODBC... http://en.wikipedia.org/wiki/Database_Source_Name http://en.wikipedia.org/wiki/ODBC So you have a Database Source Name, and you're trying to connect to an ODBC database? Ok, you may want to look at the 'mxODBC' third-party module: http://www.egenix.com/files/python/mxODBC.html The examples on that page shows how to start up a connection, given a DSN: ### >>> import mx.ODBC.iODBC >>> db = mx.ODBC.iODBC.DriverConnect('DSN=database;UID=user;PWD=passwd') ### And by this time, we should have a 'db' connection that we can use to start querying the database. > I am not famiilier with Python code. Hmmm. That can be a problem. Are you sure you want to tackle databases before Python? You may want to get familiar with some Python basics, because otherwise, depending on your previous background, you're bound to run into issues that have nothing to do with databases, but have more to do with how Python works. It sounds like you've had some programming experience already. If that's the case, we strongly recommend you look at the Official Tutorial at: http://www.python.org/doc/tut/ to at least get you up to speed quickly. There are other guides in: http://www.python.org/topics/learn/ that may also be useful as reference material. If you have more questions, please feel free to ask. Good luck! From dyoo at hkn.eecs.berkeley.edu Thu Sep 2 08:31:56 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Sep 2 08:32:05 2004 Subject: [Tutor] Suggestions as to how to read a file in paragraphs In-Reply-To: Message-ID: > > First, do you need the efficiency? Is it actually causing a problem > > just now? > > Before yes, but not now. The efficiency is needed when very large files > are needed and not enough RAM is available to process huge files (eg. > > 3 million lines) > > > Lots of modules might help (re, parser, string, fileinput etc) but > > nothing specifically for splitting text files by paragraph. (And how > > do you define a paragraph separator? Is it a blank line or is it an > > indented first line? Both are valid...) > > Depending on the biological sequence files, the paragraph separator > could be a "//" or newlines or any string really. Hi Tzu-Ming, An iterator approach might work here. It's possible to do something like this: ### def breakIntoRecords(read, delimiter): """A generated that, given a read() function (like the one provided by files), will yield records, separated by the given delimiter.""" buffer = [] while True: nextChar = read(1) if not nextChar: break buffer.append(nextChar) if buffer[-len(delimiter):] == list(delimiter): yield ''.join(buffer) buffer = [] if buffer: yield ''.join(buffer) ### Forgive me for the ugly code; it's late. *grin* This uses Python's "generator" support, which allows us to easily write things that can yield chunks of data at a time. The function above will chunk up a file, based on the delimiter we give it. Let's test this function, by using the StringIO module to mimic a string as a file-like object: ### >>> from StringIO import StringIO >>> textFile = StringIO('hello world\nthis is a test\ncan you see this?') >>> print list(breakIntoRecords(textFile.read, '\n')) ['hello world\n', 'this is a test\n', 'can you see this?'] >>> textFile.seek(0) >>> print list(breakIntoRecords(textFile.read, ' ')) ['hello ', 'world\nthis ', 'is ', 'a ', 'test\ncan ', 'you ', 'see ', 'this?'] ### Here, we call 'list()' to make it easy to see how the system is breaking things into records: in reality, we would NOT call list() on the result of breakIntoRecords(), since that would suck everything into memory at once. And that would be bad. *grin* Instead, we'd read it piecemeal, probably in a for loop. Python will read the minimal characters necessary to see the next record, and requests the next chunk by calling next(): ### >>> iterator = breakIntoRecords(textText.read, 'i') >>> iterator.next() 'hello world\nthi' >>> iterator.next() 's i' >>> iterator.next() 's a test\ncan you see thi' >>> iterator.next() 's?' >>> iterator.next() Traceback (most recent call last): File "", line 1, in ? StopIteration ### So just as long as your records aren't larger than system memory, this should be efficient. This solution assumes that your delimiters are static strings. (The function above can be improved: we could probably do better by reading the file as blocks of characters, rather than check for the delimiter on each character read.) > I know in perl there is an input record separator which by default is > the newline and one can specify this to a specific delimiter. Is there > one in python? Not certain. Python has adopted 'universal newlines' support, http://www.python.org/doc/2.3.4/whatsnew/node7.html This allows us to tell Python to guess between the three main standard ways to define a line. So there may be something in Python that we might be able to reuse, to redefine a "line" as something else. But I'm not sure how easily accessible this might be. Good luck to you! From alan.gauld at blueyonder.co.uk Thu Sep 2 08:59:16 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Sep 2 08:59:14 2004 Subject: [Tutor] Listing function arguments References: <00cb01c49025$e6b81570$0d01a8c0@studioaction.local><040701c49066$3603d020$6401a8c0@xp> <000c01c49073$94639710$2901a8c0@atyss> Message-ID: <001601c490ba$5cc1ad50$6401a8c0@xp> > I wanted to know what the funciton uses for paramter names, so I can assign > values to variables of the same name and pass them to the function. I'm still slightly confused about why you want to give the variables the parameter *names*. You shouldn't need to give the variables the same name as the parameters. For example: def f(x=0,y=1,z=2): return x+y+z a = 3 b = 7 c = 42 print f(a,b,c) # -> 52 What is important is the type and sequence of the parameters. The variables passed as arguments can have completely different "names". There is a slight tweak with named parameters where you have a many parameters and want to pass a subset not necessarily in the order specified, and I guess that's what you are trying to do? > Anyway the tips given by Kent and Andrei are exactly what I wanted: > help( myfunction ) And yes that would tell you the parameter names so that you can assign the arguments by name, but you still don't need to name your variables with the same names. Returning to our example: print f(z=b) we assign our variable b to the parameter named z. HTH, Alan G. From alan.gauld at blueyonder.co.uk Thu Sep 2 09:07:03 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Sep 2 09:07:01 2004 Subject: [Tutor] saving program References: <008201c49076$6a3c3d90$bc4ebb18@hochstein> Message-ID: <002201c490bb$7311d890$6401a8c0@xp> Hi Jason, > good afternoon. I was wondering if there was a way to make > a program save the info it gives so when you open it again > it displays the information that was last inputed into the > program. Hmm, there are a couple of possibilities here. Do you mean you want to save the data that the user of your program entered, ie that was captured via raw_input() say, or from reading a file? OR Do you mean you want to save the program commands that you have typed in at the >>> prompt iusing IDLE or Pythonwin?? If the first then you have to write code to save the data into a file and then read it back when your program restarts. If the second then you have to type your program into a new text file (with name ending in .py). IDLE can create those for you from the File->New menu, and you just save the file when you are finished. Next time you start IDLE use File->Open to read it again and carry on working from where you left off.. > So you don't have to start fresh everytime you start the program. I'm guessing from this you are meaning the second scenario but I'm not sure. If you are following my tutorial then I cover this in the "More Sequences" topic. I also cover saving data to files in the "Handling Files" topic! Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From alan.gauld at blueyonder.co.uk Thu Sep 2 09:14:27 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Sep 2 09:14:25 2004 Subject: [Tutor] help-Please help me to read Text From JPEG file References: <000001c49095$91365380$c762013d@h5e1d0> Message-ID: <003101c490bc$7be17100$6401a8c0@xp> > Please help me to write python code to read Text from JPEG file and store to > standard TEXT file. We had this request once before, a long time back, it might be worth searching the archives on ActiveState to see if there was an answer. But basically the "text" in a JPEG is just part of the bitmap pattern encoded using the JPEG compression rules, trying to extract text from a JPEG will be extremely difficult unless the JPEG is limited to a scanned image of a printed page, in which case an OCR program could be used and you might find a library of OCR functions somewhere. But if the text is in a mixed graphics picture - the name of a hotel in a photo say, it will be extremely difficult to extract it from the image. You might fare better if you post to the comp.lang.python group too - this is a bit advanced for the tutor list I suspect! HTH, Alan G. From kent_johnson at skillsoft.com Thu Sep 2 11:50:45 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Sep 2 11:50:57 2004 Subject: [Tutor] Suggestions as to how to read a file in paragraphs In-Reply-To: References: Message-ID: <6.1.0.6.0.20040902054756.029b1878@mail4.skillsoft.com> I took a look at the source code for reading lines from a file (in Objects/fileobject.c/get_line()). The three recognized line endings are hard-coded (the code looks specifically for \r, \n and \r\n) so you can't customize this. Kent At 11:31 PM 9/1/2004 -0700, Danny Yoo wrote: > > I know in perl there is an input record separator which by default is > > the newline and one can specify this to a specific delimiter. Is there > > one in python? > >Not certain. Python has adopted 'universal newlines' support, > > http://www.python.org/doc/2.3.4/whatsnew/node7.html > >This allows us to tell Python to guess between the three main standard >ways to define a line. So there may be something in Python that we might >be able to reuse, to redefine a "line" as something else. But I'm not >sure how easily accessible this might be. > > >Good luck to you! > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From my.mailing.lists at noos.fr Thu Sep 2 13:07:07 2004 From: my.mailing.lists at noos.fr (nik) Date: Thu Sep 2 13:07:16 2004 Subject: [Tutor] converting string to a number In-Reply-To: <6.1.0.6.0.20040902054756.029b1878@mail4.skillsoft.com> References: <6.1.0.6.0.20040902054756.029b1878@mail4.skillsoft.com> Message-ID: <4136FEDB.20400@noos.fr> hi, I have a string that could either be a number or text, and I'd like to test which it is. If I do try: number = string.atof(str) # do my number stuff except: text = str # do my string stuff then it's using the exception handling like an if statement. This feels kinda wrong (hacky or lazy). Is it, or is it an acceptable method in python? nik From s.e.murdock at soton.ac.uk Thu Sep 2 15:25:45 2004 From: s.e.murdock at soton.ac.uk (Stuart Murdock) Date: Thu Sep 2 15:25:57 2004 Subject: [Tutor] First few eigenvectors of Numeric Array Message-ID: <41371F59.5040607@soton.ac.uk> Hi I have a 10000 by 10000 square Numeric array which I have obtained using Numeric python. I need to obtain the first 10 eigenvalues and eigenvectors of this so I dont want to have to calculate all eigenvectors of the matrix. Is anyone aware of any pythonic packages which can calculate, lets say, the 10 eigenvectors corresponding to the top 10 eigenvalues of a Numeric array. Thanks Stuart -- Stuart Murdock Ph.D, Research Fellow, Dept. of Chemistry / E-Science, University of Southampton, Highfield, Southampton, SO17 1BJ, United Kingdom http://www.biosimgrid.org From H.FANGOHR at soton.ac.uk Thu Sep 2 15:35:23 2004 From: H.FANGOHR at soton.ac.uk (Hans Fangohr) Date: Thu Sep 2 15:42:54 2004 Subject: [Tutor] assigning __doc__ strings (manually) In-Reply-To: <4135A047.4010100@po-box.mcgill.ca> References: <4135A047.4010100@po-box.mcgill.ca> Message-ID: Hi Brian, Danny and Kent. Thanks to Kent and Danny for providing a solution and the corresponding explanation to my problem. Brian has responded with an 'orthogonal' question which I'll address above. > Hans Fangohr said unto the world upon 2004-09-01 17:21: >> Greetings, >> >> I am facing the following problem and would like some advise: >> >> I have two functions, say for simplicity, real_f and f: >> >> def real_f(x): >> """this is my doc-string""" >> return x**2, x**3 >> >> def f(x): >> return real_f(x)[0] >> >> >> The actual work is done in real_f() and some users might be interested >> in x**3 and x**2. However, most of the users will only care about x**2 >> and are happy to use the function f() for this. >> >> (In the actual program I am working on there is of course more work >> involved than just computing x**2 and x**3 ...) >> >> Since the main computation is done in real_f(), I thought I'd create a >> doc-string in real_f() that explains the computation being implemented >> etc (as done above). >> > > > >> Hans >> > > Hi Hans, > > I get that your code description was simplified, but I've a question and > possibly a suggestion about it. (All this is orthogonal to your posted > question.) Fair enough. > From what you say, it seems like you are expecting most of the time the > function f() will be the one used, and real_f() will be directly called > much less often. As you describe your setup, f() essentially runs real_f() > and throws away half the work it produces. (Are there needed side-effects > to the "thrown-away" part of real_f() that you didn't mention?) > > In that context, wouldn't it be more efficient to put the computational > work in f() directly and have real_f() call f() and then itself do the > other needed work? > > I mean something like > > def f(x): > return x**2 > > def real_f(x): > return f(x), x**3 > > (Obviously the names you posted are no longer the ones to use in that f() > now really does something itself, but I'm keeping your names structure.) > > It won't matter much for such simple computations as the toy ones of your > post, and I get the "premature optimization is the root of all evil" > point. But still, to this relative newcomer's mind, your structure seems > undesirable. > > So, this is either a request for an explanation of what is wrong with what > I say, or a helpful observation. I leave it to those higher up the > pythonic peaks to determine which ;-) The precise problem is this: the function which I called f is a Runge-Kutta-Fehlberg integrater for ordinary differential equations with adaptive stepsize. To solve the problem dy/dt=g(y,t) one would call the integrator and it returns a vector T and a vector Y (or n vectors if g(y,t) is a n-dimensional vector) and each entry corresponding to one time step. Usually, this information -- lets call it (T,Y) -- is sufficient. Sometimes however, one wants to know the step size (which, admittedly could be computed from T) and -- more importantly -- the error estimate for each integration step. (This is to be used in a teaching context and differs therefore slightly from what you would use in scientific 'production' computation.) The stepsize and errors are readily available when the computation is performed and are usually thrown away. So all in all, my approach outline above is not too far away from the actual problem ;-) However, let me rephrase the challenge: if my integrater function could return a varying number of objects, this would solve my problem very nicely. (I don't think one can do this in Python?) The ideal syntax to call the integrater function RKF would be this: T,Y = RKF( g, t0=0, tfinal=10 ) meaning that the function g(y,t) should be integrated from t=0 to t=10. If one wants to analyse the performance of the integration in more detail, then I'd like to call the function like this: T,Y,log = RKF( g, t0=0, tfinal=10 ) where log could be a dictionary containing all sorts of extra data, or a list of arrays or something along those lines. Does that make things clearer? With the approach I outlined initially, I would have two functions def RKF( g, t0, tfinal ): return RKFLog( g, t0, tfinal)[0:2] and def RKFLog( g, t0, tfinal ): #perform integration return T, Y, log With Kent's help I can synchronise the docstrings across the two functions. However, maybe there are better solutions out there. Cheers, Hans From kent_johnson at skillsoft.com Thu Sep 2 16:09:02 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Sep 2 16:08:51 2004 Subject: [Tutor] assigning __doc__ strings (manually) In-Reply-To: References: <4135A047.4010100@po-box.mcgill.ca> Message-ID: <6.1.0.6.0.20040902095343.0285bdd8@mail4.skillsoft.com> Hans, I don't know of any way for a python function to know how many results the caller is expecting and change its return value accordingly. OTOH a python function can easily return a different type of result depending on the inputs: >>> def evens(i): ... if i%2 == 0: ... return (i, i/2) ... else: ... return '%d is odd' % i ... >>> evens(1) '1 is odd' >>> evens(2) (2, 1) In your case, you could pass another argument to RKF that tells it whether to return the log data or not: def RKF( g, t0, tfinal, returnLog=0): # perform integration if returnLog: return T, Y, log else: return T, Y However, I think this is bad design - it will be confusing to users and error-prone; I think your solution is better. You could also use a class to store the results, then the client code would look something like rkf = RKF( g, t0=0, tfinal=10 ) a, b = rkf.solution log = rkf.log but this seems like overkill to me. Kent At 02:35 PM 9/2/2004 +0100, Hans Fangohr wrote: >> From what you say, it seems like you are expecting most of the time the >>function f() will be the one used, and real_f() will be directly called >>much less often. As you describe your setup, f() essentially runs real_f() >>and throws away half the work it produces. (Are there needed side-effects >>to the "thrown-away" part of real_f() that you didn't mention?) >> >>In that context, wouldn't it be more efficient to put the computational >>work in f() directly and have real_f() call f() and then itself do the >>other needed work? >> >>I mean something like >> >>def f(x): >>return x**2 >> >>def real_f(x): >>return f(x), x**3 >> >>(Obviously the names you posted are no longer the ones to use in that f() >>now really does something itself, but I'm keeping your names structure.) >> >>It won't matter much for such simple computations as the toy ones of your >>post, and I get the "premature optimization is the root of all evil" >>point. But still, to this relative newcomer's mind, your structure seems >>undesirable. >> >>So, this is either a request for an explanation of what is wrong with what >>I say, or a helpful observation. I leave it to those higher up the >>pythonic peaks to determine which ;-) > >The precise problem is this: the function which I called f is a >Runge-Kutta-Fehlberg integrater for ordinary differential equations >with adaptive stepsize. To solve the problem dy/dt=g(y,t) one would >call the integrator and it returns a vector T and a vector Y (or n >vectors if g(y,t) is a n-dimensional vector) and each entry >corresponding to one time step. Usually, this information -- lets call >it (T,Y) -- is sufficient. Sometimes however, one wants to know the >step size (which, admittedly could be computed from T) and -- more >importantly -- the error estimate for each integration step. (This is >to be used in a teaching context and differs therefore slightly from >what you would use in scientific 'production' computation.) > >The stepsize and errors are readily available when the computation is >performed and are usually thrown away. So all in all, my approach >outline above is not too far away from the actual problem ;-) > >However, let me rephrase the challenge: if my integrater function >could return a varying number of objects, this would solve my problem >very nicely. (I don't think one can do this in Python?) > >The ideal syntax to call the integrater function RKF would be this: > >T,Y = RKF( g, t0=0, tfinal=10 ) > >meaning that the function g(y,t) should be integrated from t=0 to t=10. > >If one wants to analyse the performance of the integration in more >detail, then I'd like to call the function like this: > >T,Y,log = RKF( g, t0=0, tfinal=10 ) > >where log could be a dictionary containing all sorts of extra data, or >a list of arrays or something along those lines. > >Does that make things clearer? > >With the approach I outlined initially, I would have two functions > >def RKF( g, t0, tfinal ): > return RKFLog( g, t0, tfinal)[0:2] > >and > >def RKFLog( g, t0, tfinal ): > #perform integration > > return T, Y, log > >With Kent's help I can synchronise the docstrings across the two >functions. However, maybe there are better solutions out there. > >Cheers, > >Hans > From project5 at redrival.net Thu Sep 2 16:39:08 2004 From: project5 at redrival.net (Andrei) Date: Thu Sep 2 16:39:14 2004 Subject: [Tutor] Re: converting string to a number References: <6.1.0.6.0.20040902054756.029b1878@mail4.skillsoft.com> <4136FEDB.20400@noos.fr> Message-ID: nik noos.fr> writes: > I have a string that could either be a number or text, and I'd like to > test which it is. > > If I do > > try: > number = string.atof(str) Gaah, the string module again :). You can simply do: number = float(str) Also, don't use builtins for variable names. str is a builtin. What you do can get you into trouble, e.g. when you wish to convert a number to a string using str(mynumber). Use s instead: number = float(s) If you have doubts about something being a builtin, you can try it in the interactive interpreter, like this: >>> 'str' in dir(__builtins__) True >>> 'apples' in dir(__builtins__) False or like this: >>> help(str) Help on class str in module __builtin__: class str(basestring) | str(object) -> string > # do my number stuff > except: > text = str > # do my string stuff > > then it's using the exception handling like an if statement. This feels kinda wrong (hacky or lazy). It isn't wrong, it's in fact very good. I can't even think of a better way to do it. You'll just need to pay attention to the possibility that "do my number stuff" might cause an exception as well (e.g. if you try to divide something by your number and number happens to be 0, you'll get a ZeroDivisionError), thereby causing the code to interpret your number as a string anyway. Whether you want this or not, I don't know. Yours, Andrei From rob.benton at conwaycorp.net Thu Sep 2 17:04:15 2004 From: rob.benton at conwaycorp.net (Rob Benton) Date: Thu Sep 2 17:03:59 2004 Subject: [Tutor] static PyObject * or non-static Message-ID: <4137366F.5070006@conwaycorp.net> Hey I've been reading through the Extending and Embedding section of the python docs. One thing that keeps appearing is a chunk of code like this: Section 2.1.1 Adding Data and Methods to the Basic Example ================================================================= static PyObject * Noddy_name(Noddy* self) { static PyObject *format = NULL; PyObject *args, *result; if (format == NULL) { format = PyString_FromString("%s %s"); if (format == NULL) return NULL; } ... } ================================================================= I'm curious as to why the format PyObject * is made static. Should I make everything static that can be? I didn't know if maybe there was a reason for doing that. From kent_johnson at skillsoft.com Thu Sep 2 17:34:01 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Sep 2 17:34:07 2004 Subject: [Tutor] Re: converting string to a number In-Reply-To: References: <6.1.0.6.0.20040902054756.029b1878@mail4.skillsoft.com> <4136FEDB.20400@noos.fr> Message-ID: <6.1.0.6.0.20040902105117.029f2ce0@mail4.skillsoft.com> At 02:39 PM 9/2/2004 +0000, Andrei wrote: >If you have doubts about something being a builtin, you can try it in the >interactive interpreter, like this: > > >>> 'str' in dir(__builtins__) > True > >>> 'apples' in dir(__builtins__) > False or just type the name itself: >>> str >>> apples Traceback (most recent call last): File "", line 1, in ? NameError: name 'apples' is not defined > > # do my number stuff > > except: > > text = str > > # do my string stuff > > > > then it's using the exception handling like an if statement. This feels > kinda >wrong (hacky or lazy). > >It isn't wrong, it's in fact very good. I can't even think of a better way >to do >it. You'll just need to pay attention to the possibility that "do my number >stuff" might cause an exception as well (e.g. if you try to divide >something by >your number and number happens to be 0, you'll get a ZeroDivisionError), >thereby >causing the code to interpret your number as a string anyway. Whether you want >this or not, I don't know. To guard against these possibilities, you can do two things: 1. Catch the actual exception that will be thrown (ValueError) instead of catching everything. 2. Use try / except / else to remove "do my number stuff" from the try block, so any exception thrown from it (even ValueError) will be propagated to the caller. Like this: >>> def maybeNumber(val): ... try: ... number = float(val) ... except ValueError: ... text = val ... print text, 'is a string' ... else: ... print number, 'is a number' ... >>> maybeNumber(1) 1.0 is a number >>> maybeNumber('ab') ab is a string Kent (who is finally starting to understand what try / except / else is good for...) From my.mailing.lists at noos.fr Thu Sep 2 18:01:24 2004 From: my.mailing.lists at noos.fr (nik) Date: Thu Sep 2 18:01:29 2004 Subject: [Tutor] Re: converting string to a number In-Reply-To: <6.1.0.6.0.20040902105117.029f2ce0@mail4.skillsoft.com> References: <6.1.0.6.0.20040902054756.029b1878@mail4.skillsoft.com> <4136FEDB.20400@noos.fr> <6.1.0.6.0.20040902105117.029f2ce0@mail4.skillsoft.com> Message-ID: <413743D4.6050605@noos.fr> Kent Johnson wrote: > At 02:39 PM 9/2/2004 +0000, Andrei wrote: > >> If you have doubts about something being a builtin, you can try it in >> the >> interactive interpreter, like this: >> >> >>> 'str' in dir(__builtins__) >> True >> >>> 'apples' in dir(__builtins__) >> False > > > or just type the name itself: > >>> str > > >>> apples > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'apples' is not defined > >> > # do my number stuff >> > except: >> > text = str >> > # do my string stuff >> > >> > then it's using the exception handling like an if statement. This >> feels kinda >> wrong (hacky or lazy). >> >> It isn't wrong, it's in fact very good. I can't even think of a >> better way to do >> it. You'll just need to pay attention to the possibility that "do my >> number >> stuff" might cause an exception as well (e.g. if you try to divide >> something by >> your number and number happens to be 0, you'll get a >> ZeroDivisionError), thereby >> causing the code to interpret your number as a string anyway. Whether >> you want >> this or not, I don't know. > > > To guard against these possibilities, you can do two things: > 1. Catch the actual exception that will be thrown (ValueError) instead > of catching everything. > 2. Use try / except / else to remove "do my number stuff" from the try > block, so any exception thrown from it (even ValueError) will be > propagated to the caller. > > Like this: > >>> def maybeNumber(val): > ... try: > ... number = float(val) > ... except ValueError: > ... text = val > ... print text, 'is a string' > ... else: > ... print number, 'is a number' > ... > >>> maybeNumber(1) > 1.0 is a number > >>> maybeNumber('ab') > ab is a string > > Kent (who is finally starting to understand what try / except / else > is good for...) > > Thanks for the advice guys, I hadn't thought of what would happen if it wasn't the exception you were expecting. It still feels uncomfortable though, I've always felt an exception is *exceptional*, ie something that was outside your control. However, I'm happy enough now to go and use it... nik From alan.gauld at blueyonder.co.uk Thu Sep 2 18:29:30 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Sep 2 18:29:23 2004 Subject: [Tutor] static PyObject * or non-static References: <4137366F.5070006@conwaycorp.net> Message-ID: <00a501c4910a$06853470$6401a8c0@xp> > static PyObject * > Noddy_name(Noddy* self) > { > static PyObject *format = NULL; > PyObject *args, *result; > I'm curious as to why the format PyObject * is made static. One of the features of a static variable inside a function is that it retains its value between function calls. Basically static assigns storage on the heap rather than the stack. Most function data is on the stack so that when a function call ends all the data on the stack gets unwound and lost, but the heap data persists. > make everything static that can be? No that will only waste memory. temporary variables within functions should go on the stack so that they can be deleted. Alan G. From python at bernardlebel.com Thu Sep 2 20:36:31 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Thu Sep 2 19:34:09 2004 Subject: [Tutor] Listing function arguments References: <00cb01c49025$e6b81570$0d01a8c0@studioaction.local><040701c49066$3603d020$6401a8c0@xp> <000c01c49073$94639710$2901a8c0@atyss> <001601c490ba$5cc1ad50$6401a8c0@xp> Message-ID: <001301c4911b$c66181c0$2901a8c0@atyss> Hi Alan, The ultimate end to my question was to know the actual order of arguments. I know I can send a,b,c, as values for parameters x,y,z. However, I want to know in what order I have to supply values for the function to work. If I supply the wrong value to a given parameter, I won't go very far :-) In this case, I need to know if sSource is before or after sTarget, and on the same roll why not check if there are arguments I may have forgotten. Plus, the help() function is great, but I know document each parameter in the doc string, so I can see if I make a mistake. Thanks for the help! Bernard ----- Original Message ----- From: "Alan Gauld" To: "Bernard Lebel" ; Sent: Thursday, September 02, 2004 7:59 AM Subject: Re: [Tutor] Listing function arguments > > I wanted to know what the funciton uses for paramter names, so I can > assign > > values to variables of the same name and pass them to the function. > > I'm still slightly confused about why you want to give the > variables the parameter *names*. You shouldn't need to give the > variables the same name as the parameters. > For example: > > def f(x=0,y=1,z=2): return x+y+z > > a = 3 > b = 7 > c = 42 > > print f(a,b,c) # -> 52 > > What is important is the type and sequence of the parameters. > The variables passed as arguments can have completely different > "names". There is a slight tweak with named parameters > where you have a many parameters and want to pass a subset > not necessarily in the order specified, and I guess that's what > you are trying to do? > > > Anyway the tips given by Kent and Andrei are exactly what I wanted: > > help( myfunction ) > > And yes that would tell you the parameter names so that you can > assign the arguments by name, but you still don't need to name > your variables with the same names. Returning to our example: > > print f(z=b) > > we assign our variable b to the parameter named z. > > HTH, > > Alan G. > > > From Mark.Kels at gmail.com Thu Sep 2 19:52:15 2004 From: Mark.Kels at gmail.com (Mark Kels) Date: Thu Sep 2 19:52:33 2004 Subject: [Tutor] A problem with saveing data for later use. Message-ID: Hello, first,I want to apologize for my bad english. I'm from a non-englishe country (israel) so I dont speak englise very wel. and now the problem: I want to make a simple personal organizer (no GUI) that have address book,calendar etc. The problem is that I dont know how to save the data that comes from the user. And a personal organizer cant work if it doest "remembers" the info that the user iputs... If anyone has an idea i'll be more then happy to read it. I'm sorry if you dont understand the question... let me know if you dont,and I'll try to rewrite it. thanks!! From askoose at sandia.gov Thu Sep 2 20:01:30 2004 From: askoose at sandia.gov (Kooser, Ara S) Date: Thu Sep 2 20:01:50 2004 Subject: [Tutor] beginner help!!!! Message-ID: <9A4B2157EFDBE546BECD68C62AC3B1C81738F457@es05snlnt.sandia.gov> Could you post the code and the error message. Thanks "There is something to be learned from a rainstorm. When meeting with a sudden shower, you try not to get wet and run quickly along the road. But doing such things as passing under the eaves of houses, you still get wet. When you are resolved from the beginning, you will not be perplexed, though you still get the same soaking." - Yamamoto Tsunetomo -----Original Message----- From: Jill and Paul [mailto:bear4@zoominternet.net] Sent: Saturday, August 28, 2004 7:04 PM To: tutor@python.org Subject: [Tutor] beginner help!!!! I am very new at learning Python and I am trying to type in a program for practice. It has "else:" in it and I keep getting either a syntax error message or an indentation error no matter what I do. HELP!!!!! Jill -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040902/d1cea46a/attachment.htm From dyoo at hkn.eecs.berkeley.edu Thu Sep 2 20:17:14 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Sep 2 20:17:19 2004 Subject: [Tutor] beginner help!!!! In-Reply-To: <9A4B2157EFDBE546BECD68C62AC3B1C81738F457@es05snlnt.sandia.gov> Message-ID: On Thu, 2 Sep 2004, Kooser, Ara S wrote: > Could you post the code and the error message. Thanks Hi Jill, Yes, we need to see your code. I suspect it might be an indentation problem, but without seeing your code, I can't make any solid remarks either. Feel free to just copy and paste it in your reply. About the error message stuff: don't parapharse the error: show it to us as it comes. For example, here's the kind of error message we like to see: ### Traceback (most recent call last): File "", line 1, in ? NameError: name 'oracle' is not defined ### In contrast, if we paraphrase the error message to just: "There's a Name Error somewhere in my program", then that's not as helpful to us. The real error message itself has told us what appears to be undefined, and on what line the problems appear to start. The paraphrase, on the other hand, just tells us that something's wrong, but doesn't tell us where to look. In this case, originality is not a good thing: it's good not to suppress that information in paraphrase. Instead, just copy-and-paste the error, around where the "Traceback" starts. Good luck! From dyoo at hkn.eecs.berkeley.edu Thu Sep 2 20:22:34 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Sep 2 20:23:40 2004 Subject: [Tutor] names In-Reply-To: <000601c48ece$2e2f3770$121c8645@oemcomputer> Message-ID: On Mon, 30 Aug 2004, Diana Furr wrote: > How do you get Python to let name=(anyone's name) > > I saw some posts on this subject but didn't find an answer. Hi Diana, Can you point us to one of those posts? I'm not quite sure what you mean yet, and maybe the context will help. Are you trying to do something like this? ### >>> game = "frogger" >>> game 'frogger' ### Here, we can assign the string value "frogger" to the variable name 'game'. Is this what you're looking for? From kent_johnson at skillsoft.com Thu Sep 2 20:31:33 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Sep 2 20:31:40 2004 Subject: [Tutor] names In-Reply-To: <000601c48ece$2e2f3770$121c8645@oemcomputer> References: <000601c48ece$2e2f3770$121c8645@oemcomputer> Message-ID: <6.1.0.6.0.20040902143025.028a54c0@mail4.skillsoft.com> If you want the user to be able to type in her name, use raw_input(): >>> name = raw_input('What is your name? ') What is your name? Kent >>> name 'Kent' At 04:16 PM 8/30/2004 -0400, Diana Furr wrote: >How do you get Python to let name=(anyone's name) >I saw some posts on this subject but didn't find an answer. >Thank you, >Diana >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Thu Sep 2 20:36:06 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Sep 2 20:36:12 2004 Subject: [Tutor] First few eigenvectors of Numeric Array In-Reply-To: <41371F59.5040607@soton.ac.uk> Message-ID: On Thu, 2 Sep 2004, Stuart Murdock wrote: > I have a 10000 by 10000 square Numeric array which I have obtained using > Numeric python. I need to obtain the first 10 eigenvalues and > eigenvectors of this so I dont want to have to calculate all > eigenvectors of the matrix. Is anyone aware of any pythonic packages > which can calculate, lets say, the 10 eigenvectors corresponding to the > top 10 eigenvalues of a Numeric array. Hi Stuart, Yikes! *grin* This sounds like a really specialized question; I'm not sure if many of us here can help. You may want to ask this question on the Scientific Python (SciPy) mailing list: http://www.scipy.org/ Isn't Numeric Python now deprecated in favor of the Numarray project, though? http://www.stsci.edu/resources/software_hardware/numarray Numarray does provide a function to grab eigenvalues and eigenvectors: http://stsdas.stsci.edu/numarray/Doc/node64.html and Numeric Python has similar functions: http://www.pfdubois.com/numpy/html2/numpy-18.html#pgfId-303058 but neither appear to allow a 'N max eigenvalues' style query. I don't personally have the math background to point out how to make that work. I'd ask on SciPy, where that community may be better equipped to help. Best of wishes to you! From kent_johnson at skillsoft.com Thu Sep 2 20:54:32 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Sep 2 20:54:59 2004 Subject: [Tutor] python editor In-Reply-To: <4eb23360040822013612cc10c2@mail.gmail.com> References: <4eb23360040822013612cc10c2@mail.gmail.com> Message-ID: <6.1.0.6.0.20040902144737.02856ad0@mail4.skillsoft.com> There are many editors that work well with Python. Which one is best is a matter of (sometimes strong!) personal preference. If you have a text editor you like, it may well have Python support available. Here is a list to get you started. Many of the editors are free or have trial versions, so you can try a few and find one you like. http://www.python.org/moin/PythonEditors Python web programming is another big topic. If you can give us some idea what you want to do maybe we can help you better. For simple projects the cgi module might be all you need. For more complex projects there are many frameworks available. Here is a list: http://www.python.org/cgi-bin/moinmoin/WebProgramming HTH Kent At 12:06 PM 8/22/2004 +0330, Meisam GanjeAli wrote: >hello >what is the best pythin editor, and how can i extend my ability for >python programming for web? >thanks for your help. >bye. >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From bill at celestial.net Thu Sep 2 20:59:34 2004 From: bill at celestial.net (Bill Campbell) Date: Thu Sep 2 20:59:40 2004 Subject: [Tutor] spitshell for python Message-ID: <20040902185934.GB93162@alexis.mi.celestial.com> Someplace in the python.org documentation I saw something analagous to the perl idiom to start python from a script, but I couldn't find it recently when I wanted to use it. The main reason I use this is that I have a key mapping in vi[m] that does ``:!sh -x %'' to test scripts, and I would like to have the same think work for python as it now does for shell and perl. The perl version starts out something like: #!/usr/local/bin/perl eval ' exec /usr/local/bin/perl -....' Bill -- INTERNET: bill@Celestial.COM Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ It is necessary for the welfare of society that genius should be privileged to utter sedition, to blaspheme, to outrage good taste, to corrupt the youthful mind, and generally to scandalize one's uncles. -- George Bernard Shaw From kent_johnson at skillsoft.com Thu Sep 2 21:00:03 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Sep 2 21:00:28 2004 Subject: [Tutor] A problem with saveing data for later use. In-Reply-To: References: Message-ID: <6.1.0.6.0.20040902145454.02a02de8@mail4.skillsoft.com> The shelve module might work for you. Here is a short article showing how to create a simple address book using shelve: http://www.wdvl.com/Authoring/Languages/Python/Quick/python6_3.html If shelve is not adequate you probably want to use a database such as MySQL to store the data. Kent At 07:52 PM 9/2/2004 +0200, Mark Kels wrote: >Hello, >first,I want to apologize for my bad english. >I'm from a non-englishe country (israel) so I dont speak englise very wel. > >and now the problem: >I want to make a simple personal organizer (no GUI) that have address >book,calendar etc. >The problem is that I dont know how to save the data that comes from the user. >And a personal organizer cant work if it doest "remembers" the info >that the user iputs... >If anyone has an idea i'll be more then happy to read it. > >I'm sorry if you dont understand the question... >let me know if you dont,and I'll try to rewrite it. > >thanks!! >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From pythonTutor at venix.com Thu Sep 2 21:05:14 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Thu Sep 2 21:05:23 2004 Subject: [Tutor] A problem with saveing data for later use. In-Reply-To: References: Message-ID: <1094151914.3782.8.camel@laptop.venix.com> The solution to how to save your data depends upon the data and how it is used. The tutorials will teach you how to use files. A file is the basic tool for saving data. There is a good chance that the shelve module can help with saving data for a personal organizer. You can read about shelve in the Library Reference Manual. Your first step is to figure out what your data looks like and how it will be used. This can be a tough first project, depending upon how fancy you need this organizer to be. On Thu, 2004-09-02 at 13:52, Mark Kels wrote: > Hello, > first,I want to apologize for my bad english. > I'm from a non-englishe country (israel) so I dont speak englise very wel. > > and now the problem: > I want to make a simple personal organizer (no GUI) that have address > book,calendar etc. > The problem is that I dont know how to save the data that comes from the user. > And a personal organizer cant work if it doest "remembers" the info > that the user iputs... > If anyone has an idea i'll be more then happy to read it. > > I'm sorry if you dont understand the question... > let me know if you dont,and I'll try to rewrite it. > > thanks!! > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 320-210-3409 (changed Aug 26, 2004) From mhansen at cso.atmel.com Thu Sep 2 21:07:34 2004 From: mhansen at cso.atmel.com (Mike Hansen) Date: Thu Sep 2 21:07:30 2004 Subject: [Tutor] beginner help!!!! In-Reply-To: <20040902181722.433451E4016@bag.python.org> References: <20040902181722.433451E4016@bag.python.org> Message-ID: <41376F76.3040003@cso.atmel.com> Are you using IDLE's Python Shell to type in your program? If so, you can get a little hung up with typing if else statements. IDLE 1.0.3 >>> x = 1 >>> if x == 1: print "something" else: SyntaxError: invalid syntax >>> if x == 1: print "something" else: print "something else" something >>> I had to type a backspace at the line I wanted the else clause to be placed. You need to assume the >>> prompt isn't there when getting the indentation lined up when using the Python Shell. If you aren't using the Python Shell, then ignore this post. Mike > -----Original Message----- > *From:* Jill and Paul [mailto:bear4@zoominternet.net] > *Sent:* Saturday, August 28, 2004 7:04 PM > *To:* tutor@python.org > *Subject:* [Tutor] beginner help!!!! > > I am very new at learning Python and I am trying to type in a > program for practice. It has "else:" in it and I keep getting > either a syntax error message or an indentation error no matter > what I do. HELP!!!!! > > Jill > > From jeff at ccvcorp.com Thu Sep 2 21:18:13 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu Sep 2 21:16:58 2004 Subject: [Tutor] assigning __doc__ strings (manually) In-Reply-To: <6.1.0.6.0.20040902095343.0285bdd8@mail4.skillsoft.com> References: <4135A047.4010100@po-box.mcgill.ca> <6.1.0.6.0.20040902095343.0285bdd8@mail4.skillsoft.com> Message-ID: <413771F5.3000109@ccvcorp.com> > At 02:35 PM 9/2/2004 +0100, Hans Fangohr wrote: > >> The ideal syntax to call the integrater function RKF would be this: >> >> T,Y = RKF( g, t0=0, tfinal=10 ) >> >> meaning that the function g(y,t) should be integrated from t=0 to t=10. >> >> If one wants to analyse the performance of the integration in more >> detail, then I'd like to call the function like this: >> >> T,Y,log = RKF( g, t0=0, tfinal=10 ) >> >> where log could be a dictionary containing all sorts of extra data, or >> a list of arrays or something along those lines. Depending on your particular usage, it may also be reasonable to simply always return the extra data, and leave it up to the calling code to either use it or discard it: T, Y = RKF( g, t0= 0, tfinal=10 )[:2] or T, Y, _ = RKF( g, t0= 0, tfinal=10 ) I'm thinking in particular of the standard library function os.path.splitext(), which splits a file extension from a path/file name. It returns both the base name (without the extension) and the extension even though most of the time that this is used, the extension itself is all that's needed and the base name is just thrown away. This does suffer from feeling a bit less "clean", since you're constantly throwing stuff away. On the other hand, it spares you having two very-similar-purpose functions, and makes the act of discarding unneeded data more explicit. Jeff Shannon Technician/Programmer Credit International From jeff at ccvcorp.com Thu Sep 2 21:27:07 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu Sep 2 21:25:52 2004 Subject: [Tutor] Re: converting string to a number In-Reply-To: <413743D4.6050605@noos.fr> References: <6.1.0.6.0.20040902054756.029b1878@mail4.skillsoft.com> <4136FEDB.20400@noos.fr> <6.1.0.6.0.20040902105117.029f2ce0@mail4.skillsoft.com> <413743D4.6050605@noos.fr> Message-ID: <4137740B.1080202@ccvcorp.com> nik wrote: > Thanks for the advice guys, I hadn't thought of what would happen if it > wasn't the exception you were expecting. It still feels uncomfortable > though, I've always felt an exception is *exceptional*, ie something > that was outside your control. The feeling you have is consistent with how *most* languages use exceptions, so it's entirely understandable. However, Python exceptions are less costly than many other languages' exceptions, so it's a fairly standard control-flow mechanism in Python. Indeed, you may not realize it, but even basic control structures are built on top of exceptions. As an example, for and while loops use a StopIteration exception to indicate that they are done. The handling for this is automatically created in the bytecode and is thus hidden from the normal user, but if you peek under the covers, it's there. So yes, this is a perfectly acceptable usage of exceptions -- Python tends to follow the old truism that "It's easier to ask for forgiveness than for permission" -- in most cases, it's more straightforward to try an action and catch the exception if it doesn't work, than it is to check ahead of time whether the action will work. Jeff Shannon Technician/Programmer Credit International From alan.gauld at blueyonder.co.uk Thu Sep 2 22:32:35 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Sep 2 22:32:25 2004 Subject: [Tutor] A problem with saveing data for later use. References: Message-ID: <00c001c4912b$fb5e9ec0$6401a8c0@xp> > I want to make a simple personal organizer (no GUI) that have address > book,calendar etc. > The problem is that I dont know how to save the data that comes from the user. Take a look at the new Handling Files topic in my tutor, it has an example of a simple address book complete with saving and restoring the data. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From alan.gauld at blueyonder.co.uk Thu Sep 2 22:39:36 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Sep 2 22:39:27 2004 Subject: [Tutor] Static Variables References: Message-ID: <00c501c4912c$f67b49c0$6401a8c0@xp> > By the way, would anyone guide me how to become a pro in C Experience. As the guy who looks after the lawns at Wimbledon tennis court says when asked how to get the same quality of lawn: "Water regularly, Cut regularly, Feed rgularly and repeat for 300 years... " C programming doesn't take so long but it does take experience. Reading a lot of code of different types helps - try the Python source code, and other sourceforge projects. Look at the Linux kernel code. Working in partnership with experienced programmers helps too but is hard for a casual programmer to do in practice. There aren't any magic books but a few to consider are: Programming Pearls by Jon Bentley - not all C but sound programming practice The Practice of Programming - Kernighan & Pike The Pragmatic Programmer. All of these are quite short but packed full of advise to lift the amateur up towards pro standards. And finally a book every coder should read: Code Complete by McConnell - possibly the best thing to ever come from Microsoft! :-) If you were doing C++ I'd also recommend Herb Sutter's pair of books. Alan G. From dyoo at hkn.eecs.berkeley.edu Thu Sep 2 22:41:19 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Sep 2 22:43:28 2004 Subject: [Tutor] Static Variables In-Reply-To: Message-ID: > By the way, would anyone guide me how to become a pro in C (an e-book, > some maillists, some hints or just whatever you think may be helpful)? Hi Ashkan, Read Python's C implementation. *grin* I'm actually a little serious about this: I learned quite a bit about C by seeing how Python was implemented in it. It's amazing how much work goes into some of the features in Python; it makes me all the more glad that I don't have to work at that level... usually. In general, read other people's code, and write good programs: I think that's a pretty steady way to get better at programming in any language. There's an abundance of Open Source code out there: I'd recommend taking advantage of it. > I read Kernighan and Ritchie's "THE C PROGRAMMING LANGUAGE", but I need > something that makes me a real man!! If reading K&R doesn't improve your macho rating, I don't know what will. *grin* But if you want to read another book, I'd recommend 'Programming Pearls': http://www.cs.bell-labs.com/cm/cs/pearls/ One can only go so far with just reading, though: to get better, you'll need to apply what you've read. Pick a project that you like to work on, and go with it. Good luckt oyou! From alan.gauld at blueyonder.co.uk Thu Sep 2 23:44:32 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Sep 2 23:44:21 2004 Subject: [Tutor] How can I catch a Windows event? References: <1093770234.16895@gar.st.nograd.net> Message-ID: <00d401c49136$08c7f480$6401a8c0@xp> > I am new in computing and python. My problem is during > switching off/ restaring Win 98 the phyton script written by me > doesn?t stop. (in Win XP. no problem) Caveat: The following are personal observations which are not based on deep knowledge but my own painful experience. OK, How are you running the program? Is it starting as a service or as a regular program from the start menu or Startup group? Also how are you switching Windows off? Windows 98 is not very well behaved at the best of times and doesn't like threads much at all, barely tolerates them some would say! So unless your main program keeps track of all the threads you start and closes them down properly you will have problems, especially if somebody just hits the off switch.. > I guess it is because of a thread. By checking from the internet > I found the WM_QUERYENDSESSION should be caught for regular > stopping, but I do not understand how. Are you running a GUI or console application? Console apps don't get windows events like Windows apps do under '98 - they do in XP since the console is really a windows app, but in '9x they are glorified DOS boxes so you need to pick up the DOS interrupt handler. Unfortunately this is difficult from normal code! > I am also not sure, which I should use win 32all or wxPython. Win32all is the package if you want to mess with low level windows events. OTOH wxPython should trap the message for you and close down cleanly. > The following script stops the win98 shutdown process > if I start the script from consol. That should be because Windows sees the console running a background process and knows it can't stop it so it just kind of gives up and asks you to kill it. This regularly happens to me if I run Cygwin with background jobs! It's what's supposed to happen and is "A Good Thing" IMHO. The alternative would be fore Windows to just kill the application outright when it migt be in the middle of a major file operation and thus destroy reams of data... If you want better behaviour you need to turn your app into a proper GUI and catch the events from Windows. I'mn not sure if that clarifies or confuses further! Alan G. From rha207 at yahoo.com Thu Sep 2 23:45:56 2004 From: rha207 at yahoo.com (Ron A) Date: Thu Sep 2 23:45:58 2004 Subject: [Tutor] help with __str__ Message-ID: <20040902214556.63574.qmail@web50906.mail.yahoo.com> This is from the book "Python Programming for the absolute beginner" slightly modified. It's concantenating rank and suit each time you create a new card and it seems to be doing it without having to use print card each time. How is the str method being used without using print? I'm really getting confused now. Ron A # Playing Cards # Demonstrates combining objects # Michael Dawson - 4/9/03 class Card(object): """ A playing card. """ def __init__(self, rank, suit): self.rank = rank self.suit = suit def __str__(self): rep = self.rank + self.suit return rep class Hand(object): """ A hand of playing cards. """ def __init__(self): self.cards = [] def __str__(self): if self.cards: rep = "" for card in self.cards: rep += str(card) + " " else: rep = "" return rep def clear(self): self.cards = [] def add(self, card): self.cards.append(card) def give(self, card, other_hand): self.cards.remove(card) other_hand.add(card) # main card1 = Card(rank = "A", suit = "c") card2 = Card(rank = "2", suit = "c") card3 = Card(rank = "3", suit = "c") card4 = Card(rank = "4", suit = "c") card5 = Card(rank = "5", suit = "c") my_hand = Hand() my_hand.add(card1) my_hand.add(card2) my_hand.add(card3) my_hand.add(card4) my_hand.add(card5) print "\nPrinting my hand after adding 5 cards:" print my_hand your_hand = Hand() my_hand.give(card1, your_hand) my_hand.give(card2, your_hand) print "\nGave the first two cards from my hand to your hand." print "Your hand:" print your_hand print "My hand:" print my_hand my_hand.clear() print "\nMy hand after clearing it:" print my_hand raw_input("\n\nPress the enter key to exit.") __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From alan.gauld at blueyonder.co.uk Thu Sep 2 23:47:58 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Sep 2 23:47:46 2004 Subject: [Tutor] spitshell for python References: <20040902185934.GB93162@alexis.mi.celestial.com> Message-ID: <00f201c49136$83706820$6401a8c0@xp> > mapping in vi[m] that does ``:!sh -x %'' to test scripts, and I would like > to have the same think work for python as it now does for shell and perl. > > The perl version starts out something like: > > #!/usr/local/bin/perl > eval ' exec /usr/local/bin/perl -....' I'm no perl hacker but does execfile() do what you need? Alan G From alan.gauld at blueyonder.co.uk Thu Sep 2 23:50:54 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Sep 2 23:50:49 2004 Subject: [Tutor] Re: converting string to a number References: <6.1.0.6.0.20040902054756.029b1878@mail4.skillsoft.com> <4136FEDB.20400@noos.fr> <6.1.0.6.0.20040902105117.029f2ce0@mail4.skillsoft.com><413743D4.6050605@noos.fr> <4137740B.1080202@ccvcorp.com> Message-ID: <00ff01c49136$ecb409e0$6401a8c0@xp> > Indeed, you may not realize it, but even basic control structures are > built on top of exceptions. As an example, for and while loops use a > StopIteration exception to indicate that they are done. I didn't realize it! Thanks for that bit of insight Jeff. Interesting indeed! Alan G. From adam at monkeez.org Thu Sep 2 23:53:05 2004 From: adam at monkeez.org (Adam) Date: Thu Sep 2 23:53:12 2004 Subject: [Tutor] String to integer? In-Reply-To: <002201c49069$bcf7aa90$2901a8c0@atyss> References: <27761.217.206.168.163.1094043268.spork@webmail.monkeez.org><00b201c49023$ad72bf10$0d01a8c0@studioaction.local> <413622E1.2020300@monkeez.org> <002201c49069$bcf7aa90$2901a8c0@atyss> Message-ID: <41379641.2030102@monkeez.org> Bernard Lebel wrote: > Hi Adam, > > Sorry for the learning curve, I should have mentioned that the tutorial that > comes with the documentation covers dictionaries. That would have saved you > some time I guess. My bad. > > Cheers > Bernard > > > ----- Original Message ----- > From: "Adam" > Cc: > Sent: Wednesday, September 01, 2004 8:28 PM > Subject: Re: [Tutor] String to integer? > > > >>Bernard Lebel wrote: >> >> >>>Personally I'd consider using a dictionary for that. Assign the letter > > (the > >>>key) to the number (the value). >>> >>> >>>Cheers >>>Bernard >>> >> >>Bernard, >> >>The dictionary worked a treat (although I had to spend half an hour >>working it out). >> >>Many thanks >> >>Adam Bernard, Not your bad at all - it's just my cranky brain trying to get back in to programming after such a long time away. Thanks again. Adam -- site: http://www.monkeez.org wiki: http://wiki.monkeez.org From alan.gauld at blueyonder.co.uk Thu Sep 2 23:56:24 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Sep 2 23:56:12 2004 Subject: [Tutor] My tutorial Message-ID: <010701c49137$b0dbcc40$6401a8c0@xp> For those who are interested I just uploaded the final installment of the re-wtritten tutor. (Its not quite done because I need to do a brand new topic on regular expressions, which I now use in the case study). I will be tidying up loose ends and reorganising the site over the next few weeks so that the rewrite and original tutors effectively swap position. After that I intend to add a new section with topics on practical applications of Python - the os module, XML and CGI programming, some sockets and urllib etc. But as it stands now the new version is effectively completely rewritten wrt the original. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From dyoo at hkn.eecs.berkeley.edu Fri Sep 3 00:07:28 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Sep 3 00:07:32 2004 Subject: [Tutor] help with __str__ In-Reply-To: <20040902214556.63574.qmail@web50906.mail.yahoo.com> Message-ID: On Thu, 2 Sep 2004, Ron A wrote: > This is from the book "Python Programming for the absolute beginner" > slightly modified. It's concantenating rank and suit each time you > create a new card and it seems to be doing it without having to use > print card each time. How is the str method being used without using > print? I'm really getting confused now. Hi Ron, The '__str__' method of a method does fire off when we print out a thing... but it also fires off if we call the str() "string conversion" on something. For example: ### >>> class TestStr: ... def __str__(self): ... print "*** DEBUG: __str__ is firing off!***" ... return "TestStr instance" ... >>> t = TestStr() >>> print t *** DEBUG: __str__ is firing off!*** TestStr instance >>> value = str(t) *** DEBUG: __str__ is firing off!*** >>> ### Does this make sense? __str__() is used by both Python's "print" statement and the 'str()' builtin function, and your code is calling str() on things. We'd use str() if we want to get at the string value, but not necessarily print out to screen. For example, there are other things we can do to a string value besides print it out directly: ### >>> str(t) * 3 *** DEBUG: __str__ is firing off!*** 'TestStr instanceTestStr instanceTestStr instance' >>> len(str(t)) *** DEBUG: __str__ is firing off!*** 16 ### One thing to realize is that 'print' itself does not give us a value. It's something that works as a "side-effect": we see the thing that's being printed, but otherwise, printing doesn't have a "value". Here are things that have values: ### >>> 3 * 4 12 >>> 'ha' * 7 'hahahahahahaha' ### These things are "expressions": they're calculations that result in a new value. We usually try to write our functions so that they return values. ### >>> def square(x): ... return x * x ... >>> result = square(42) >>> result 1764 ### 'print' is different: it just prints to screen, but has no real value: ### >>> def printSquare(x): ... print x * x ... >>> result = printSquare(42) 1764 >>> print result None ### We'd say that printSquare() has a "side-effect" of displaying the square of a number on screen, but doesn't give back a useful value to us. That's what 'None' is about. The main different between the two here is that square() can easily be used in some larger computation, but printSquare() can't: ### >>> (square(3) + square(4)) ** 0.5 5.0 >>> (printSquare(3) + printSquare(4)) ** 0.5 9 16 Traceback (most recent call last): File "", line 1, in ? TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType' ### So that's why all of the functions in your program try not to just "print" their computation: rather, they actually try to "return" the value to the caller. Most people try to get their functions to 'return' values because such functions often end up being more useful than ones that only print to screen. If you have more questions, please feel free to ask. Good luck! From kent_johnson at skillsoft.com Fri Sep 3 00:16:40 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Sep 3 00:16:49 2004 Subject: [Tutor] help with __str__ In-Reply-To: <20040902214556.63574.qmail@web50906.mail.yahoo.com> References: <20040902214556.63574.qmail@web50906.mail.yahoo.com> Message-ID: <6.1.0.6.0.20040902180128.02899e10@mail4.skillsoft.com> Ron, Class methods whose names start and end with __ are called "special methods". They allow you to customize the way python uses your class. One thing you might want to customize is the string representation of your class. This is the string you get when you call str(xx) where xx is an instance of the class. It is also the string that prints when you say "print xx". On its own, Python is pretty simple-minded about how to display an instance of a class - it will just show you the module and class names and the actual memory address of the instance: >>> class A: ... pass ... >>> a=A() >>> print a <__main__.A instance at 0x007CF9E0> If the class defines a __str__ method, Python will call it when you call str() or print: >>> class B: ... def __str__(self): ... return "I'm a B!" ... >>> b=B() >>> print b I'm a B! To recap: when you tell Python to "print b", Python calls str(b) to get the string representation of b. If the class of b has a __str__ method, str(b) becomes a call to b.__str__(). This returns the string to print. You can get the string representation yourself by calling str() directly. This is what is happening in Hand.__str__() - it calls str() for each of the cards in the hand (which becomes a call to Card.__str__()), puts all the card strings together into one string, and uses that as the string for the whole hand. Kent At 02:45 PM 9/2/2004 -0700, Ron A wrote: >This is from the book "Python Programming for the >absolute beginner" >slightly modified. It's concantenating rank and suit >each time you create a >new card and it seems to be doing it without having to >use print card each >time. >How is the str method being used without using >print? I'm really >getting confused now. > >Ron A > ># Playing Cards ># Demonstrates combining objects ># Michael Dawson - 4/9/03 > >class Card(object): > """ A playing card. """ > def __init__(self, rank, suit): > self.rank = rank > self.suit = suit > > def __str__(self): > rep = self.rank + self.suit > return rep > > >class Hand(object): > """ A hand of playing cards. """ > def __init__(self): > self.cards = [] > > def __str__(self): > if self.cards: > rep = "" > for card in self.cards: > rep += str(card) + " " > else: > rep = "" > return rep > > def clear(self): > self.cards = [] > > def add(self, card): > self.cards.append(card) > > def give(self, card, other_hand): > self.cards.remove(card) > other_hand.add(card) > > ># main >card1 = Card(rank = "A", suit = "c") >card2 = Card(rank = "2", suit = "c") >card3 = Card(rank = "3", suit = "c") >card4 = Card(rank = "4", suit = "c") >card5 = Card(rank = "5", suit = "c") > > >my_hand = Hand() >my_hand.add(card1) >my_hand.add(card2) >my_hand.add(card3) >my_hand.add(card4) >my_hand.add(card5) >print "\nPrinting my hand after adding 5 cards:" >print my_hand > >your_hand = Hand() >my_hand.give(card1, your_hand) >my_hand.give(card2, your_hand) >print "\nGave the first two cards from my hand to your >hand." >print "Your hand:" >print your_hand >print "My hand:" >print my_hand > >my_hand.clear() >print "\nMy hand after clearing it:" >print my_hand > >raw_input("\n\nPress the enter key to exit.") > > > > >__________________________________________________ >Do You Yahoo!? >Tired of spam? Yahoo! Mail has the best spam protection around >http://mail.yahoo.com >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From amonroe at columbus.rr.com Fri Sep 3 00:28:18 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Fri Sep 3 00:28:24 2004 Subject: [Tutor] names In-Reply-To: <000601c48ece$2e2f3770$121c8645@oemcomputer> References: <000601c48ece$2e2f3770$121c8645@oemcomputer> Message-ID: <116676944534.20040902182818@columbus.rr.com> > How do you get Python to let name=(anyone's name) > I saw some posts on this subject but didn't find an answer. Put quotation marks around the name. Alan From alan.gauld at blueyonder.co.uk Fri Sep 3 00:39:23 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Sep 3 00:39:11 2004 Subject: [Tutor] help with __str__ References: <20040902214556.63574.qmail@web50906.mail.yahoo.com> Message-ID: <012601c4913d$b2098f20$6401a8c0@xp> > slightly modified. It's concantenating rank and suit > each time you create a new card and it seems to be > doing it without having to use print card each > time. How is the str method being used without using > print? I'm really getting confused now. What makes you think its concatenating anything? The only time they get concatenated is when they get printed which is when the __str__ gets called. And it only concatenates for the duration of the print. What makes you think its doing anything else? > class Card(object): > """ A playing card. """ > def __init__(self, rank, suit): > self.rank = rank > self.suit = suit > > def __str__(self): > rep = self.rank + self.suit > return rep > Actually this is a pretty dumb class, a tuple would work just as well! > class Hand(object): > """ A hand of playing cards. """ > def __init__(self): > self.cards = [] > > def __str__(self): > if self.cards: > rep = "" > for card in self.cards: > rep += str(card) + " " Note that the call to str() here will also call the __str__ method of each card. But that only applies when printing a hand. The concatenation is still only temporary. > else: > rep = "" > return rep > print my_hand So within this call the individual card __str__() methods get called. HTH, Alan G. From fathimajaveed at hotmail.com Fri Sep 3 04:20:04 2004 From: fathimajaveed at hotmail.com (Fathima Javeed) Date: Fri Sep 3 04:20:10 2004 Subject: [Tutor] drawing a graph Message-ID: Hi, I have managed to get distances between sequnces at each P value, using randomization, so now i have a html output file where there are two set of values one is different distance percentage and another P values from 1 to 100, How would i draw a graph in Python i.e. distance against P values for each sequence, Completely lost now, really would appreciate help, would it be helpful to paste my code here? Cheers Fuzzi >From: Kent Johnson >To: tutor@python.org >Subject: Re: [Tutor] need help with comparing list of sequences in >Python!! >Date: Tue, 31 Aug 2004 07:04:09 -0400 > >Fuzzi, > >Here is one way to do this: >- Use zip() to pair up elements from the two sequences > >>> s1='aaabbbbcccc' > >>> s2='aaaccccbcccccccccc' > >>> zip(s1, s2) >[('a', 'a'), ('a', 'a'), ('a', 'a'), ('b', 'c'), ('b', 'c'), ('b', 'c'), >('b', 'c'), ('c', 'b'), ('c', 'c'), ('c', 'c'), ('c', 'c')] > >- Use a list comprehension to compare the elements of the pair and put the >results in a new list. I'm not sure if you want to count the matches or the >mismatches - your original post says mismatches, but in your example you >count matches. This example counts matches but it is easy to change. > >>> [a == b for a, b in zip(s1, s2)] >[True, True, True, False, False, False, False, False, True, True, True] > >- In Python, True has a value of 1 and False has a value of 0, so adding up >the elements of this list gives the number of matches: > >>> sum([a == b for a, b in zip(s1, s2)]) >6 > >- min() and len() give you the length of the shortest sequence: > >>> min(len(s1), len(s2)) >11 > >- When you divide, you have to convert one of the numbers to a float or >Python will use integer division! > >>> 6/11 >0 > >>> float(6)/11 >0.54545454545454541 > >Put this together with the framework that Alan gave you to create a program >that calculates distances. Then you can start on the randomization part. > >Kent > > >At 04:03 AM 8/31/2004 +0100, Fathima Javeed wrote: >>Hi Kent >> >>To awnser your question: >>well here is how it works >>sequence one = aaabbbbcccc >>length = 11 >> >>seq 2 = aaaccccbcccccccccc >>length = 18 >> >>to get the pairwise similarity of this score the program compares the >>letters >>of the two sequences upto length = 11, the length of the shorter sequence. >> >>so a match gets a score of 1, therefore using + for match and x for >>mismatch >> >>aaabbbbcccc >>aaaccccbcccccccccc >>+++xxxxx+++ >> >>there fore the score = 6/11 = 0.5454 or 54% >> >>so you only score the first 11 letters of each score and its is not >>required to compare the rest of the sequence 2. this is what the >>distance matrix is doing >> >>match score == 6 >> >>The spaces are deleted to make both of them the same length >> >> >>>From: Kent Johnson >>>To: "Fathima Javeed" , tutor@python.org >>>Subject: Re: [Tutor] need help with comparing list of sequences in >>>Python!! >>>Date: Mon, 30 Aug 2004 13:53:19 -0400 >>> >>>Fuzzi, >>> >>>How do you count mismatches if the lengths of the sequences are >>>different? Do you start from the front of both sequences or do you look >>>for a best match? Do you count the extra characters in the longer string >>>as mismatches or do you ignore them? An example or two would help. >>> >>>For example if >>>s1=ABCD >>>s2=XABDDYY >>>how many characters do you count as different? >>> >>>Kent >>> >>>At 07:00 PM 8/29/2004 +0100, Fathima Javeed wrote: >>>>Hi, >>>>would really appreciate it if someone could help me in Python as i am >>>>new to the language. >>>> >>>>Well i have a list of protein sequences in a text file, e.g. (dummy >>>>data) >>>> >>>>MVEIGEKAPEIELVDTDLKKVKIPSDFKGKVVVLAFYPAAFTSVCTKEMCTFRDSMAKFNEVNAVVIGISVDP >>>>PFS >>>> >>>>MAPITVGDVVPDGTISFFDENDQLQTVSVHSIAAGKKVILFGVPGAFTPTCSMSHVPGFIGKAEELKSKG >>>> >>>>APIKVGDAIPAVEVFEGEPGNKVNLAELFKGKKGVLFGVPGAFTPGCSKTHLPGFVEQAEALKAKGVQVVACL >>>>SVND >>>> >>>>HGFRFKLVSDEKGEIGMKYGVVRGEGSNLAAERVTFIIDREGNIRAILRNI >>>> >>>>etc etc >>>> >>>>They are not always of the same length, >>>> >>>>The first sequence is always the reference sequence which i am tring to >>>>investigate, basically to reach the objective, i need to compare each >>>>sequence with the first one, starting with the the comparison of the >>>>reference sequence by itself. >>>> >>>>The objective of the program, is to manupulate each sequence i.e. >>>>randomly change characters and calculate the distance (Distance: Number >>>>of letters between a pair of sequnces that dont match DIVIDED by the >>>>length of the shortest sequence) between the sequence in question >>>>against the reference sequence. So therefore need a program code where >>>>it takes the first sequence as a reference sequence (constant which is >>>>on top of the list), first it compares it with itself, then it compares >>>>with the second sequence, then with the third sequence etc etc each at >>>>a time, >>>> >>>>for the first comparison, you take a copy of the ref sequnce and >>>>manupulate the copied sequence) i.e. randomly changing the letters in >>>>the sequence, and calculating the distances between them. >>>>(the letters that are used for this are: A R N D C E Q G H I L K M F P S >>>>T W Y V) >>>> >>>>The reference sequence is never altered or manupulated, for the first >>>>comparison, its the copied version of the reference sequence thats >>>>altered. >>>> >>>>Randomization is done using different P values >>>>e.g for example (P = probability of change) >>>>if P = 0 no random change has been done >>>>if P = 1.0 all the letters in that particular sequence has been >>>>randomly changed, therefore p=1.0 equals to the length of the sequence >>>> >>>>So its calculating the distance each time between two sequences ( first >>>>is always the reference sequnce and another second sequence) at each P >>>>value ( starting from 0, then 0.1, 0.2, ....... 1.0). >>>> >>>>Note: Number of sequnces to be compared could be any number and of any >>>>length >>>> >>>>I dont know how to compare each sequence with the first sequnce and how >>>>to do randomization of the characters in the sequnce therefore to >>>>calculate the distance for each pair of sequnce , if someone can give me >>>>any guidance, I would be greatful >>>> >>>>Cheers >>>>Fuzzi >>>> >>>>_________________________________________________________________ >>>>Stay in touch with absent friends - get MSN Messenger >>>>http://www.msn.co.uk/messenger >>>> >>>>_______________________________________________ >>>>Tutor maillist - Tutor@python.org >>>>http://mail.python.org/mailman/listinfo/tutor >> >>_________________________________________________________________ >>It's fast, it's easy and it's free. Get MSN Messenger today! >>http://www.msn.co.uk/messenger > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ Express yourself with cool new emoticons http://www.msn.co.uk/specials/myemo From kent_johnson at skillsoft.com Fri Sep 3 04:31:57 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Sep 3 04:32:02 2004 Subject: [Tutor] Module for fixed decimal arithmetic - followup Message-ID: <6.1.0.6.0.20040902222954.02a0bae0@mail4.skillsoft.com> Recently someone requested a python module for fixed point arithmetic. It turns out that python 2.4 includes the decimal module which does just that. See PEP 327 for details: http://www.python.org/peps/pep-0327.html Kent From rha207 at yahoo.com Fri Sep 3 05:37:36 2004 From: rha207 at yahoo.com (Ron A) Date: Fri Sep 3 05:37:37 2004 Subject: [Tutor] help with __str__ Thanks Message-ID: <20040903033736.42655.qmail@web50904.mail.yahoo.com> I think I have it now. Thanks everybody. Ron A ---------------------------------- So that's why all of the functions in your program try not to just "print" their computation: rather, they actually try to "return" the value to the caller. Most people try to get their functions to 'return' values because such functions often end up being more useful than ones that only print to screen. If you have more questions, please feel free to ask. Good luck! __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From klas.martelleur at telia.com Fri Sep 3 07:55:19 2004 From: klas.martelleur at telia.com (Klas Marteleur) Date: Fri Sep 3 07:55:21 2004 Subject: [Tutor] My tutorial In-Reply-To: <010701c49137$b0dbcc40$6401a8c0@xp> References: <010701c49137$b0dbcc40$6401a8c0@xp> Message-ID: <200409030755.19141.klas.martelleur@telia.com> Thanks for a great piece of work! > After that I intend to add a > new section with topics on practical applications of Python > - the os module, XML and CGI programming, some sockets and > urllib etc. I am looking forward to the new section. Klas From dyoo at hkn.eecs.berkeley.edu Fri Sep 3 08:17:34 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Sep 3 08:17:37 2004 Subject: [Tutor] names (fwd) Message-ID: ---------- Forwarded message ---------- Date: Thu, 2 Sep 2004 20:12:25 -0400 From: Diana Furr To: Danny Yoo Subject: Re: [Tutor] names I would like to say thank you to Danny Yoo, Kent Johnson, and R. Alan Monroe for trying to answer my question. I spent 2 days trying to find the answer to that question and stumbled on the answer about 30mins after I gave up looking. name = raw_input('What is your name?') was the answer that I was looking for. I do have 1 more question though. I am trying to learn this but have no computer experience except being a user. Can anyone suggest book or something to help me out with the meaning of things like (), __str__ . Even the beginner stuff is way over my head at this point. Or is stuff something that you get used to in time? Again thank you for the help. ----- Original Message ----- From: "Danny Yoo" To: "Diana Furr" Cc: Sent: Thursday, September 02, 2004 2:22 PM Subject: Re: [Tutor] names > > > On Mon, 30 Aug 2004, Diana Furr wrote: > >> How do you get Python to let name=(anyone's name) >> >> I saw some posts on this subject but didn't find an answer. > > > Hi Diana, > > > Can you point us to one of those posts? I'm not quite sure what you mean > yet, and maybe the context will help. > > > Are you trying to do something like this? > > ### >>>> game = "frogger" >>>> game > 'frogger' > ### > > Here, we can assign the string value "frogger" to the variable name > 'game'. Is this what you're looking for? > From dyoo at hkn.eecs.berkeley.edu Fri Sep 3 08:47:54 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Sep 3 08:48:02 2004 Subject: [Tutor] drawing a graph In-Reply-To: Message-ID: On Fri, 3 Sep 2004, Fathima Javeed wrote: > I have managed to get distances between sequnces at each P value, using > randomization, so now i have a html output file where there are two set > of values one is different distance percentage and another P values from > 1 to 100, How would i draw a graph in Python i.e. distance against P > values for each sequence, Completely lost now, really would appreciate > help, would it be helpful to paste my code here? Hi Vuzzi, Can you give us a small example of what you'd like a graph to look like, for, say three small sequences? That may help us to point you toward the right graph-generating tools. There are graph tools from the 'graphviz' project: http://www.research.att.com/sw/tools/graphviz/ but I'm not sure if you mean this kind of graph. *grin* "Graph" is another one of those overloaded words. You might mean bar charts or line graphs instead. Perhaps you might be able to use HTMLGen to generate nice HTML bar charts: http://www.linuxjournal.com/article.php?sid=2986 But it sounds like you might want something more. There's a Python extension module the R statistics system, and since R has robust graphing, you can take advantage of it: http://rpy.sourceforge.net/ http://www.togaware.com/linux/survivor/Graphs.shtml Does this help? Good luck to you! From karthik at james.hut.fi Fri Sep 3 08:51:04 2004 From: karthik at james.hut.fi (Karthikesh Raju) Date: Fri Sep 3 08:51:13 2004 Subject: [Tutor] Help with regular expressions Message-ID: Hi All, i am trying to craft a regular expression to do the following: in a file say a.txt a.txt 1 2 3 4 5 6 7 8 9 10 11 23 34 54 56 *** ( 3 5 ) *** -------------------------------- Now i want to match the *** ( 3 5 ) *** line and load 3 in rows and 5 in columns. Where should i start? i tried import re p = re.compile('\( [0-9]+ [0-9]+ \)') a = '( 3 5 )' p.match(a) didnt move a cm .... warm regards karthik ----------------------------------------------------------------------- Karthikesh Raju, email: karthik@james.hut.fi karthikesh.raju@gmail.com Researcher, http://www.cis.hut.fi/karthik Helsinki University of Technology, Tel: +358-9-451 5389 Laboratory of Comp. & Info. Sc., Fax: +358-9-451 3277 Department of Computer Sc., P.O Box 5400, FIN 02015 HUT, Espoo, FINLAND ----------------------------------------------------------------------- From alan.gauld at blueyonder.co.uk Fri Sep 3 09:17:09 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Sep 3 09:16:51 2004 Subject: [Tutor] spitshell for python References: <20040902185934.GB93162@alexis.mi.celestial.com> <00f201c49136$83706820$6401a8c0@xp> <20040902230828.GA9754@alexis.mi.celestial.com> Message-ID: <013701c49186$06f2b0f0$6401a8c0@xp> > I don't think so. Typically there's a commonly accepted way to > provide code that is legal under the shell and the language that > will be ignored by python, but cause the shell to exec python > with appropriate arguments. As an example, this works as the > first lines in a perl script: That doesn't help me I'm afraid. You are going to have to explain what's happening in the perl code > #!/usr/local/bin/perl This bit I understand - it runs the perl interpreter :-) > eval ' exec /usr/local/bin/perl -S $0 ${1+"$@"}' And this evaluates a string as a perl instruction, or is it as a shell instruction? hmm probably the latter. But what is inside the string? It looks like we are running another copy of perl to execute whatever the $0... arguments are? What is the -S option? > if $running_under_some_shell; And I assume this is a conditional that determines whether the eval gets executed depending on the shell, ie Bourne, Bash, csh etc? So I'm guessing that what you want is a bit of Python code that will figure out which shell is running and execute a shell command in that dialect? And the bit of shell to execute, in turn, runs some python script? Am I right? If so that sounds like it brings me back to execfile... so presumably I'm missing some magic in the line noise at the end of the eval statement... Alan G. From karthik at james.hut.fi Fri Sep 3 09:42:06 2004 From: karthik at james.hut.fi (Karthikesh Raju) Date: Fri Sep 3 09:42:11 2004 Subject: [Tutor] Help With Regular expression? - Partial solution Message-ID: Hi All, i found a partial solution somthing like p = re.compile('\( [0-9]+ [0-9]+ \)') this will match (5 6), or any tuple with 2 indices, i want to put an optional part something like ('\( [0-9]+ ([0-9]?+) \)') so that i can match any thing of the form ( 5 ) ( 5 6 ) (5 6 7) and so on .. How should one craft it .. warm regards karthik ----------------------------------------------------------------------- Karthikesh Raju, email: karthik@james.hut.fi karthikesh.raju@gmail.com Researcher, http://www.cis.hut.fi/karthik Helsinki University of Technology, Tel: +358-9-451 5389 Laboratory of Comp. & Info. Sc., Fax: +358-9-451 3277 Department of Computer Sc., P.O Box 5400, FIN 02015 HUT, Espoo, FINLAND ----------------------------------------------------------------------- From alan.gauld at blueyonder.co.uk Fri Sep 3 09:45:05 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Sep 3 09:44:47 2004 Subject: [Tutor] names (fwd) References: Message-ID: <015c01c49189$ed77e060$6401a8c0@xp> > was looking for. I do have 1 more question though. I am trying to learn this > but have no computer experience except being a user. Can anyone suggest > book or something to help me out with the meaning of things like (), __str__ OK, () is pretty fundamental, and most beginners tutorials should explain the use of parens. But __str__ is pretty advanced and not something you need to worry about for a long time yet. In fact I think that in 7 years of Python use I've only directly used __str__ once! While there are several tutorials for absolute beginners I am obviously most interested in the shortcomings of mine! So if you want to try using it let me know when you come across anything you don't think I have explained. I'll then add it and so the tutor gets better for everyone... :-) > . Even the beginner stuff is way over my head at this point. Or is stuff > something that you get used to in time? Again thank you for the help. You can get used to it but there's no reason you can't have it explained too. I certainly try to explain those kinds of basic concepts. As I say there are several other tutorials around but you do have the advantage that I read the tutor list! :-) Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From Janssen at rz.uni-frankfurt.de Fri Sep 3 11:14:11 2004 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Fri Sep 3 11:14:17 2004 Subject: [Tutor] Help with regular expressions In-Reply-To: References: Message-ID: On Fri, 3 Sep 2004, Karthikesh Raju wrote: > p.match(a) > > didnt move a cm .... With match you will only find text starting at the beginning of "a". Try p.search to get matches from within "a". regards Michael From kent_johnson at skillsoft.com Fri Sep 3 11:54:10 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Sep 3 11:54:17 2004 Subject: [Tutor] names (fwd) In-Reply-To: References: Message-ID: <6.1.0.6.0.20040903055235.02986310@mail4.skillsoft.com> You can read my recommendations here: http://personalpages.tds.net/~kent37/Python/PythonResources.html Kent At 11:17 PM 9/2/2004 -0700, Danny Yoo wrote: >---------- Forwarded message ---------- >Date: Thu, 2 Sep 2004 20:12:25 -0400 >From: Diana Furr >To: Danny Yoo >Subject: Re: [Tutor] names > >I would like to say thank you to Danny Yoo, Kent Johnson, and R. Alan >Monroe for trying to answer my question. I spent 2 days trying to find the >answer to that question and stumbled on the answer about 30mins after I gave >up looking. name = raw_input('What is your name?') was the answer that I >was looking for. I do have 1 more question though. I am trying to learn this >but have no computer experience except being a user. Can anyone suggest >book or something to help me out with the meaning of things like (), __str__ >. Even the beginner stuff is way over my head at this point. Or is stuff >something that you get used to in time? Again thank you for the help. From kent_johnson at skillsoft.com Fri Sep 3 11:59:46 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Sep 3 11:59:56 2004 Subject: [Tutor] Re: drawing a graph In-Reply-To: References: Message-ID: <6.1.0.6.0.20040903055522.02933650@mail4.skillsoft.com> Fuzzi, I recently found the graphing module from VPython very easy to use to create a simple graph. Here is what I did: http://mail.python.org/pipermail/tutor/2004-August/031568.html http://vpython.org/ If you want more help with your existing program then posting the code to the list is a good idea, we can look at it and make suggestions or help you take the next step. Kent At 03:20 AM 9/3/2004 +0100, Fathima Javeed wrote: >Hi, > >I have managed to get distances between sequnces at each P value, using >randomization, so now i have a html output file where there are two set of >values one is different distance percentage and another P values from 1 to >100, How would i draw a graph in Python i.e. distance against P values for >each sequence, Completely lost now, really would appreciate help, would it >be helpful to paste my code here? > >Cheers >Fuzzi > >>From: Kent Johnson >>To: tutor@python.org >>Subject: Re: [Tutor] need help with comparing list of sequences in >>Python!! >>Date: Tue, 31 Aug 2004 07:04:09 -0400 >> >>Fuzzi, >> >>Here is one way to do this: >>- Use zip() to pair up elements from the two sequences >> >>> s1='aaabbbbcccc' >> >>> s2='aaaccccbcccccccccc' >> >>> zip(s1, s2) >>[('a', 'a'), ('a', 'a'), ('a', 'a'), ('b', 'c'), ('b', 'c'), ('b', 'c'), >>('b', 'c'), ('c', 'b'), ('c', 'c'), ('c', 'c'), ('c', 'c')] >> >>- Use a list comprehension to compare the elements of the pair and put >>the results in a new list. I'm not sure if you want to count the matches >>or the mismatches - your original post says mismatches, but in your >>example you count matches. This example counts matches but it is easy to >>change. >> >>> [a == b for a, b in zip(s1, s2)] >>[True, True, True, False, False, False, False, False, True, True, True] >> >>- In Python, True has a value of 1 and False has a value of 0, so adding >>up the elements of this list gives the number of matches: >> >>> sum([a == b for a, b in zip(s1, s2)]) >>6 >> >>- min() and len() give you the length of the shortest sequence: >> >>> min(len(s1), len(s2)) >>11 >> >>- When you divide, you have to convert one of the numbers to a float or >>Python will use integer division! >> >>> 6/11 >>0 >> >>> float(6)/11 >>0.54545454545454541 >> >>Put this together with the framework that Alan gave you to create a >>program that calculates distances. Then you can start on the >>randomization part. >> >>Kent >> >> >>At 04:03 AM 8/31/2004 +0100, Fathima Javeed wrote: >>>Hi Kent >>> >>>To awnser your question: >>>well here is how it works >>>sequence one = aaabbbbcccc >>>length = 11 >>> >>>seq 2 = aaaccccbcccccccccc >>>length = 18 >>> >>>to get the pairwise similarity of this score the program compares the >>>letters >>>of the two sequences upto length = 11, the length of the shorter sequence. >>> >>>so a match gets a score of 1, therefore using + for match and x for mismatch >>> >>>aaabbbbcccc >>>aaaccccbcccccccccc >>>+++xxxxx+++ >>> >>>there fore the score = 6/11 = 0.5454 or 54% >>> >>>so you only score the first 11 letters of each score and its is not >>>required to compare the rest of the sequence 2. this is what the >>>distance matrix is doing >>> >>>match score == 6 >>> >>>The spaces are deleted to make both of them the same length >>> >>> >>>>From: Kent Johnson >>>>To: "Fathima Javeed" , tutor@python.org >>>>Subject: Re: [Tutor] need help with comparing list of sequences in >>>>Python!! >>>>Date: Mon, 30 Aug 2004 13:53:19 -0400 >>>> >>>>Fuzzi, >>>> >>>>How do you count mismatches if the lengths of the sequences are >>>>different? Do you start from the front of both sequences or do you look >>>>for a best match? Do you count the extra characters in the longer >>>>string as mismatches or do you ignore them? An example or two would help. >>>> >>>>For example if >>>>s1=ABCD >>>>s2=XABDDYY >>>>how many characters do you count as different? >>>> >>>>Kent >>>> >>>>At 07:00 PM 8/29/2004 +0100, Fathima Javeed wrote: >>>>>Hi, >>>>>would really appreciate it if someone could help me in Python as i am >>>>>new to the language. >>>>> >>>>>Well i have a list of protein sequences in a text file, e.g. (dummy data) >>>>> >>>>>MVEIGEKAPEIELVDTDLKKVKIPSDFKGKVVVLAFYPAAFTSVCTKEMCTFRDSMAKFNEVNAVVIGISVDP >>>>>PFS >>>>> >>>>>MAPITVGDVVPDGTISFFDENDQLQTVSVHSIAAGKKVILFGVPGAFTPTCSMSHVPGFIGKAEELKSKG >>>>> >>>>>APIKVGDAIPAVEVFEGEPGNKVNLAELFKGKKGVLFGVPGAFTPGCSKTHLPGFVEQAEALKAKGVQVVACL >>>>>SVND >>>>> >>>>>HGFRFKLVSDEKGEIGMKYGVVRGEGSNLAAERVTFIIDREGNIRAILRNI >>>>> >>>>>etc etc >>>>> >>>>>They are not always of the same length, >>>>> >>>>>The first sequence is always the reference sequence which i am tring >>>>>to investigate, basically to reach the objective, i need to compare >>>>>each sequence with the first one, starting with the the comparison of >>>>>the reference sequence by itself. >>>>> >>>>>The objective of the program, is to manupulate each sequence i.e. >>>>>randomly change characters and calculate the distance (Distance: >>>>>Number of letters between a pair of sequnces that dont match DIVIDED >>>>>by the length of the shortest sequence) between the sequence in >>>>>question against the reference sequence. So therefore need a program >>>>>code where it takes the first sequence as a reference sequence >>>>>(constant which is on top of the list), first it compares it with >>>>>itself, then it compares with the second sequence, then with the third >>>>>sequence etc etc each at a time, >>>>> >>>>>for the first comparison, you take a copy of the ref sequnce and >>>>>manupulate the copied sequence) i.e. randomly changing the letters in >>>>>the sequence, and calculating the distances between them. >>>>>(the letters that are used for this are: A R N D C E Q G H I L K M F P >>>>>S T W Y V) >>>>> >>>>>The reference sequence is never altered or manupulated, for the first >>>>>comparison, its the copied version of the reference sequence thats altered. >>>>> >>>>>Randomization is done using different P values >>>>>e.g for example (P = probability of change) >>>>>if P = 0 no random change has been done >>>>>if P = 1.0 all the letters in that particular sequence has been >>>>>randomly changed, therefore p=1.0 equals to the length of the sequence >>>>> >>>>>So its calculating the distance each time between two sequences ( >>>>>first is always the reference sequnce and another second sequence) at >>>>>each P value ( starting from 0, then 0.1, 0.2, ....... 1.0). >>>>> >>>>>Note: Number of sequnces to be compared could be any number and of any >>>>>length >>>>> >>>>>I dont know how to compare each sequence with the first sequnce and >>>>>how to do randomization of the characters in the sequnce therefore to >>>>>calculate the distance for each pair of sequnce , if someone can give >>>>>me any guidance, I would be greatful >>>>> >>>>>Cheers >>>>>Fuzzi >>>>> >>>>>_________________________________________________________________ >>>>>Stay in touch with absent friends - get MSN Messenger >>>>>http://www.msn.co.uk/messenger >>>>> >>>>>_______________________________________________ >>>>>Tutor maillist - Tutor@python.org >>>>>http://mail.python.org/mailman/listinfo/tutor >>> >>>_________________________________________________________________ >>>It's fast, it's easy and it's free. Get MSN Messenger today! >>>http://www.msn.co.uk/messenger >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor > >_________________________________________________________________ >Express yourself with cool new emoticons http://www.msn.co.uk/specials/myemo > From project5 at redrival.net Fri Sep 3 13:07:51 2004 From: project5 at redrival.net (Andrei) Date: Fri Sep 3 13:08:02 2004 Subject: [Tutor] Re: converting string to a number References: <6.1.0.6.0.20040902054756.029b1878@mail4.skillsoft.com> <4136FEDB.20400@noos.fr> <6.1.0.6.0.20040902105117.029f2ce0@mail4.skillsoft.com> <413743D4.6050605@noos.fr> Message-ID: nik noos.fr> writes: > Thanks for the advice guys, I hadn't thought of what would happen if it > wasn't the exception you were expecting. It still feels uncomfortable > though, I've always felt an exception is *exceptional*, ie something > that was outside your control. The name is misleading :). You do need to be careful with them though, because they have the potential of hiding problems and/or making them difficult to solve when you use them *too* liberally (particularly generic try-excepts over large pieces of code). Yours, Andrei From kent_johnson at skillsoft.com Fri Sep 3 14:12:09 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Sep 3 14:12:12 2004 Subject: [Tutor] Help With Regular expression? - Partial solution In-Reply-To: References: Message-ID: <6.1.0.6.0.20040903080337.0288c6b8@mail4.skillsoft.com> If I understand you correctly, you want to match an open parenthesis followed by one or more digits, optionally followed by any number of (one or more whitespace followed by one or more digits) followed by a closing parenthesis This regex will do just that: \(\d+(\s+\d+)*\) Taking a closer look: \( - open paren \d+ - one or more digits (\s+\d+)* - one or more whitespace followed by one or more digits, repeated zero or more times \) - closing parenthesis This regex will recognize the line of interest, it won't help you extract the numbers. For that you could use re.findall, or maybe split() is enough. BTW Python includes a handy regex tester, it is in Python/Tools/Scripts/redemo.py Kent At 10:42 AM 9/3/2004 +0300, Karthikesh Raju wrote: >Hi All, > >i found a partial solution somthing like > >p = re.compile('\( [0-9]+ [0-9]+ \)') > >this will match (5 6), or any tuple with 2 indices, i want to put an >optional part something like > >('\( [0-9]+ ([0-9]?+) \)') >so that i can match any thing of the form >( 5 ) ( 5 6 ) (5 6 7) and so on .. > >How should one craft it .. > >warm regards > >karthik >----------------------------------------------------------------------- >Karthikesh Raju, email: karthik@james.hut.fi > karthikesh.raju@gmail.com >Researcher, http://www.cis.hut.fi/karthik >Helsinki University of Technology, Tel: +358-9-451 5389 >Laboratory of Comp. & Info. Sc., Fax: +358-9-451 3277 >Department of Computer Sc., >P.O Box 5400, FIN 02015 HUT, >Espoo, FINLAND >----------------------------------------------------------------------- >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From s.venter at ntlworld.com Fri Sep 3 17:53:16 2004 From: s.venter at ntlworld.com (Gerhard Venter) Date: Fri Sep 3 17:53:29 2004 Subject: [Tutor] CGI-version not working while similar command-line script is fine Message-ID: <4138936C.8060308@ntlworld.com> Hi all I'm trying to convert the following little code (which works fine if you have lynx installed) into CGI: #! /usr/bin/env python import os websitename = raw_input('enter a website: ') command = 'lynx --dump ' + websitename k=os.popen(command, 'r') for line in k.readlines(): print(line) ------------------------------------------------ My CGI version produces no errors, only a blank page. I have other Python CGI scripts, so it is not about web server config. I have also tested my HTML form, and was able to print the value of websitename to HTML, so I know the form passes the data to the script. import cgi, os import cgitb; cgitb.enable() <>form = cgi.FieldStorage() website = form["websitename"].value command = 'lynx --dump ' + websitename k=os.popen(command, 'r') <>print 'Content-type: text/plain' print for line in k.readlines(): print(line) ------------------------- I suspect there is a hint in the fact that I had to use raw_input instead of just input for the cmd-line version (just input causes a NameError). Maybe the CGI-module has its own version of this effect Any pointers welcome. Gerhard From kent_johnson at skillsoft.com Fri Sep 3 18:17:52 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Sep 3 18:17:57 2004 Subject: [Tutor] CGI-version not working while similar command-line script is fine In-Reply-To: <4138936C.8060308@ntlworld.com> References: <4138936C.8060308@ntlworld.com> Message-ID: <6.1.0.6.0.20040903121324.029ffa58@mail4.skillsoft.com> At 04:53 PM 9/3/2004 +0100, Gerhard Venter wrote: >I suspect there is a hint in the fact that I had to use raw_input instead >of just input for the cmd-line version (just input causes a >NameError). Maybe the CGI-module has its own version of this effect I don't know what is wrong with your CGI but this isn't it. When you just want to input a string, raw_input() is the correct method. input() _evaluates_ what you type, just as if you had typed it to the interpreter, and returns the result. That's why you get a NameError For example, using input() what I type is evaluated: >>> while 1: ... print input("What? ") ... What? 1 1 What? 1+2 3 What? str What? foo Traceback (most recent call last): File "", line 2, in ? File "", line 0, in ? NameError: name 'foo' is not defined The same thing with raw_input() just echoes back exactly what I type: >>> while 1: ... print raw_input('What? ') ... What? 1 1 What? 1+2 1+2 What? str str What? foo foo Kent From dyoo at hkn.eecs.berkeley.edu Fri Sep 3 19:38:22 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Sep 3 19:38:43 2004 Subject: [Tutor] beginner help!!!! (fwd) Message-ID: Hi Jill, Let me forward your response to Tutor too: please use "Reply-to-All" in your email client, so that your responses reach the Tutor list. We want to make sure you can get help from the whole group, and not just one person. Anyway, ok, let's take a look. Hmmm... from your printout below, I see that you can get the 'print' statements working ok, so that's good. When you saved your program, how did you save it? What does your saved file look like? Have you seen this page yet? http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/ The tutorial from that link should show how to save and run a program --- it also covers a few pitfalls that you might be running into. I have a vague feeling that you might be saving the "transcript" --- that is, the conversation you're having with the interpreter, but and not just program statements. Can you try the tutorial above and see if you can get that sample exercise working? Good luck to you. ---------- Forwarded message ---------- Date: Thu, 2 Sep 2004 21:02:11 -0400 From: Jill and Paul To: Danny Yoo Subject: Re: [Tutor] beginner help!!!! Thanks Danny! I feel so out of it! Here is the sample exercise I typed: Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. **************************************************************** Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. **************************************************************** IDLE 1.0 >>> print "Jack and Jill went up a hill" Jack and Jill went up a hill >>> print "to fetch a pail of water;" to fetch a pail of water; >>> print "Jack fell down, and broke his crown," Jack fell down, and broke his crown, >>> print "and Jill came tumbling after." and Jill came tumbling after. >>> After I save it and try to run it here comes the error. It says: Syntax error There's an error in your program: invalid syntax It has an OK button. Ugh! It does that every time I type an exercise. I can't run any of them! I have no idea what happened to the indentation error I asked about previously. How frustrating! Jill ----- Original Message ----- From: "Danny Yoo" To: "'Jill and Paul'" Cc: "Tutor" Sent: Thursday, September 02, 2004 2:17 PM Subject: RE: [Tutor] beginner help!!!! > > > On Thu, 2 Sep 2004, Kooser, Ara S wrote: > > > Could you post the code and the error message. Thanks > > > Hi Jill, > > > Yes, we need to see your code. I suspect it might be an indentation > problem, but without seeing your code, I can't make any solid remarks > either. Feel free to just copy and paste it in your reply. > > > About the error message stuff: don't parapharse the error: show it to us > as it comes. For example, here's the kind of error message we like to > see: > > > ### > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'oracle' is not defined > ### > > > In contrast, if we paraphrase the error message to just: > > "There's a Name Error somewhere in my program", > > then that's not as helpful to us. The real error message itself has told > us what appears to be undefined, and on what line the problems appear to > start. The paraphrase, on the other hand, just tells us that something's > wrong, but doesn't tell us where to look. > > In this case, originality is not a good thing: it's good not to suppress > that information in paraphrase. Instead, just copy-and-paste the error, > around where the "Traceback" starts. > > > Good luck! > > From dactex at swbell.net Fri Sep 3 19:49:46 2004 From: dactex at swbell.net (David Carter) Date: Fri Sep 3 19:51:36 2004 Subject: [Tutor] FW: HTMLgen question Message-ID: <000101c491de$68a55750$2800005a@gobot> Hello All; I decided to try out the HTMLgen module today. First of all, let me preface by saying that my HTMLgen install is kludged together, since I have no "make" for Windows, and I had to sort of build it manually by reading the Readme and trying to grok the makefile.txt as best I could. I'm running Python 2.3.2 under Win2K Server with IIS as an ASP-type page. So I just tried the simplest thing I could think of: *******BEGIN CODE***************** <%@ LANGUAGE=PYTHON %> <% import HTMLgen a = HTMLgen.BasicDocument() Response.Write(a) %> *******END CODE******************* Browsing to the page returns: *******BEGIN RESPONSE***************** Python ActiveX Scripting Engine error '80020009' Traceback (most recent call last): File "