" (For those interested, urlMask = r"http://[\w\Q./\?=\R]+" is ther version w/o the optional
ending.) I can't seem to make a string optional- only a single character via []s. I for some reason thuoght it'll be ()s, but no help there- it just returns only the
. Anybody? Thx, Omer. -------------- next part -------------- An HTML attachment was scrubbed... URL: From airchia at gmail.com Sun Jan 4 19:25:33 2009 From: airchia at gmail.com (Nick Scholtes) Date: Sun, 4 Jan 2009 12:25:33 -0600 Subject: [Tutor] Python - Data Mining? Message-ID: Hi, I'm still very, very new to Python and programming. I was wondering if anyone can point me in the right direction. As I gradually learn Python, one of the things I want to be able to do is take a database, run queries and extract information and then graph that information visually to see patterns in the data. Where should I start? Does Python do this? If not, what language is used for this? Thank you very much, Nick -- Art: http://www.coroflot.com/bellsoffreedom -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sun Jan 4 19:54:36 2009 From: bgailer at gmail.com (bob gailer) Date: Sun, 04 Jan 2009 13:54:36 -0500 Subject: [Tutor] Add all natural numbers that are multiples of 3 and 5 In-Reply-To: References: <496028B9.2040505@gmail.com> Message-ID: <496105EC.4080604@gmail.com> Alan Gauld wrote: > "bob gailer" wrote > >> Also consider that the sum of consecutive integers between 1 and n is >> n*(n+1)/2. >> Calculate that for 1..333 then multiply by 3 >> Calculate that for 1..199 then multiply by 5 >> add those >> Calculate that for 1..66 then multiply by 15 >> subtract that from the total > > Ooh, that's sneaky! I haven't seen that before. Guess you did not study number theory. Standard algorithm. Google sum of consecutive integers. Regarding Project Euler - I believe one of the objectives is to find solutions that are not just brute force. Some of the problems can be solved by brute force but will take too much computer time. Sphere Online Judge www.spoj.pl is even more rigorous in that it runs your program and if run time is too long the solution is considered not correct. -- Bob Gailer Chapel Hill NC 919-636-4239 From sierra_mtnview at sbcglobal.net Sun Jan 4 19:49:23 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 04 Jan 2009 10:49:23 -0800 Subject: [Tutor] WinMerge -- I'm Impressed Message-ID: <496104B3.1080108@sbcglobal.net> An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sun Jan 4 20:09:53 2009 From: bgailer at gmail.com (bob gailer) Date: Sun, 04 Jan 2009 14:09:53 -0500 Subject: [Tutor] RE Silliness In-Reply-To: <515008f10901041007s1670d6b0v5ac53978ce0a0e1c@mail.gmail.com> References: <515008f10901041007s1670d6b0v5ac53978ce0a0e1c@mail.gmail.com> Message-ID: <49610981.5070708@gmail.com> Omer wrote: > I'm sorry, burrowed into the reference until my eyes bled. > > What I want is to have a regular expression with an optional ending of > "
" > > (For those interested, > urlMask = r"http://[\w\Q./\?=\R]+" > is ther version w/o the optional
ending.) > > I can't seem to make a string optional- only a single character via > []s. I for some reason thuoght it'll be ()s, but no help there- it > just returns only the
. Anybody? > urlMask = r"http://[\w\Q./\?=\R]+(
" > > > > (For those interested, > > urlMask = r"http://[\w\Q./\?=\R]+" > > is ther version w/o the optional
ending.) > > > > I can't seem to make a string optional- only a single character via > > []s. I for some reason thuoght it'll be ()s, but no help there- it > > just returns only the
. Anybody? > > > urlMask = r"http://[\w\Q./\?=\R]+(
)?" >>> text=u"Not working example
And another line
', u''] spir, I did understand it. What I'm not understanding is why isn't this working. (Whereas, >>> OldurlMask = r"http://[\w\Q./\?=\R]+" #Not f-ing working. >>> re.findall(OldurlMask,text) ['http://this.is.a/url?header=null', 'http://and.another.url'] does work. Which is what had me frowning. Also, this ugly url mask is working: >>> UglyUrlMask = r"(http://[\w\Q./\?=\R]+
', 'http://and.another.url'] Anyone?) On Mon, Jan 5, 2009 at 12:08 AM, spir wrote: > On Sun, 04 Jan 2009 14:09:53 -0500 > bob gailer wrote: > > > Omer wrote: > > > I'm sorry, burrowed into the reference until my eyes bled. > > > > > > What I want is to have a regular expression with an optional ending of > > > "
" > > > > > > (For those interested, > > > urlMask = r"http://[\w\Q./\?=\R]+" > > > is ther version w/o the optional
ending.) > > > > > > I can't seem to make a string optional- only a single character via > > > []s. I for some reason thuoght it'll be ()s, but no help there- it > > > just returns only the
. Anybody? > > > > > urlMask = r"http://[\w\Q./\?=\R]+(
)?" > > > > From the docs: ? Causes the resulting RE to match 0 or 1 repetitions of > > the preceding RE. ab? will match either 'a' or 'ab'. > > > > > > Maybe Omer had not noted that a sub-expression can be grouped in () so that > an operator (?+*) applies on the whole group. > Denis > > ------ > la vida e estranya > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Mon Jan 5 17:45:56 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 5 Jan 2009 11:45:56 -0500 Subject: [Tutor] RE Silliness In-Reply-To: <515008f10901050816k385ebc52i9d688e580fbadc29@mail.gmail.com> References: <515008f10901041007s1670d6b0v5ac53978ce0a0e1c@mail.gmail.com> <49610981.5070708@gmail.com> <20090104230807.1b128435@o> <515008f10901050816k385ebc52i9d688e580fbadc29@mail.gmail.com> Message-ID: <1c2a2c590901050845l605e3639m64debd3ec9c788a5@mail.gmail.com> On Mon, Jan 5, 2009 at 11:16 AM, Omer wrote: > Bob, I tried your way. > >>>> import re >>>> urlMask = r"http://[\w\Q./\?=\R]+(
)?" >>>> text=u"Not working example
And >>>> another line
', u''] > > spir, I did understand it. What I'm not understanding is why isn't this > working. There is a bit of a gotcha in re.findall() - its behaviour changes depending on whether there are groups in the re. If the re contains groups, re.findall() only returns the matches for the groups. If you enclose the entire re in parentheses (making it a group) you get a better result: In [2]: urlMask = r"(http://[\w\Q./\?=\R]+(
)?)" In [3]: text=u"Not working example
And another line
) -- Bob Gailer Chapel Hill NC 919-636-4239 From alan.gauld at btinternet.com Mon Jan 5 19:25:18 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 5 Jan 2009 18:25:18 -0000 Subject: [Tutor] extreme basics References: <881ed86af5.86af5881ed@uq.edu.au> Message-ID: "Mr Gerard Kelly" wrote > This is extremely weird, I think. No, its normal and you got the right reason.... its due to floating point binary representation issues. > Here is a tiny program: > > from math import * > from Numeric import * This is probably a bad idea here (in fact its usually a bad idea!) since both math and numeric are likely to have similar names in them By importing all names from the modules there is a high chance of name clashes causing strange behaviour. Better to use import math, Numeric Or, if that's too much typing, use import math as M import Numeric as N > x=[0]*10 > > > for counter in rangelen((x)): > x[counter]=counter*0.1 > > print x Although of course you are not using anything from either math or Numeric in this example, but I assume you intend to!? HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk From alan.gauld at btinternet.com Mon Jan 5 19:33:46 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 5 Jan 2009 18:33:46 -0000 Subject: [Tutor] Wayne's waning list. References: <4962119E.3070004@socal.rr.com> Message-ID: "WM." wrote > As a BASIC, hobby programmer, (long since), I get so jargonized here > that I seldom ask about anything any more. Have you tried my tutorial, it compares VBScript (somewhat like BASIC) with Python. It might help. > gleaned from reading many, many posts is the URL for projecteuler. > Maybe, after I get past the baby steps and start using the > libraries, I will benefit more. Now, the opaque questions and > bewildering responses leave me in a very passive state. As somebody else said we cover everything from newbies to programming through to experts ion other languages whjo are new to Python and even some experts(ish) in Python who are new to a specific area(like GUI or web programming) As a result the questions range from the trivial to the esoteric. If you think you should know whats being discussed don't be afraid to jump in and ask for clarification in plain English. Either in the same thread or if its looking like a biggie as a separate thread. We aim to help and a background in BASIC should help not hinder! :-) -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From jervisau at gmail.com Mon Jan 5 20:58:45 2009 From: jervisau at gmail.com (Jervis Whitley) Date: Tue, 6 Jan 2009 06:58:45 +1100 Subject: [Tutor] Question regarding win32com getting ldap object In-Reply-To: <5487b3060901050104g3d10c577s1ee0bc8303712ae4@mail.gmail.com> References: <5487b3060901050104g3d10c577s1ee0bc8303712ae4@mail.gmail.com> Message-ID: <8e63a5ce0901051158i32b2af2al24cb89db54182c0e@mail.gmail.com> On Mon, Jan 5, 2009 at 8:04 PM, vishwajeet singh wrote: > Hi List, > > I am running following code to get ldap com object but the result I am > getting is unknown > I am using Python 25 and win32 bindings available at > http://downloads.sourceforge.net/pywin32/pywin32-212.win32-py2.2.exe?modtime=1217535908&big_mirror=0 > > *adsi = win32com.client.Dispatch('ADsNameSpaces') > print adsi > ldap = adsi.getobject('', 'LDAP:') > print ldap* > > OutPut: > > > > > Any ideas what I am doing wrong ? > > -- > Cheers, > Vishwajeet > http://www.singhvishwajeet.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > Hi, try the following from the archive: http://mail.python.org/pipermail/python-list/1999-December/018594.html Cheers, Jervis -------------- next part -------------- An HTML attachment was scrubbed... URL: From jadrifter at gmail.com Tue Jan 6 00:07:07 2009 From: jadrifter at gmail.com (jadrifter) Date: Mon, 05 Jan 2009 15:07:07 -0800 Subject: [Tutor] Usage of for loop In-Reply-To: <4499cb6a0901050519p1c0feb32odd987b5fea718ecf@mail.gmail.com> References: <4499cb6a0901050519p1c0feb32odd987b5fea718ecf@mail.gmail.com> Message-ID: <1231196827.6180.15.camel@ltop> On Mon, 2009-01-05 at 18:49 +0530, vanam wrote: > Hi all, > i am beginner to this python language and slowing learning the > language by referring docs.I am trying to understand the for loop > i.e., usage of for loop in python,unlike c where i can give condition > in python it is simple iterating over sequence. > > I am trying tounderstand the below lines of code but of no avail. > > a = ["cat", "window","defenestrate"] > for x in a: > print x, len(x) > i cant understand what x is doing here and what is the purpose of it > can anyone help me out here? > > -- > Raghavendra Vanam > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor x is a new variable and when used this way it holds one of the members of "a" for each trip through the loop. After your for loop is done there will be two new names in a "dir()" listing if you're using the interactive python shell. There will be a name "a" and a name "x". If you type "print x" it will output "defenestrate" because it still holds the last value of a from the for loop. John Purser From sander.sweers at gmail.com Tue Jan 6 01:52:32 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Tue, 6 Jan 2009 01:52:32 +0100 Subject: [Tutor] Convert values in a list back and forth from ints and time Message-ID: Hello Tutors, I use the csv module to read and write a csv file. When I read the file into a new list I convert the ints and the dates to int and time objects so I can do calculations. I use the below function which works. def convertValue(value, dateformat, reverse=False): if reverse: try: return strftime(dateformat, value) except TypeError: return str(value) else: try: return int(float(value)) except ValueError: try: return strptime(value, dateformat) except: return value When writing the lines back to a csv file I loop over the lists and convert the values back with the same function but in reverse but.... I was just wondering if there is another way of dealing with this. Should I pass the strings to the calculation function (not written yet), do my calculations and have it return strings? Or do you have another way? Thanks Sander From bgailer at gmail.com Tue Jan 6 04:38:03 2009 From: bgailer at gmail.com (bob gailer) Date: Mon, 05 Jan 2009 22:38:03 -0500 Subject: [Tutor] Convert values in a list back and forth from ints and time In-Reply-To: References: Message-ID: <4962D21B.1070702@gmail.com> Sander Sweers wrote: > Hello Tutors, > > I use the csv module to read and write a csv file. When I read the > file into a new list I convert the ints and the dates to int and time > objects so I can do calculations. I use the below function which > works. > > def convertValue(value, dateformat, reverse=False): > if reverse: > try: > return strftime(dateformat, value) > except TypeError: > return str(value) > else: > try: > return int(float(value)) > except ValueError: > try: > return strptime(value, dateformat) > except: > return value > > When writing the lines back to a csv file I loop over the lists and > convert the values back with the same function but in reverse but.... > > I was just wondering if there is another way of dealing with this. > Should I pass the strings to the calculation function (not written > yet), do my calculations and have it return strings? I prefer separation of tasks. Let the calculation routines expect and return numbers. I also suggest splitting convertValue into two functions, one that takes strings and one that takes numbers. A lot easier to read and maintain. FWIW you could dispense with reverse in convertValue by testing the type of value for int or str. -- Bob Gailer Chapel Hill NC 919-636-4239 From dextrous85 at gmail.com Tue Jan 6 06:01:34 2009 From: dextrous85 at gmail.com (vishwajeet singh) Date: Tue, 6 Jan 2009 10:31:34 +0530 Subject: [Tutor] Question regarding win32com getting ldap object In-Reply-To: <8e63a5ce0901051158i32b2af2al24cb89db54182c0e@mail.gmail.com> References: <5487b3060901050104g3d10c577s1ee0bc8303712ae4@mail.gmail.com> <8e63a5ce0901051158i32b2af2al24cb89db54182c0e@mail.gmail.com> Message-ID: <5487b3060901052101l7af23ba8x7a52d514d81f42a2@mail.gmail.com> Thanks for the help. It worked for me. On Tue, Jan 6, 2009 at 1:28 AM, Jervis Whitley wrote: > > > On Mon, Jan 5, 2009 at 8:04 PM, vishwajeet singh wrote: > >> Hi List, >> >> I am running following code to get ldap com object but the result I am >> getting is unknown >> I am using Python 25 and win32 bindings available at >> http://downloads.sourceforge.net/pywin32/pywin32-212.win32-py2.2.exe?modtime=1217535908&big_mirror=0 >> >> *adsi = win32com.client.Dispatch('ADsNameSpaces') >> print adsi >> ldap = adsi.getobject('', 'LDAP:') >> print ldap* >> >> OutPut: >> >> > >> >> Any ideas what I am doing wrong ? >> >> -- >> Cheers, >> Vishwajeet >> http://www.singhvishwajeet.com >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> Hi, > try the following from the archive: > > http://mail.python.org/pipermail/python-list/1999-December/018594.html > > Cheers, > > Jervis > -- Cheers, Vishwajeet http://www.singhvishwajeet.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Jan 6 09:46:16 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 6 Jan 2009 08:46:16 -0000 Subject: [Tutor] Convert values in a list back and forth from ints and time References: Message-ID: "Sander Sweers" wrote > I use the csv module to read and write a csv file. When I read the > file into a new list I convert the ints and the dates to int and > time > When writing the lines back to a csv file I loop over the lists and > convert the values back with the same function but in reverse > but.... > > I was just wondering if there is another way of dealing with this. If you always convert the values back to strings then you could just hold onto the original strings by storing them in a (str, val) tuple. If you do calculations and modify anmy of them then convert the value/string there and then and modify the tuple. You could even make it a class with the convertion fiunctions being methods. But whether the extra complexity is worthwhile will depend on what proportion of values get modified. If its a small proportion then the gain in speed from not doing the reverse convertion might be worth it. In most cases what you have done is probably the simplest approach and if its fast enough then don't worry about it! PS. I agree with Bob about splitting the function in two... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk From wferguson1 at socal.rr.com Tue Jan 6 18:53:00 2009 From: wferguson1 at socal.rr.com (WM.) Date: Tue, 06 Jan 2009 09:53:00 -0800 Subject: [Tutor] WAYNE'S WAINING... Message-ID: <49639A7C.5040400@socal.rr.com> One of the replies to my post explained how difficult it is to address an audience composed of several levels of skill. I understand that, nor was I condemning anyone who has a better command of jargon than I have. Jargon is essential to any trade. What I wanted to do was give Wayne the POV of someone who posted for a while, then gave up. I have plenty of questions, I shall try to put some of them in intelligible form, for your amusement. From sander.sweers at gmail.com Tue Jan 6 19:30:31 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Tue, 6 Jan 2009 19:30:31 +0100 Subject: [Tutor] Convert values in a list back and forth from ints and time In-Reply-To: <4962D21B.1070702@gmail.com> References: <4962D21B.1070702@gmail.com> Message-ID: On Tue, Jan 6, 2009 at 04:38, bob gailer wrote: > I also suggest splitting convertValue into two functions, one that takes > strings and one that takes numbers. A lot easier to read and maintain. > > FWIW you could dispense with reverse in convertValue by testing the type of > value for int or str. Thanks for feedback and suggestions. Below is the function split in 2. def convertToString(value, dateformat): print value if type(value) == int: return str(value) else: try: return strftime(dateformat, value) except TypeError: return value def convertFromString(value, dateformat): try: return int(float(value)) except ValueError: try: return strptime(value, dateformat) except: return value Greets Sander From sander.sweers at gmail.com Tue Jan 6 19:43:16 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Tue, 6 Jan 2009 19:43:16 +0100 Subject: [Tutor] Convert values in a list back and forth from ints and time In-Reply-To: References: Message-ID: On Tue, Jan 6, 2009 at 09:46, Alan Gauld wrote: > If you always convert the values back to strings then you could > just hold onto the original strings by storing them in a (str, val) tuple. > If you do calculations and modify anmy of them then convert the > value/string there and then and modify the tuple. You could even > make it a class with the convertion fiunctions being methods. > But whether the extra complexity is worthwhile will depend on > what proportion of values get modified. If its a small proportion > then the gain in speed from not doing the reverse convertion might > be worth it. In most cases what you have done is probably the > simplest approach and if its fast enough then don't worry about it! This is too complex and the speed is good enough for 2000 lines in the file. however... I am doing this to learn about python and programming. So I am interested how this class would look like. Could you give an example or point me in the right direction how I can figure it out for myself? Thanks Sander From bgailer at gmail.com Tue Jan 6 19:55:50 2009 From: bgailer at gmail.com (bob gailer) Date: Tue, 06 Jan 2009 13:55:50 -0500 Subject: [Tutor] Convert values in a list back and forth from ints and time In-Reply-To: References: <4962D21B.1070702@gmail.com> Message-ID: <4963A936.1010805@gmail.com> An HTML attachment was scrubbed... URL: From wferguson1 at socal.rr.com Tue Jan 6 20:12:16 2009 From: wferguson1 at socal.rr.com (WM.) Date: Tue, 06 Jan 2009 11:12:16 -0800 Subject: [Tutor] Interactive programming. Message-ID: <4963AD10.4060003@socal.rr.com> >>> i = 5 >>> j = 7 >>> if i <= j: print 'nudge, nudge' else: File "", line 3 else: ^ IndentationError: unexpected indent Running in IDLE, all is well until "else:". IDLE seems perplexed about the >>>s. I try to de-dent else via the backspace key, after that there is no way to avoid an error message. From norman at khine.net Tue Jan 6 20:41:49 2009 From: norman at khine.net (Norman Khine) Date: Tue, 06 Jan 2009 20:41:49 +0100 Subject: [Tutor] Interactive programming. In-Reply-To: <4963AD10.4060003@socal.rr.com> References: <4963AD10.4060003@socal.rr.com> Message-ID: <4963B3FD.1010504@khine.net> >>> i = 5 >>> j = 7 >>> if i <= j: ... print 'nudge', 'nudge' ... else: ... print 'whatever' ... nudge nudge >>> WM. wrote: > >>> i = 5 > >>> j = 7 > >>> if i <= j: > print 'nudge, nudge' > else: > > File "", line 3 > else: > ^ > IndentationError: unexpected indent > > Running in IDLE, all is well until "else:". IDLE seems perplexed about > the >>>s. I try to de-dent else via the backspace key, after that there > is no way to avoid an error message. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Tue Jan 6 20:40:13 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Tue, 6 Jan 2009 19:40:13 +0000 (GMT) Subject: [Tutor] Convert values in a list back and forth from ints and time Message-ID: <592976.37391.qm@web86704.mail.ird.yahoo.com> > > If you always convert the values back to strings then you could > > just hold onto the original strings by storing them in a (str, val) tuple. > > If you do calculations and modify anmy of them then convert the > > value/string there and then and modify the tuple. You could even > > make it a class with the convertion fiunctions being methods. > This is too complex and the speed is good enough for 2000 lines in the > file. however... Fair enough, I suspected as much. > I am doing this to learn about python and programming. So I am > interested how this class would look like. Could you give an example > or point me in the right direction how I can figure it out for myself? You just nered to define a class that can take a string and has methods to return the value. You could store both string and value as attributes and have two methods to convert between them. Here is a very simple example: >>> class Value: ... def __init__(self, vs = ""): ... self.vs = vs ... self.v = self.asInt() ... def asInt(self): ... try: self.v = int(self.vs) ... except: self.v = None ... return self.v ... def asString(self): ... vs = str(self.vs) ... return self.vs ... def setStringValue(self, s): ... self.vs = s ... self.asInt() ... def setIntValue(self, i): ... self.v = int(i) ... self.vs = str(self.v) ... >>> v = Value('42') >>> print v.v, v.vs 42 42 >>> v.setStringValue('66') >>> print v.v, v.vs 66 66 >>> v.setIntValue(7) >>> print v.v, v.vs 7 7 >>> HTH, Alan G. From alan.gauld at btinternet.com Tue Jan 6 20:57:39 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 6 Jan 2009 19:57:39 -0000 Subject: [Tutor] Interactive programming. References: <4963AD10.4060003@socal.rr.com> Message-ID: "WM." wrote > >>> i = 5 > >>> j = 7 > >>> if i <= j: > print 'nudge, nudge' > else: > > File "", line 3 > else: > ^ > IndentationError: unexpected indent > > Running in IDLE, all is well until "else:". IDLE seems perplexed This is, in my view, a long standing bug in IDLE. It doesn't show indentation properly in the shell window. If possible I'd suggest you try using Pythonwin or PyCrust or IPython or any of the other 3rd party shell windows. If you use them they will typically insert three dots as a secondary prompt which keeps everything lined up properly. The else should align with the if but in Idle it has to align to the left margin because the if is only indented due to >>> prompt! This is confusing, and effectively a bug in my opinion. Your if statement in IDLE should look like: >>> if i <= j: print 'nudge, nudge' else: ie the print should be indented and the else not be. Without the >>> it becomes sane: if i <= j: print 'nudge, nudge' else: -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk From sander.sweers at gmail.com Tue Jan 6 21:16:41 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Tue, 6 Jan 2009 21:16:41 +0100 Subject: [Tutor] Interactive programming. In-Reply-To: <4963AD10.4060003@socal.rr.com> References: <4963AD10.4060003@socal.rr.com> Message-ID: On Tue, Jan 6, 2009 at 20:12, WM. wrote: >>>> i = 5 >>>> j = 7 >>>> if i <= j: > print 'nudge, nudge' > else: > > File "", line 3 > else: > ^ > IndentationError: unexpected indent Python uses indentation to seperate code blocks and will throw an error if it finds inconsistancies. In your example else is indented while it sould not be. There is also a second error in the code. If you have an else you need to do something in the else block. Below is a working version. >>> i = 5 >>> j = 7 >>> if i <= j: print 'Nudge nudge' else: print 'Icecream' Nudge nudge I know it looks weird in idle as the original if i <= j is to the right of the else but both are *not* indented. Greets Sander From marc.tompkins at gmail.com Tue Jan 6 21:24:07 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 6 Jan 2009 12:24:07 -0800 Subject: [Tutor] WAYNE'S WANING... Message-ID: <40af687b0901061224n2103cbbbi7a5832c74de99f56@mail.gmail.com> Sorry - forgot to Reply All... On Tue, Jan 6, 2009 at 9:53 AM, WM. wrote: > One of the replies to my post explained how difficult it is to address an > audience composed of several levels of skill. I understand that, nor was I > condemning anyone who has a better command of jargon than I have. Jargon is > essential to any trade. What I wanted to do was give Wayne the POV of > someone who posted for a while, then gave up. I have plenty of questions, I > shall try to put some of them in intelligible form, for your amusement. > One thing that tends to happen here results from the fact that in Python (as in Perl) there's always more than one way to do it, and each method has its enthusiasts. So Original Poster will ask a question - possibly fairly basic - Tutor A will chime in with an answer; Tutor B will chime in with a totally different approach; Tutor C will point out a third way that's more elegant but requires understanding of advanced CS concepts; eventually the thread becomes totally incomprehensible to Original Poster. Please bear with us - we all love the language and want other people to love it too. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From wferguson1 at socal.rr.com Tue Jan 6 22:10:13 2009 From: wferguson1 at socal.rr.com (WM.) Date: Tue, 06 Jan 2009 13:10:13 -0800 Subject: [Tutor] Interactive programming. In-Reply-To: <4963B3FD.1010504@khine.net> References: <4963AD10.4060003@socal.rr.com> <4963B3FD.1010504@khine.net> Message-ID: <4963C8B5.6070600@socal.rr.com> Norman Khine wrote: > >>> i = 5 > >>> j = 7 > >>> if i <= j: > ... print 'nudge', 'nudge' > ... else: > ... print 'whatever' > ... > nudge nudge > >>> > > > WM. wrote: >> >>> i = 5 >> >>> j = 7 >> >>> if i <= j: >> print 'nudge, nudge' >> else: >> File "", line 3 >> else: >> ^ >> IndentationError: unexpected indent >> >> Running in IDLE, all is well until "else:". IDLE seems perplexed about >> the >>>s. I try to de-dent else via the backspace key, after that >> there is no way to avoid an error message. >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > Yes, I understand how your program works. What I do not understand is how you got it. My program came out in IDLE as you see it. No ..., different indentation, an error message before I could add the else alternative. (Which, as a Pythonista, one should know, is "Wink-wink".) From david at abbottdavid.com Wed Jan 7 01:34:28 2009 From: david at abbottdavid.com (David) Date: Tue, 06 Jan 2009 19:34:28 -0500 Subject: [Tutor] Linux tail -f multiple log files Message-ID: <4963F894.4050001@abbottdavid.com> Hi, This works fine if I don't use the -f option; #!/usr/bin/python from subprocess import call from termcolor import colored def slog(): sudo = "sudo" tail = "tail" sfile = "/var/log/messages" print colored("", "blue") call([sudo, tail, sfile]) def alog(): sudo = "sudo" tail = "tail" afile = "/var/log/apache2/access_log" print colored("", "green") call([sudo, tail, afile]) def elog(): sudo = "sudo" tail = "tail" afile = "/var/log/apache2/error_log" print colored("", "red") call([sudo, tail, afile]) def main(): slog() alog() elog() if __name__ == "__main__": main() Now if I do this to all the functions; def slog(): sudo = "sudo" tail = "tail" targ = "-f" # output appended data as the file grows sfile = "/var/log/messages" print colored("", "blue") call([sudo, tail, sfile]) Only the first function will print to the screen. thanks in advance, -david -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From david at abbottdavid.com Wed Jan 7 01:40:50 2009 From: david at abbottdavid.com (David) Date: Tue, 06 Jan 2009 19:40:50 -0500 Subject: [Tutor] Linux tail -f multiple log files In-Reply-To: <4963F894.4050001@abbottdavid.com> References: <4963F894.4050001@abbottdavid.com> Message-ID: <4963FA12.8020507@abbottdavid.com> > > Now if I do this to all the functions; > def slog(): > sudo = "sudo" > tail = "tail" > targ = "-f" # output appended data as the file grows > sfile = "/var/log/messages" > print colored("", "blue") > call([sudo, tail, sfile]) > > Only the first function will print to the screen. > > thanks in advance, > -david > oops should be; def slog(): sudo = "sudo" tail = "tail" targ = "-f" # output appended data as the file grows sfile = "/var/log/messages" print colored("", "blue") call([sudo, tail, targ, sfile]) -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From bill at celestial.net Wed Jan 7 01:46:41 2009 From: bill at celestial.net (Bill Campbell) Date: Tue, 6 Jan 2009 16:46:41 -0800 Subject: [Tutor] Linux tail -f multiple log files In-Reply-To: <4963FA12.8020507@abbottdavid.com> References: <4963F894.4050001@abbottdavid.com> <4963FA12.8020507@abbottdavid.com> Message-ID: <20090107004641.GA12255@ayn.mi.celestial.com> On Tue, Jan 06, 2009, David wrote: >> >> Now if I do this to all the functions; >> def slog(): >> sudo = "sudo" >> tail = "tail" >> targ = "-f" # output appended data as the file grows >> sfile = "/var/log/messages" >> print colored("", "blue") >> call([sudo, tail, sfile]) >> >> Only the first function will print to the screen. >> >> thanks in advance, >> -david >> > oops should be; > def slog(): > sudo = "sudo" > tail = "tail" > targ = "-f" # output appended data as the file grows > sfile = "/var/log/messages" > print colored("", "blue") > call([sudo, tail, targ, sfile]) Looking at how swatch does this I think the command you want to use is: cmd = 'sudo tail --follow=name --lines=1 %s' % ' '.join(args) tail = os.popen(cmd) # process output ... Bill -- INTERNET: bill at celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax: (206) 232-9186 It does not require a majority to prevail, but rather an irate, tireless minority keen to set brush fires in people's minds. -- Samuel Adams From kent37 at tds.net Wed Jan 7 03:10:50 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 6 Jan 2009 21:10:50 -0500 Subject: [Tutor] Linux tail -f multiple log files In-Reply-To: <4963F894.4050001@abbottdavid.com> References: <4963F894.4050001@abbottdavid.com> Message-ID: <1c2a2c590901061810pe13046bl8586c107cc3f09c5@mail.gmail.com> On Tue, Jan 6, 2009 at 7:34 PM, David wrote: > Hi, > This works fine if I don't use the -f option; > #!/usr/bin/python > from subprocess import call > from termcolor import colored > > def slog(): > sudo = "sudo" > tail = "tail" > sfile = "/var/log/messages" > print colored("", "blue") > call([sudo, tail, sfile]) > > > def alog(): > sudo = "sudo" > tail = "tail" > afile = "/var/log/apache2/access_log" > print colored("", "green") > call([sudo, tail, afile]) > > def elog(): > sudo = "sudo" > tail = "tail" > afile = "/var/log/apache2/error_log" > print colored("", "red") > call([sudo, tail, afile]) > > def main(): > slog() > alog() > elog() > > if __name__ == "__main__": > main() > > Now if I do this to all the functions; > def slog(): > sudo = "sudo" > tail = "tail" > targ = "-f" # output appended data as the file grows > sfile = "/var/log/messages" > print colored("", "blue") > call([sudo, tail, sfile]) > > Only the first function will print to the screen. subprocess.call() does not return until the spawned process terminates. tail -f does not terminate so the later functions are never called. You need to use a non-blocking operation to spawn the subprocess. Kent From wormwood_3 at yahoo.com Wed Jan 7 04:18:12 2009 From: wormwood_3 at yahoo.com (wormwood_3) Date: Tue, 6 Jan 2009 19:18:12 -0800 (PST) Subject: [Tutor] Getting multi-line input from user Message-ID: <769354.18027.qm@web110814.mail.gq1.yahoo.com> Hello everyone, I'd like to prompt the user for input and get back multiple lines, for example if someone wanted to enter a few paragraphs. Then I'd like to be able to print their input out and preserve formatting. Here's what I have so far: control = True user_input = [] while control: if not user_input: entry = raw_input("Enter text, 'done' on its own line to quit: \n") user_input.append(entry) else: entry = raw_input("") user_input.append(entry) if entry == "done": del user_input[-1] control = False user_input = ' '.join(user_input) print user_input So you end up with: Enter text, 'done' on its own line to quit: I am some text. And I am more. I am a new paragraph. done I am some text. And I am more. I am a new paragraph. 1) Is there a more elegant/common way to get multi-line user input than this sort of thing? 2) How can I combine and print the output so that paragraphs and the like are preserved? Thanks, Sam _______________________ Samuel Huckins Homepage - http://samuelhuckins.com Tech blog - http://dancingpenguinsoflight.com/ Photos - http://www.flickr.com/photos/samuelhuckins/ AIM - samushack | Gtalk - samushack | Skype - shuckins -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Wed Jan 7 04:24:26 2009 From: bgailer at gmail.com (bob gailer) Date: Tue, 06 Jan 2009 22:24:26 -0500 Subject: [Tutor] Getting multi-line input from user In-Reply-To: <769354.18027.qm@web110814.mail.gq1.yahoo.com> References: <769354.18027.qm@web110814.mail.gq1.yahoo.com> Message-ID: <4964206A.7060500@gmail.com> wormwood_3 wrote: > Hello everyone, > > I'd like to prompt the user for input and get back multiple lines, for > example if someone wanted to enter a few paragraphs. Then I'd like to > be able to print their input out and preserve formatting. Here's what > I have so far: > > control = True > user_input = [] > while control: > if not user_input: > entry = raw_input("Enter text, 'done' on its own line to quit: > \n") > user_input.append(entry) > else: > entry = raw_input("") > user_input.append(entry) > if entry == "done": > del user_input[-1] > control = False > user_input = ' '.join(user_input) > print user_input > > So you end up with: > > Enter text, 'done' on its own line to quit: > I am some text. > And I am more. > > I am a new paragraph. > done > I am some text. And I am more. I am a new paragraph. > > 1) Is there a more elegant/common way to get multi-line user input > than this sort of thing? For starters you can simplify things a lot: user_input = [] entry = raw_input("Enter text, 'done' on its own line to quit: \n") while entry != "done": user_input.append(entry) entry = raw_input("") user_input = ' '.join(user_input) print user_input > 2) How can I combine and print the output so that paragraphs and the > like are preserved? I don't understand. Please give an example. -- Bob Gailer Chapel Hill NC 919-636-4239 From wormwood_3 at yahoo.com Wed Jan 7 04:31:59 2009 From: wormwood_3 at yahoo.com (wormwood_3) Date: Tue, 6 Jan 2009 19:31:59 -0800 (PST) Subject: [Tutor] Getting multi-line input from user References: <769354.18027.qm@web110814.mail.gq1.yahoo.com> <4964206A.7060500@gmail.com> Message-ID: <594795.97475.qm@web110807.mail.gq1.yahoo.com> >>> For starters you can simplify things a lot: >>> >>> user_input = [] >>> entry = raw_input("Enter text, 'done' on its own line to quit: \n") >>> while entry != "done": >>> user_input.append(entry) >>> entry = raw_input("") >>> user_input = ' '.join(user_input) >>> print user_input >>> >>> 2) How can I combine and print the output so that paragraphs and the like are preserved? >>> >>> I don't understand. Please give an example. That is much cleaner, thanks! On point 2, say I enter: Enter text, 'done' on its own line to quit: I am a sentence. I am another sentence. I am a new paragraph. done What I get out is: I am a sentence. I am another sentence. I am a new paragraph. But that just shows the double new lines of my new paragraph as an extra space. I'd like to print it out so it appears just as it was typed in, with appropriate newlines. -Sam -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Wed Jan 7 07:19:23 2009 From: andreengels at gmail.com (Andre Engels) Date: Wed, 7 Jan 2009 07:19:23 +0100 Subject: [Tutor] Getting multi-line input from user In-Reply-To: <594795.97475.qm@web110807.mail.gq1.yahoo.com> References: <769354.18027.qm@web110814.mail.gq1.yahoo.com> <4964206A.7060500@gmail.com> <594795.97475.qm@web110807.mail.gq1.yahoo.com> Message-ID: <6faf39c90901062219o66cfd382p7b3c00199a1addd3@mail.gmail.com> On Wed, Jan 7, 2009 at 4:31 AM, wormwood_3 wrote: > On point 2, say I enter: > Enter text, 'done' on its own line to quit: > I am a sentence. I am another sentence. > > I am a new paragraph. > done > > What I get out is: > I am a sentence. I am another sentence. I am a new paragraph. > > But that just shows the double new lines of my new paragraph as an extra > space. I'd like to print it out so it appears just as it was typed in, with > appropriate newlines. The newline character is written \n in Python, so if you replace ' '.join(user_input) by '\n'.join(user_input) you should be getting what you want. -- Andr? Engels, andreengels at gmail.com From prasadaraon50 at gmail.com Wed Jan 7 09:45:57 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Wed, 7 Jan 2009 00:45:57 -0800 Subject: [Tutor] Convert values in a list back and forth from ints Message-ID: <9e3fac840901070045vdbe1cabv97648e12def79dda@mail.gmail.com> .>>>> class Value:.... def __init__(self, vs = ""): >... self.vs = vs >... self.v = self.asInt() >... def asInt(self): >... try: self.v = int(self.vs) >... except: self.v = None >... return self.v >... def asString(self): >... vs = str(self.vs) >... return self.vs >... def setStringValue(self, s): >... self.vs = s >... self.asInt() >... def setIntValue(self, i): >... self.v = int(i) >... self.vs = str(self.v) hello Sorry to interject. This class seems asymmetric. Class Value: def __init__(self,inte='',stri=''): self.inte=inte self.stri=stri def setvalue(inte='',stri=''): self.stri=str(self.inte) self.int=int(self.stri) I tried. But failed.What is wrong with above code? >>> Class Value: def __init__(self,inte='',stri=''): self.inte=inte self.stri=stri def setvalue(inte='',stri=''): self.stri=str(self.inte) self.int=int(self.stri) SyntaxError: invalid syntax Prasad -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Jan 7 09:56:21 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 7 Jan 2009 08:56:21 -0000 Subject: [Tutor] Getting multi-line input from user References: <769354.18027.qm@web110814.mail.gq1.yahoo.com><4964206A.7060500@gmail.com> <594795.97475.qm@web110807.mail.gq1.yahoo.com> Message-ID: "wormwood_3" wrote > On point 2, say I enter: > Enter text, 'done' on its own line to quit: > I am a sentence. I am another sentence. > > I am a new paragraph. > done > > What I get out is: > I am a sentence. I am another sentence. I am a new paragraph. > > But that just shows the double new lines of my new paragraph as an > extra space. raw_input strips off the newline character created by Enter. You need to add it back in: entry = raw_input() user_input.append(entry+'\n') HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk From alan.gauld at btinternet.com Wed Jan 7 09:58:18 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 7 Jan 2009 08:58:18 -0000 Subject: [Tutor] Getting multi-line input from user References: <769354.18027.qm@web110814.mail.gq1.yahoo.com><4964206A.7060500@gmail.com><594795.97475.qm@web110807.mail.gq1.yahoo.com> <6faf39c90901062219o66cfd382p7b3c00199a1addd3@mail.gmail.com> Message-ID: "Andre Engels" wrote > The newline character is written \n in Python, so if you replace > > ' '.join(user_input) > > by > > '\n'.join(user_input) Yep, that's better than my suggestion of adding the \n at append time. :-) Alan G. From marco.m.petersen at gmail.com Tue Jan 6 10:45:01 2009 From: marco.m.petersen at gmail.com (Marco Petersen) Date: Tue, 06 Jan 2009 17:45:01 +0800 Subject: [Tutor] SMTP Module Help Message-ID: <4963281D.9070009@gmail.com> I'm using Python 2.5.4. I wanted to try out the SMTP module. I tried to send an email through my Gmail account but it keeps saying that the connection was refused. This is the code that I used : import smtplib msg = 'Test' server = smtplib.SMTP('smtp.gmail.com') server.set_debuglevel(1) server.ehlo() server.starttls() server.ehlo() server.login('marco.m.petersen at gmail.com', 'password') server.sendmail('marco.m.petersen at gmail.com', 'marcoleepetersen at gmail.com', msg) server.close() This error message keeps coming up: Traceback (most recent call last): File "C:/Python25/send_mail.py", line 5, in server = smtplib.SMTP('smtp.gmail.com') File "C:\Python25\Lib\smtplib.py", line 244, in __init__ (code, msg) = self.connect(host, port) File "C:\Python25\Lib\smtplib.py", line 310, in connect raise socket.error, msg error: (10061, 'Connection refused') Can anyone help me with this? Thanks. -Marco From andreengels at gmail.com Wed Jan 7 10:51:56 2009 From: andreengels at gmail.com (Andre Engels) Date: Wed, 7 Jan 2009 10:51:56 +0100 Subject: [Tutor] Convert values in a list back and forth from ints In-Reply-To: <9e3fac840901070045vdbe1cabv97648e12def79dda@mail.gmail.com> References: <9e3fac840901070045vdbe1cabv97648e12def79dda@mail.gmail.com> Message-ID: <6faf39c90901070151u13410945m962a5cf7290bcbfb@mail.gmail.com> On Wed, Jan 7, 2009 at 9:45 AM, prasad rao wrote: > hello > Sorry to interject. > This class seems asymmetric. > Class Value: > def __init__(self,inte='',stri=''): > self.inte=inte > self.stri=stri > def setvalue(inte='',stri=''): > self.stri=str(self.inte) > self.int=int(self.stri) > I tried. But failed.What is wrong with above code? > > >>> Class Value: > def __init__(self,inte='',stri=''): > self.inte=inte > self.stri=stri > def setvalue(inte='',stri=''): > self.stri=str(self.inte) > self.int=int(self.stri) > > SyntaxError: invalid syntax 'class' should not start with a capital. I do by the way wonder what your code is supposed to accomplish - why have arguments inte and stri for setvalue when you don't use them (you use the existing value of self.stri). -- Andr? Engels, andreengels at gmail.com From prasadaraon50 at gmail.com Wed Jan 7 10:57:35 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Wed, 7 Jan 2009 01:57:35 -0800 Subject: [Tutor] re Message-ID: <9e3fac840901070157p5b15d256g40db2be09611e61d@mail.gmail.com> Hello I am trying to get a value as integer and a string. >>> class Value: def __init__(self,inte='',stri=''): self.inte=inte self.stri=stri def setvalue(self,inte='',stri=''): self.stri=str(self.inte) self.inte=int(self.stri) >>> v=Value(45) >>> print v.stri >>> v.inte 45 >>> v.stri '' >>> c=Value('36') >>> c.stri '' >>> But it is not converting.How can I do it? Prasad -------------- next part -------------- An HTML attachment was scrubbed... URL: From KLegodi at csir.co.za Wed Jan 7 10:46:05 2009 From: KLegodi at csir.co.za (Kgotlelelo Legodi) Date: Wed, 07 Jan 2009 11:46:05 +0200 Subject: [Tutor] good day Message-ID: <496495FD0200004000022646@pta-emo.csir.co.za> good day I just started using python and i want to know how can i solve a boundary value problem for ordinary differential equations using shooting method in python.use the general equation to demonstrate the python code. Thank you -- This message is subject to the CSIR's copyright terms and conditions, e-mail legal notice, and implemented Open Document Format (ODF) standard. The full disclaimer details can be found at http://www.csir.co.za/disclaimer.html. This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. MailScanner thanks Transtec Computers for their support. From andreengels at gmail.com Wed Jan 7 11:09:51 2009 From: andreengels at gmail.com (Andre Engels) Date: Wed, 7 Jan 2009 11:09:51 +0100 Subject: [Tutor] re In-Reply-To: <9e3fac840901070157p5b15d256g40db2be09611e61d@mail.gmail.com> References: <9e3fac840901070157p5b15d256g40db2be09611e61d@mail.gmail.com> Message-ID: <6faf39c90901070209r17c0ec27s138d4f2034747c44@mail.gmail.com> On Wed, Jan 7, 2009 at 10:57 AM, prasad rao wrote: > Hello > I am trying to get a value as integer and a string. >>>> class Value: > def __init__(self,inte='',stri=''): > self.inte=inte > self.stri=stri > def setvalue(self,inte='',stri=''): > self.stri=str(self.inte) > self.inte=int(self.stri) > >>>> v=Value(45) >>>> print v.stri >>>> v.inte > 45 >>>> v.stri > '' >>>> c=Value('36') >>>> c.stri > '' >>>> > But it is not converting.How can I do it? > Prasad > Let's take a step back, and see what is happening here. >>>> v=Value(45) This means that you create a Value object. If you create an object, its __init__ is called. What does that ini look like? def __init__(self,inte='',stri='') We disregard the 'self' for now, and look at the other arguments. The _first_ argument of your function will be mapped to inte, the second to stri. In this case you have only one argument, so this argument (45) will be mapped to inte, and stri will take its default value (which is '') > self.inte=inte > self.stri=stri So after this, self.inte will be set to inte (that is 45), and self.stri to stri (that is ''). Which indeed is exactly what you get when you look up v.inte and v.stri. >>>> c=Value('36') If we go through the analysis above, you will find that after this c.inte = '36' c.stri = '' What would you _want_ to do? I think what you want is the following: you give a single argument, which can either be an integer or a string representing an integer, and the local variables inte and string should then give the integer and string representation of that argument. This can be done in the following way: class Value: def __init__(self,val): # I do not add a default value for val, because I will always call Value(somevalue), not Value() self.inte = int(val) # Whether val is a string or an integer, this will be its integer representation self.stri = str(val) # similar (when typing this in you can of course do without the #s and whatever I have written after that) -- Andr? Engels, andreengels at gmail.com From a.t.hofkamp at tue.nl Wed Jan 7 11:28:29 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Wed, 07 Jan 2009 11:28:29 +0100 Subject: [Tutor] Interactive programming. In-Reply-To: <4963C8B5.6070600@socal.rr.com> References: <4963AD10.4060003@socal.rr.com> <4963B3FD.1010504@khine.net> <4963C8B5.6070600@socal.rr.com> Message-ID: <496483CD.3040806@tue.nl> WM. wrote: > Norman Khine wrote: >> >>> i = 5 >> >>> j = 7 >> >>> if i <= j: >> ... print 'nudge', 'nudge' >> ... else: >> ... print 'whatever' >> ... >> nudge nudge >> >>> > Yes, I understand how your program works. What I do not understand is > how you got it. My program came out in IDLE as you see it. No ..., > different indentation, an error message before I could add the else > alternative. (Which, as a Pythonista, one should know, is "Wink-wink".) In IDLE in the window with the ">>>" prompt: After the colon at the 'if' line, you press ENTER (ie you tell Python 'the line has ended here'). The interpreter then supplies the "..." to denote that you are entering a multi-line statement. You then continue entering the next lines (with some indenting for both branches!!), pressing ENTER after each line. At the end (just above the "nudge nudge" output), Python also gives a "..." prompt, to give you the option to enter more statements under the last print. Since you don't have any more statements, just press ENTER (saying, 'I am finished'). Then Python will execute the complete if statement (and one of the branches), and output the result. The normal approach however for entering a program is to use an editor window. Click on 'new file' somewhere in IDLE (I am not an IDLE user nor do I have the program around, so I cannot give you more precise directions unfortunately), and enter the Python program without the ">>>" and "..." stuff at the start of the line. Once you are finished, save it, and press 'run' (it is in a menu somewhere if I remember correctly). Then the Python interpreter will run all statements in the file. With this approach you can also load (and run) previous made programs (which is a quite useful feature, I might add :) ). (Instead of 'new file', use 'load file' or 'edit file'). Good luck, Albert From a.t.hofkamp at tue.nl Wed Jan 7 11:35:23 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Wed, 07 Jan 2009 11:35:23 +0100 Subject: [Tutor] good day In-Reply-To: <496495FD0200004000022646@pta-emo.csir.co.za> References: <496495FD0200004000022646@pta-emo.csir.co.za> Message-ID: <4964856B.5050005@tue.nl> Kgotlelelo Legodi wrote: > good day > > I just started using python and i want to know how can i solve a boundary value problem for ordinary differential equations using shooting method in python.use the general equation to demonstrate the python code. I have no background in numeric calculations, but for starters, you may want to investigate the numpy and/or scipy Python packages. Google will probably also give you good starting points of existing numeric code/libraries. As for actually writing the program, I am afraid you'll have to do that yourself. Sincerely, Albert From a.t.hofkamp at tue.nl Wed Jan 7 11:49:25 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Wed, 07 Jan 2009 11:49:25 +0100 Subject: [Tutor] SMTP Module Help In-Reply-To: <4963281D.9070009@gmail.com> References: <4963281D.9070009@gmail.com> Message-ID: <496488B5.9040206@tue.nl> Marco Petersen wrote: > I'm using Python 2.5.4. I wanted to try out the SMTP module. I tried to > send an email through my Gmail account but it keeps saying that the > connection was refused. > > This is the code that I used : > > import smtplib > msg = 'Test' > > > server = smtplib.SMTP('smtp.gmail.com') > server.set_debuglevel(1) > server.ehlo() > server.starttls() > server.ehlo() > server.login('marco.m.petersen at gmail.com', 'password') > server.sendmail('marco.m.petersen at gmail.com', > 'marcoleepetersen at gmail.com', msg) > server.close() > > This error message keeps coming up: > > > Traceback (most recent call last): > File "C:/Python25/send_mail.py", line 5, in > server = smtplib.SMTP('smtp.gmail.com') > File "C:\Python25\Lib\smtplib.py", line 244, in __init__ > (code, msg) = self.connect(host, port) > File "C:\Python25\Lib\smtplib.py", line 310, in connect > raise socket.error, msg > error: (10061, 'Connection refused') 'Connection refused' usually means that the other side doesn't like you for some reason. (In other words, it doesn't look like a Python problem but like a network problem.) Since it happens before you can start the protocol, my guess is that smtp.gmail.com does not accept your machine as valid to speak SMTP with (at least not at the port you are trying). The person to talk to would be the owner/admin of smtp.gmail.com. Sincerely, Albert From david at hlacik.eu Wed Jan 7 11:59:05 2009 From: david at hlacik.eu (=?ISO-8859-2?Q?David_Hl=E1=E8ik?=) Date: Wed, 7 Jan 2009 11:59:05 +0100 Subject: [Tutor] linked list with cycle structure In-Reply-To: References: Message-ID: Hello guys, I have a linked list where *number of elements is unlimited* and **last element points on random (can be first, last, in middle , anywhere) element within linked list** - this is important . My goals is to create an architecture /scheme for **algoritmus which will count total number of elements** of such linked list. Yes , maybe it sounds strange, but we need to implement this and i would be very gladfull for your toughts. Thanks in advance and wishing you a sucessfull year! David From mickmick at hotmail.co.uk Wed Jan 7 07:06:30 2009 From: mickmick at hotmail.co.uk (mickth) Date: Tue, 6 Jan 2009 22:06:30 -0800 (PST) Subject: [Tutor] Brand new to python have simple problem Message-ID: <21325502.post@talk.nabble.com> I'm brand new to python and every time i start to learn it i get the same problem and end up giving up and moving on to another language. the print statement doesn't work in either the comand line or IDLE i get this in IDLE: SyntaxError: invalid syntax (, line 1) and just SyntaxError: invalid syntax in the command line. Even doing the hello world or doing simple sums. If I type "hello, world" i get the right outcome but print "Hello world" i get the error. When i type print it's purple in IDLE if that means anything. I've tried reinstalling python and tried an earlier version with same results. i'm running windows vista home prem 32bit I know i may seem an imbecile for posting such a simple thing but i'm determined to learn it this time i've already learnt vb and C and want to broaden out! Thanks for any help -- View this message in context: http://www.nabble.com/Brand-new-to-python-have-simple-problem-tp21325502p21325502.html Sent from the Python - tutor mailing list archive at Nabble.com. From iamscifius at yahoo.com Wed Jan 7 07:39:38 2009 From: iamscifius at yahoo.com (Michael Lam) Date: Tue, 6 Jan 2009 22:39:38 -0800 (PST) Subject: [Tutor] Opening a window to fit an image Message-ID: <708336.86242.qm@web111316.mail.gq1.yahoo.com> I got a similar problem, except that calling it twice wouldn't work for me. I tried looking everywhere and I seemed to be doing everything exactly like other people..... After fiddling around, I got this order: pygame.init() pygame.display.set_icon(pygame.image.load("image.bmp")) window = pygame.display.set_mode((640, 480 pygame.display.set_caption('Caption') Something wrong with using Surface.convert() as I originally used a load_image() function that did that. Michael From kent37 at tds.net Wed Jan 7 12:32:01 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 7 Jan 2009 06:32:01 -0500 Subject: [Tutor] Interactive programming. In-Reply-To: <496483CD.3040806@tue.nl> References: <4963AD10.4060003@socal.rr.com> <4963B3FD.1010504@khine.net> <4963C8B5.6070600@socal.rr.com> <496483CD.3040806@tue.nl> Message-ID: <1c2a2c590901070332o5807c4d3pffee564834ffb2bf@mail.gmail.com> On Wed, Jan 7, 2009 at 5:28 AM, A.T.Hofkamp wrote: > WM. wrote: >> >> Norman Khine wrote: >>> >>> >>> i = 5 >>> >>> j = 7 >>> >>> if i <= j: >>> ... print 'nudge', 'nudge' >>> ... else: >>> ... print 'whatever' >>> ... >>> nudge nudge >>> >>> > >> Yes, I understand how your program works. What I do not understand is how >> you got it. My program came out in IDLE as you see it. No ..., different >> indentation, an error message before I could add the else alternative. >> (Which, as a Pythonista, one should know, is "Wink-wink".) > > In IDLE in the window with the ">>>" prompt: > > After the colon at the 'if' line, you press ENTER (ie you tell Python 'the > line has ended here'). > The interpreter then supplies the "..." to denote that you are entering a > multi-line statement. No, IDLE does not supply the ..., that is the source of the confusion. If you use the interpreter directly from a command/terminal window it will supply the ... continuation prompt but the IDLE shell will not. Kent From KLegodi at csir.co.za Wed Jan 7 12:31:52 2009 From: KLegodi at csir.co.za (Kgotlelelo Legodi) Date: Wed, 07 Jan 2009 13:31:52 +0200 Subject: [Tutor] shooting method in python code Message-ID: <4964AEC8020000400002267D@pta-emo.csir.co.za> good day I just started using python and i want to know how can i solve a boundary value problem for ordinary differential equations using shooting method in python.use the general equation to demonstrate the python code. Thank you Kgotlelelo Legodi Natural Resources and the Environment CSIR 012 841 3402 (Tel) 012 841 4322 (Fax) 072 344 3846 (Cell) KLegod at csir.co.za -- This message is subject to the CSIR's copyright terms and conditions, e-mail legal notice, and implemented Open Document Format (ODF) standard. The full disclaimer details can be found at http://www.csir.co.za/disclaimer.html. This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. MailScanner thanks Transtec Computers for their support. From a.t.hofkamp at tue.nl Wed Jan 7 12:46:07 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Wed, 07 Jan 2009 12:46:07 +0100 Subject: [Tutor] linked list with cycle structure In-Reply-To: References: Message-ID: <496495FF.9050509@tue.nl> David Hl??ik wrote: > Hello guys, > > I have a linked list where *number of elements is unlimited* and > **last element points on random (can be first, last, in middle , > anywhere) element within linked list** - this is important . My goals > is to create an architecture /scheme for **algoritmus which will count > total number of elements** of such linked list. > Yes , maybe it sounds strange, but we need to implement this and i > would be very gladfull for your toughts. Python supplies a list data structure for you, so in 'normal' Python, you wouldn't bother with linked lists and all the assoicated problems. However, if you really want: Make a class for a list-element, with a next/prev variable (if you have a double-linked list). Instantiate as many objects as you like from that class, and let the next/prev variables from one object refer to other objects that you instantiated. (Python doesn't care where a variable refers to.) For the NULL value you can use None. Sincerely, Albert From andreengels at gmail.com Wed Jan 7 12:48:09 2009 From: andreengels at gmail.com (Andre Engels) Date: Wed, 7 Jan 2009 12:48:09 +0100 Subject: [Tutor] Brand new to python have simple problem In-Reply-To: <21325502.post@talk.nabble.com> References: <21325502.post@talk.nabble.com> Message-ID: <6faf39c90901070348ide09b5fk83131f618abce10b@mail.gmail.com> On Wed, Jan 7, 2009 at 7:06 AM, mickth wrote: > > I'm brand new to python and every time i start to learn it i get the same > problem and end up giving up and moving on to another language. > > the print statement doesn't work in either the comand line or IDLE i get > this in IDLE: > SyntaxError: invalid syntax (, line 1) > > and just SyntaxError: invalid syntax in the command line. > > Even doing the hello world or doing simple sums. If I type "hello, world" i > get the right outcome but print "Hello world" i get the error. When i type > print it's purple in IDLE if that means anything. > > I've tried reinstalling python and tried an earlier version with same > results. i'm running windows vista home prem 32bit > > I know i may seem an imbecile for posting such a simple thing but i'm > determined to learn it this time i've already learnt vb and C and want to > broaden out! Could you please give an exact copy (both your commands and the reactions, with copy and paste) of the idle session that leads to the error message? Here is what I get (working), you might be able to find from this where it goes wrong, but if not, please show what you get so we can look at it: >>> "Hello world" 'Hello world' >>> print "Hello world" Hello world >>> -- Andr? Engels, andreengels at gmail.com From kent37 at tds.net Wed Jan 7 12:48:32 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 7 Jan 2009 06:48:32 -0500 Subject: [Tutor] good day In-Reply-To: <496495FD0200004000022646@pta-emo.csir.co.za> References: <496495FD0200004000022646@pta-emo.csir.co.za> Message-ID: <1c2a2c590901070348n1e6877d6y3b5cf2960edfa1fc@mail.gmail.com> On Wed, Jan 7, 2009 at 4:46 AM, Kgotlelelo Legodi wrote: > good day > > I just started using python and i want to know how can i solve a boundary value problem for ordinary differential equations using shooting method in python.use the general equation to demonstrate the python code. Googling "python boundary value problem" finds these: http://books.google.com/books?id=WiDie-hev1kC&pg=PA295&lpg=PA295&dq=python+boundary+value+problem&source=web&ots=naWIAjsXpq&sig=lw9U0c-lQe1rUtlWv8W0cKXUGHI&hl=en&sa=X&oi=book_result&resnum=1&ct=result#PPA295,M1 http://lbolla.wordpress.com/2008/04/14/bvp/ http://www.scilab.org/doc/manual/Docu-html659.html http://projects.scipy.org/pipermail/scipy-user/2006-October/009483.html Kent From kent37 at tds.net Wed Jan 7 12:54:56 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 7 Jan 2009 06:54:56 -0500 Subject: [Tutor] SMTP Module Help In-Reply-To: <4963281D.9070009@gmail.com> References: <4963281D.9070009@gmail.com> Message-ID: <1c2a2c590901070354p7a519612j4ff12e6db1e44c08@mail.gmail.com> On Tue, Jan 6, 2009 at 4:45 AM, Marco Petersen wrote: > I'm using Python 2.5.4. I wanted to try out the SMTP module. I tried to send > an email through my Gmail account but it keeps saying that the connection > was refused. > > This is the code that I used : > > import smtplib > msg = 'Test' > > > server = smtplib.SMTP('smtp.gmail.com') >From the docs here http://mail.google.com/support/bin/answer.py?answer=77662 Google SMTP uses port 587, not the standard SMTP port 25. Try server = smtplib.SMTP('smtp.gmail.com', 587) Kent From a.t.hofkamp at tue.nl Wed Jan 7 12:56:28 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Wed, 07 Jan 2009 12:56:28 +0100 Subject: [Tutor] Interactive programming. In-Reply-To: <1c2a2c590901070332o5807c4d3pffee564834ffb2bf@mail.gmail.com> References: <4963AD10.4060003@socal.rr.com> <4963B3FD.1010504@khine.net> <4963C8B5.6070600@socal.rr.com> <496483CD.3040806@tue.nl> <1c2a2c590901070332o5807c4d3pffee564834ffb2bf@mail.gmail.com> Message-ID: <4964986C.9070309@tue.nl> Kent Johnson wrote: > On Wed, Jan 7, 2009 at 5:28 AM, A.T.Hofkamp wrote: >> WM. wrote: >>> Norman Khine wrote: >>>> >>> i = 5 >>>> >>> j = 7 >>>> >>> if i <= j: >>>> ... print 'nudge', 'nudge' >>>> ... else: >>>> ... print 'whatever' >>>> ... >>>> nudge nudge >>>> >>> >>> Yes, I understand how your program works. What I do not understand is how >>> you got it. My program came out in IDLE as you see it. No ..., different >>> indentation, an error message before I could add the else alternative. >>> (Which, as a Pythonista, one should know, is "Wink-wink".) >> In IDLE in the window with the ">>>" prompt: >> >> After the colon at the 'if' line, you press ENTER (ie you tell Python 'the >> line has ended here'). >> The interpreter then supplies the "..." to denote that you are entering a >> multi-line statement. > > No, IDLE does not supply the ..., that is the source of the confusion. > > If you use the interpreter directly from a command/terminal window it > will supply the ... continuation prompt but the IDLE shell will not. Thank you Kent, I didn't know that. The story stays the same, except that you don't get the "... " from Python. That means that the second line and further are all shifted 4 positions to the left, so you'd need to enter something like: >>> i = 5 >>> j = 7 >>> if i <= j: print 'nudge', 'nudge' else: print 'whatever' I agree that this is highly confusing. The best solution is probably to use the editor window instead, and save/run your programs from there. Sincerely, Albert From kent37 at tds.net Wed Jan 7 12:57:21 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 7 Jan 2009 06:57:21 -0500 Subject: [Tutor] linked list with cycle structure In-Reply-To: References: Message-ID: <1c2a2c590901070357s728c7b09ydabbd6fc41bf79d5@mail.gmail.com> On Wed, Jan 7, 2009 at 5:59 AM, David Hl??ik wrote: > Hello guys, > > I have a linked list where *number of elements is unlimited* and > **last element points on random (can be first, last, in middle , > anywhere) element within linked list** - this is important . My goals > is to create an architecture /scheme for **algoritmus which will count > total number of elements** of such linked list. So the list is effectively endless because it has a cycle? You could walk the list, adding elements (or their ids) to a set, stopping when you get to an element that is in the set already. Then the size of the set is the size of the list. Kent From kent37 at tds.net Wed Jan 7 13:00:33 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 7 Jan 2009 07:00:33 -0500 Subject: [Tutor] Brand new to python have simple problem In-Reply-To: <21325502.post@talk.nabble.com> References: <21325502.post@talk.nabble.com> Message-ID: <1c2a2c590901070400n294205fbg9872504eb83387cf@mail.gmail.com> On Wed, Jan 7, 2009 at 1:06 AM, mickth wrote: > > I'm brand new to python and every time i start to learn it i get the same > problem and end up giving up and moving on to another language. > > the print statement doesn't work in either the comand line or IDLE i get > this in IDLE: > SyntaxError: invalid syntax (, line 1) > > and just SyntaxError: invalid syntax in the command line. > > Even doing the hello world or doing simple sums. If I type "hello, world" i > get the right outcome but print "Hello world" i get the error. When i type > print it's purple in IDLE if that means anything. What version of Python are you using? In Python 3.0, print is a function, not a statement, so you need parentheses: print("Hello world") Most Python books and tutorials are written for Python 2.x. Make sure your references match the Python version you are using, there are significant changes in 3.0. Kent From wormwood_3 at yahoo.com Wed Jan 7 13:57:29 2009 From: wormwood_3 at yahoo.com (wormwood_3) Date: Wed, 7 Jan 2009 04:57:29 -0800 (PST) Subject: [Tutor] Getting multi-line input from user References: <769354.18027.qm@web110814.mail.gq1.yahoo.com><4964206A.7060500@gmail.com><594795.97475.qm@web110807.mail.gq1.yahoo.com> <6faf39c90901062219o66cfd382p7b3c00199a1addd3@mail.gmail.com> Message-ID: <585915.34965.qm@web110808.mail.gq1.yahoo.com> Joining with newline works perfectly. Thanks everyone! _______________________ Samuel Huckins Homepage - http://samuelhuckins.com Tech blog - http://dancingpenguinsoflight.com/ Photos - http://www.flickr.com/photos/samuelhuckins/ AIM - samushack | Gtalk - samushack | Skype - shuckins ________________________________ From: Alan Gauld To: tutor at python.org Sent: Wednesday, January 7, 2009 3:58:18 AM Subject: Re: [Tutor] Getting multi-line input from user "Andre Engels" wrote > The newline character is written \n in Python, so if you replace > > ' '.join(user_input) > > by > > '\n'.join(user_input) Yep, that's better than my suggestion of adding the \n at append time. :-) Alan G. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjampman at gmail.com Wed Jan 7 15:47:25 2009 From: tjampman at gmail.com (Ole Henning Jensen) Date: Wed, 07 Jan 2009 15:47:25 +0100 Subject: [Tutor] SMTP Module Help In-Reply-To: <4963281D.9070009@gmail.com> References: <4963281D.9070009@gmail.com> Message-ID: <4964C07D.3050607@gmail.com> Marco Petersen wrote: > I'm using Python 2.5.4. I wanted to try out the SMTP module. I tried to > send an email through my Gmail account but it keeps saying that the > connection was refused. > > This is the code that I used : > > import smtplib > msg = 'Test' > > > server = smtplib.SMTP('smtp.gmail.com') > server.set_debuglevel(1) > server.ehlo() > server.starttls() > server.ehlo() > server.login('marco.m.petersen at gmail.com', 'password') > server.sendmail('marco.m.petersen at gmail.com', > 'marcoleepetersen at gmail.com', msg) > server.close() > > This error message keeps coming up: > > > Traceback (most recent call last): > File "C:/Python25/send_mail.py", line 5, in > server = smtplib.SMTP('smtp.gmail.com') > File "C:\Python25\Lib\smtplib.py", line 244, in __init__ > (code, msg) = self.connect(host, port) > File "C:\Python25\Lib\smtplib.py", line 310, in connect > raise socket.error, msg > error: (10061, 'Connection refused') > > > Can anyone help me with this? > I must admit that I know nothing of the SMTP module, but I do know that with gmail you need to use an SSL secure connection on port 995. I doesn't seem to be aplied in your script as far as I can tell. Best Regards Ole From alpanachaturvedi at yahoo.com Wed Jan 7 16:14:43 2009 From: alpanachaturvedi at yahoo.com (CHATURVEDI ALPANA) Date: Wed, 7 Jan 2009 07:14:43 -0800 (PST) Subject: [Tutor] New to tkSnack In-Reply-To: Message-ID: <418961.90915.qm@web33607.mail.mud.yahoo.com> Hi All, I am very new to tkSnack. Trying to understand it. Please help me out. I thought of a very simple scenario. I would like to play a audio from line-in and then check if the audio is present. If there is no audio for 20 seconds then i need to raise an error. Is it possible to do this with tkSnack?If yes, then how can we do it? Regards, Alpana From damontimm at gmail.com Wed Jan 7 16:48:36 2009 From: damontimm at gmail.com (Damon Timm) Date: Wed, 7 Jan 2009 10:48:36 -0500 Subject: [Tutor] SMTP Module Help In-Reply-To: <4963281D.9070009@gmail.com> References: <4963281D.9070009@gmail.com> Message-ID: <262679b50901070748r4c27e6fco4ac15ee4f20c5e88@mail.gmail.com> On 1/6/09, Marco Petersen wrote: > I'm using Python 2.5.4. I wanted to try out the SMTP module. I tried to send > an email through my Gmail account but it keeps saying that the connection > was refused. I used this example to get emailing from python through gmail smtp to work: http://codecomments.wordpress.com/2008/01/04/python-gmail-smtp-example/ Note, there are a couple errors in the code that prevent it from working out-of-the-box ... however, if you read the comments they get worked out. Also, I think I would echo what the other folks mentioned here, is that you probably need to specify the port (587) as in: server = smtplib.SMTP('smtp.gmail.com', 587) Damon > > This is the code that I used : > > import smtplib > msg = 'Test' > > > server = smtplib.SMTP('smtp.gmail.com') > server.set_debuglevel(1) > server.ehlo() > server.starttls() > server.ehlo() > server.login('marco.m.petersen at gmail.com', 'password') > server.sendmail('marco.m.petersen at gmail.com', > 'marcoleepetersen at gmail.com', msg) > server.close() > > This error message keeps coming up: > > > Traceback (most recent call last): > File "C:/Python25/send_mail.py", line 5, in > server = smtplib.SMTP('smtp.gmail.com') > File "C:\Python25\Lib\smtplib.py", line 244, in __init__ > (code, msg) = self.connect(host, port) > File "C:\Python25\Lib\smtplib.py", line 310, in connect > raise socket.error, msg > error: (10061, 'Connection refused') > > > Can anyone help me with this? > > Thanks. > > -Marco > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From cbabcock at asciiking.com Wed Jan 7 17:17:47 2009 From: cbabcock at asciiking.com (Chris Babcock) Date: Wed, 7 Jan 2009 09:17:47 -0700 Subject: [Tutor] SMTP Module Help In-Reply-To: <4964C07D.3050607@gmail.com> References: <4963281D.9070009@gmail.com> <4964C07D.3050607@gmail.com> Message-ID: <20090107091747.774d1c3c@mail.asciiking.com> On Wed, 07 Jan 2009 15:47:25 +0100 Ole Henning Jensen wrote: > Marco Petersen wrote: > > I'm using Python 2.5.4. I wanted to try out the SMTP module. I > > tried to send an email through my Gmail account but it keeps saying > > that the connection was refused. > > error: (10061, 'Connection refused') > > > > > > Can anyone help me with this? > > > > I must admit that I know nothing of the SMTP module, but I do know > that with gmail you need to use an SSL secure connection on port 995. Yes, 995 is the port for POPS. For inbound mail, you probably want to use IMAPS on port 993. The original question is about SMTP, however. Google is offering SMTP submission over TLS on ports 465 and 587. Port 465 was defined as SMTP over SSL in some reference works, but the IETF still has it listed for a router protocol. Port 587 has been reserved for mail submission. More importantly for home users, your ISP should NOT block port 587 (RFC 4409). Best, Chris -- Thank you everyone! USAK is live on its new connection. So far you have given \$198 towards next quarter. To make a donation, use this link (opens on PayPal): http://tinyurl.com/USAK2009 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 489 bytes Desc: not available URL: From inthefridge at gmail.com Wed Jan 7 17:42:09 2009 From: inthefridge at gmail.com (Spencer Parker) Date: Wed, 7 Jan 2009 09:42:09 -0700 Subject: [Tutor] df type function in python Message-ID: I am looking for a function in python that would operate similar to df. I would use df, but I am unable to parse the data that it gives me from there. If it would give me a single line I could then split it out if I needed to, but I can't see how to actually do that. What I am trying to do is get some information on a drive I have mounted. I have a disk image that I have mounted on temp folder that I need to see how much total pace it is taking up. It gives me a more accurate representation of my xen disk images that just an ls -sk or something on the file. -- Spencer Parker -------------- next part -------------- An HTML attachment was scrubbed... URL: From wferguson1 at socal.rr.com Wed Jan 7 17:46:51 2009 From: wferguson1 at socal.rr.com (WM.) Date: Wed, 07 Jan 2009 08:46:51 -0800 Subject: [Tutor] Interactive programming. In-Reply-To: <4964986C.9070309@tue.nl> References: <4963AD10.4060003@socal.rr.com> <4963B3FD.1010504@khine.net> <4963C8B5.6070600@socal.rr.com> <496483CD.3040806@tue.nl> <1c2a2c590901070332o5807c4d3pffee564834ffb2bf@mail.gmail.com> <4964986C.9070309@tue.nl> Message-ID: <4964DC7B.6060703@socal.rr.com> IDLE 2.6 >>> i = 1 >>> j = 11 >>> if j > 1: print j else: SyntaxError: invalid syntax >>> I am getting a little dizzy here. I know about text editor, code, save, F5. Many tutorials say that it is funner and faster to test an idea 'interactively', using IDLE. Nothing is said about fiddling the output. In the above bit the 'else' is in the wrong place because IDLE or PYTHON terminated the script. I hate to be a bore here, but if the mechanics of the program are not as they are said to be in the tutorials, how am I to proceed? From rabidpoobear at gmail.com Wed Jan 7 17:58:03 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 7 Jan 2009 10:58:03 -0600 Subject: [Tutor] good day In-Reply-To: <4964856B.5050005@tue.nl> References: <496495FD0200004000022646@pta-emo.csir.co.za> <4964856B.5050005@tue.nl> Message-ID: On Wed, Jan 7, 2009 at 4:35 AM, A.T.Hofkamp wrote: > Kgotlelelo Legodi wrote: >> >> good day >> >> I just started using python and i want to know how can i solve a boundary > > value problem for ordinary differential equations using shooting method in > python.use the general equation to demonstrate the python code. > > > I have no background in numeric calculations, but for starters, you may want > to investigate the numpy and/or scipy Python packages. Google will probably > also give you good starting points of existing numeric code/libraries. > > > As for actually writing the program, I am afraid you'll have to do that > yourself. > Also, this sounds a lot like you just copied and pasted it from a homework assignment. We're not going to be able to provide you with code samples in that case, but you're welcome to ask more questions and post about any problems you run into. From kent37 at tds.net Wed Jan 7 18:08:17 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 7 Jan 2009 12:08:17 -0500 Subject: [Tutor] Interactive programming. In-Reply-To: <4964DC7B.6060703@socal.rr.com> References: <4963AD10.4060003@socal.rr.com> <4963B3FD.1010504@khine.net> <4963C8B5.6070600@socal.rr.com> <496483CD.3040806@tue.nl> <1c2a2c590901070332o5807c4d3pffee564834ffb2bf@mail.gmail.com> <4964986C.9070309@tue.nl> <4964DC7B.6060703@socal.rr.com> Message-ID: <1c2a2c590901070908s493fe05dyd0e04e75c29ad4cf@mail.gmail.com> On Wed, Jan 7, 2009 at 11:46 AM, WM. wrote: > IDLE 2.6 >>>> i = 1 >>>> j = 11 >>>> if j > 1: > print j > else: > > SyntaxError: invalid syntax >>>> > > I am getting a little dizzy here. > > I know about text editor, code, save, F5. > > Many tutorials say that it is funner and faster to test an idea > 'interactively', using IDLE. Nothing is said about fiddling the output. > > In the above bit the 'else' is in the wrong place because IDLE or PYTHON > terminated the script. You have to backspace before typing 'else:' to remove the (automatic) block indentation. IDLE auto-indents after the 'if:' and it will continue to indent each line until you tell it to stop by backspacing over the indent. Kent From edwin_boyette at yahoo.com Wed Jan 7 18:13:54 2009 From: edwin_boyette at yahoo.com (Edwin Boyette) Date: Wed, 7 Jan 2009 09:13:54 -0800 (PST) Subject: [Tutor] Interactive programming. Message-ID: <128547.28733.qm@web53703.mail.re2.yahoo.com> --- On Wed, 1/7/09, WM. wrote: From: WM. Subject: Re: [Tutor] Interactive programming. To: "A.T.Hofkamp" Cc: tutor at python.org Date: Wednesday, January 7, 2009, 11:46 AM IDLE 2.6 >>> i = 1 >>> j = 11 >>> if? j > 1: ??? print j ??? else: ??? ??? SyntaxError: invalid syntax >>> I am getting a little dizzy here. I know about text editor, code, save, F5. Many tutorials say that it is funner and faster to test an idea 'interactively', using IDLE.? Nothing is said about fiddling the output. In the above bit the 'else' is in the wrong place because IDLE or PYTHON terminated the script. I hate to be a bore here, but if the mechanics of the program are not as they are said to be in the tutorials, how am I to proceed? _______________________________________________ Tutor maillist? -? Tutor at python.org http://mail.python.org/mailman/listinfo/tutor ? ? You could wrapt it all up in a function and then call the function in idle. ? ? >>> def nudge_nudge(): ?i = 5 ?j = 7 ?if i <= j: ??print "nudge","nudge" ?else: ??print "whatever" nudge_nudge() -------------- next part -------------- An HTML attachment was scrubbed... URL: From inthefridge at gmail.com Wed Jan 7 19:08:52 2009 From: inthefridge at gmail.com (Spencer Parker) Date: Wed, 7 Jan 2009 11:08:52 -0700 Subject: [Tutor] df type function in python In-Reply-To: <4964EE33.6010600@sjsears.com> References: <4964EE33.6010600@sjsears.com> Message-ID: Is there anyway to get rid of the header information? I just want the output that it gives me for the device. On Wed, Jan 7, 2009 at 11:02 AM, Stuart Sears wrote: > On 07/01/09 16:42, Spencer Parker wrote: > >> I am looking for a function in python that would operate similar to df. >> I would use df, but I am unable to parse the data that it gives me >> from there. If it would give me a single line I could then split it out >> if I needed to, but I can't see how to actually do that. What I am >> trying to do is get some information on a drive I have mounted. I have a >> disk image that I have mounted on temp folder that I need to see how >> much total pace it is taking up. It gives me a more accurate >> representation of my xen disk images that just an ls -sk or something on >> the file. >> > > Which version of df do you have? Which OS is this on? > > If you want one line per device/mountpoint, df -P will do so on linux > systems nowadays. I have no idea whether any of this has been ported across > to other *NIX systems. > > Regards, > > Stuart > -- > Stuart Sears RHCA etc. > "It's today!" said Piglet. > "My favourite day," said Pooh. > -- Spencer Parker -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Jan 7 19:33:40 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 7 Jan 2009 13:33:40 -0500 Subject: [Tutor] df type function in python In-Reply-To: References: <4964EE33.6010600@sjsears.com> Message-ID: <1c2a2c590901071033q39bb61eg65d69eed5bd5a543@mail.gmail.com> On Wed, Jan 7, 2009 at 1:08 PM, Spencer Parker wrote: > Is there anyway to get rid of the header information? I just want the > output that it gives me for the device. If you know how to get the output of df into Python (e.g. with the subprocess module or a pipe) then you can use the str.splitlines() method to divide it into lines and pick out the line you want. Kent From inthefridge at gmail.com Wed Jan 7 19:36:53 2009 From: inthefridge at gmail.com (Spencer Parker) Date: Wed, 7 Jan 2009 11:36:53 -0700 Subject: [Tutor] df type function in python In-Reply-To: <1c2a2c590901071033q39bb61eg65d69eed5bd5a543@mail.gmail.com> References: <4964EE33.6010600@sjsears.com> <1c2a2c590901071033q39bb61eg65d69eed5bd5a543@mail.gmail.com> Message-ID: What I did was just grep for anything starting with "/" It then just outputs it to a single line now...and I can split it as needed. Thanks again!!1 On Wed, Jan 7, 2009 at 11:33 AM, Kent Johnson wrote: > On Wed, Jan 7, 2009 at 1:08 PM, Spencer Parker > wrote: > > Is there anyway to get rid of the header information? I just want the > > output that it gives me for the device. > > If you know how to get the output of df into Python (e.g. with the > subprocess module or a pipe) then you can use the str.splitlines() > method to divide it into lines and pick out the line you want. > > Kent > -- Spencer Parker -------------- next part -------------- An HTML attachment was scrubbed... URL: From stuart at sjsears.com Wed Jan 7 19:30:54 2009 From: stuart at sjsears.com (Stuart Sears) Date: Wed, 07 Jan 2009 18:30:54 +0000 Subject: [Tutor] df type function in python In-Reply-To: References: Message-ID: <4964F4DE.9050105@sjsears.com> Redirecting to the list as I seem to have replied off-list rather inadvertently... On 07/01/09 16:42, Spencer Parker wrote: > I am looking for a function in python that would operate similar to df. > I would use df, but I am unable to parse the data that it gives me > from there. If it would give me a single line I could then split it out > if I needed to, but I can't see how to actually do that. What I am > trying to do is get some information on a drive I have mounted. I have a > disk image that I have mounted on temp folder that I need to see how > much total pace it is taking up. It gives me a more accurate > representation of my xen disk images that just an ls -sk or something on > the file. Which version of df do you have? Which OS is this on? If you want one line per device/mountpoint, df -P will do so on linux systems nowadays. I have no idea whether any of this has been ported across to other *NIX systems. Regards, Stuart -- Stuart Sears RHCA etc. "It's today!" said Piglet. "My favourite day," said Pooh. From stuart at sjsears.com Wed Jan 7 19:27:56 2009 From: stuart at sjsears.com (Stuart Sears) Date: Wed, 07 Jan 2009 18:27:56 +0000 Subject: [Tutor] df type function in python In-Reply-To: References: <4964EE33.6010600@sjsears.com> Message-ID: <4964F42C.1070105@sjsears.com> On 07/01/09 18:08, Spencer Parker wrote: > Is there anyway to get rid of the header information? I just want > the output that it gives me for the device. parse the output and junk the first line? I'm no subprocess expert, but a bit of playing about suggests this would work: from subprocess import Popen, PIPE df = Popen('df -P', shell=True, stdout=PIPE) no_header = df.stdout.readlines()[1:] I'm sure there are more elegant ways to do this, but it does work. tuning the df -P command to only give you the device your are interested in should reduce the output a little more. Regards, Stuart ps there's need to reply to me directly, I'm subscribed to the list, albeit mostly to cower at the feet of those who inhabit it :) -- Stuart Sears RHCA etc. "It's today!" said Piglet. "My favourite day," said Pooh. From rschroev_nospam_ml at fastmail.fm Wed Jan 7 20:51:02 2009 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Wed, 07 Jan 2009 20:51:02 +0100 Subject: [Tutor] df type function in python In-Reply-To: References: Message-ID: Spencer Parker schreef: > I am looking for a function in python that would operate similar to df. > I would use df, but I am unable to parse the data that it gives me from > there. If it would give me a single line I could then split it out if I > needed to, but I can't see how to actually do that. What I am trying to > do is get some information on a drive I have mounted. I have a disk > image that I have mounted on temp folder that I need to see how much > total pace it is taking up. It gives me a more accurate representation > of my xen disk images that just an ls -sk or something on the file. Some time ago I wrote something like that for a script of mine: import subprocess def df(filesystem): """Report disk usage. Return a dictionary with total, used, available. Sizes are reported in blocks of 1024 bytes.""" output = subprocess.Popen( ['/bin/df', '-B 1024', filesystem], stdout=subprocess.PIPE).communicate()[0] lines = output.split('\n') fs, blocks_total, blocks_used, blocks_available, used, mount = lines[1].split() blocks_total = int(blocks_total) blocks_used = int(blocks_used) blocks_available = int(blocks_available) return dict( total=blocks_total, used=blocks_used, available=blocks_available) I use from a cronjob in a script that monitors the disk usage and sends me a mail if the disk gets too full. -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From ksarikhani at gmail.com Wed Jan 7 22:04:28 2009 From: ksarikhani at gmail.com (Kayvan Sarikhani) Date: Wed, 7 Jan 2009 16:04:28 -0500 Subject: [Tutor] Opsware Global Shell Scripting Message-ID: Hi there...I'm new to Python scripting, with maybe 3 days under my belt thus far. Besides the occasional shell script, the last time I ever touched a programming language was probably at least 12 years ago, if that gives you any indication of my experience. :) I don't know if this is the proper place to ask, but I've run into the problem below. Right now I'm beginning to work within the Opsware Global Shell, which if you're unfamiliar with it, basically is exactly what it sounds like...the goal is to launch a script which changes directories to a list of servers, prints the server name, remotes into managed virtual servers, checks the date, and outputs this into a file. I do have a bash script as follows, which does the job: #!/bin/bash # # This script checks the dates on all managed systems. OUTFILE="/home/ksarikhani/public/bin/timecheck.txt" rm -f \$OUTFILE cd "/opsw/Server/@/" for SERVER_NAME in * do echo ---- \$SERVER_NAME echo ---- \$SERVER_NAME >> \$OUTFILE rosh -n \$SERVER_NAME -l \$LOGNAME \ "date" >> \$OUTFILE done # Last line in date.sh. Even though the above does what I need it to do, I'd REALLY like to determine the equivalent in Python...I've tried several different methods, but about as far as I get is printing the server name. This is what I've cobbled together so far. #!/usr/bin/python import os, sys sys.stdout = open('timecheck.txt','w') for servername in os.listdir('/opsw/Server/@'): print '---', servername os.system('rosh -n \$SERVER_NAME -l \$LOGNAME') os.system('date') sys.stdout.close() The problem is this...for logging into systems via the global shell, one has to change directories to the one with the list of all managed servers (or specify the path for each one), and then launch a "rosh -n -l " to be able to get into it. However, when I launch the script, what happens is the following message: *rosh: Username must be specified with -l or via path* And this is a continual loop that I can't break. This is of course not a Python error, but as you might guess from looking at the script, the whole \$SERVER_NAME piece is probably wrong. I thought maybe I could do something like this... *os.system('rosh -n', servername, '-l \$LOGNAME')* But of course os.system allows exactly one argument, and not three. This is where I'm stuck, and I've been digging into the books and examples and forums and just not quite sure what to look for. I would have liked to have completed the script without asking for help, but nothing quite seems to fit what I'm doing. Any suggestions or guidance would be highly appreciated. Thanks! K -------------- next part -------------- An HTML attachment was scrubbed... URL: From wferguson1 at socal.rr.com Wed Jan 7 22:45:35 2009 From: wferguson1 at socal.rr.com (WM.) Date: Wed, 07 Jan 2009 13:45:35 -0800 Subject: [Tutor] Interactive programming. In-Reply-To: <4963B3FD.1010504@khine.net> References: <4963AD10.4060003@socal.rr.com> <4963B3FD.1010504@khine.net> Message-ID: <4965227F.608@socal.rr.com> Norman Khine wrote: > >>> i = 5 > >>> j = 7 > >>> if i <= j: > ... print 'nudge', 'nudge' > ... else: > ... print 'whatever' > ... > nudge nudge The above is just what the tutorials said would happen. Can anyone give me a step-by-step in IDLE 2.6 that would make this happen? From sander.sweers at gmail.com Wed Jan 7 23:09:09 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Wed, 7 Jan 2009 23:09:09 +0100 Subject: [Tutor] Opsware Global Shell Scripting In-Reply-To: References: Message-ID: On Wed, Jan 7, 2009 at 22:04, Kayvan Sarikhani wrote: > #!/usr/bin/python > import os, sys > sys.stdout = open('timecheck.txt','w') > for servername in os.listdir('/opsw/Server/@'): > print '---', servername > os.system('rosh -n \$SERVER_NAME -l \$LOGNAME') > os.system('date') > sys.stdout.close() > > The problem is this...for logging into systems via the global shell, one has > to change directories to the one with the list of all managed servers (or > specify the path for each one), and then launch a "rosh -n -l > " to be able to get into it. > > This is of course not a Python error, but as you might guess from looking at > the script, the whole \$SERVER_NAME piece is probably wrong. Indeed the variables are wrong > I thought maybe > I could do something like this... > > os.system('rosh -n', servername, '-l \$LOGNAME') > > But of course os.system allows exactly one argument, and not three. Almost, look at the below session in idle. The %s are replaced by the variables servername and logname. See string formatting [1] for more info. >>> servername = 'testserver' >>> logname = 'logname' >>> print 'rosh -m %s -l %s' % (servername, logname) rosh -m testserver -l logname So you need to use something like below in your loop. roshCommand = 'rosh -m %s -l %s' % (servername, logname) os.system(roshCommand) I do not see the servername variable being assigned a value in your script so the above will fail. I assume it will be something like logname = '/var/log/somelogfile' You might want to look at the subprocess module as this gives you a lot more control but is also more complicated. Greets Sander [1] http://docs.python.org/library/stdtypes.html#string-formatting-operations From david at hlacik.eu Wed Jan 7 23:13:57 2009 From: david at hlacik.eu (=?ISO-8859-2?Q?David_Hl=E1=E8ik?=) Date: Wed, 7 Jan 2009 23:13:57 +0100 Subject: [Tutor] linked list with cycle structure In-Reply-To: <6sjok8F6dqciU1@mid.uni-berlin.de> References: <6sjok8F6dqciU1@mid.uni-berlin.de> Message-ID: Hi, so okay, i will create a helping set, where i will be adding elements ID, when element ID will be allready in my helping set i will stop and count number of elements in helping set. This is how long my cycled linked list is. But what if i have another condition , and that is *i can use only helping memory with constant size* ? This means i am not able to create any set and adding elements there. I need to have a constant size variables . This is complication a complication for me. Thanks in advance! David On Wed, Jan 7, 2009 at 2:22 PM, Diez B. Roggisch wrote: > > David Hl??ik wrote: > > > dictionary with cycle structure > > > > Hello guys, > > > > I have a linked list where *number of elements is unlimited* and > > **last element points on random (can be first, last, in middle , > > anywhere) element within linked list** - this is important . My goals > > is to create an architecture /scheme for **algoritmus which will count > > total number of elements** of such linked list. > > Yes , maybe it sounds strange, but we need to implement this and i > > would be very gladfull for your toughts. > > Time for homework again? Last time sorting in O(n), now this. How about you > try something yourself and show us the results - then we might comment on > enhancements or problems. > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list From sander.sweers at gmail.com Wed Jan 7 23:21:53 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Wed, 7 Jan 2009 23:21:53 +0100 Subject: [Tutor] Interactive programming. In-Reply-To: <4965227F.608@socal.rr.com> References: <4963AD10.4060003@socal.rr.com> <4963B3FD.1010504@khine.net> <4965227F.608@socal.rr.com> Message-ID: On Wed, Jan 7, 2009 at 22:45, WM. wrote: > Norman Khine wrote: >> >> >>> i = 5 >> >>> j = 7 >> >>> if i <= j: >> ... print 'nudge', 'nudge' >> ... else: >> ... print 'whatever' >> ... >> nudge nudge > > The above is just what the tutorials said would happen. > Can anyone give me a step-by-step in IDLE 2.6 that would make this happen? The above is not from idle but from the interactive python command line. If you are on windows it is an entry in the python 2.6 start menu entry. Greets Sander From wferguson1 at socal.rr.com Wed Jan 7 23:36:07 2009 From: wferguson1 at socal.rr.com (WM.) Date: Wed, 07 Jan 2009 14:36:07 -0800 Subject: [Tutor] Interactive programming. In-Reply-To: References: <4963AD10.4060003@socal.rr.com> <4963B3FD.1010504@khine.net> <4965227F.608@socal.rr.com> Message-ID: <49652E57.8060000@socal.rr.com> IDLE 2.6 >>> i = 1 >>> if i > 1: print 'x' else: print 'y' y >>> Last post on this topic, I guess. I think that the script looks pretty lame, though. From kent37 at tds.net Wed Jan 7 23:37:46 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 7 Jan 2009 17:37:46 -0500 Subject: [Tutor] Interactive programming. In-Reply-To: <4965227F.608@socal.rr.com> References: <4963AD10.4060003@socal.rr.com> <4963B3FD.1010504@khine.net> <4965227F.608@socal.rr.com> Message-ID: <1c2a2c590901071437w30a8e0f4obaa0a245bcc1de89@mail.gmail.com> On Wed, Jan 7, 2009 at 4:45 PM, WM. wrote: > Norman Khine wrote: >> >> >>> i = 5 >> >>> j = 7 >> >>> if i <= j: >> ... print 'nudge', 'nudge' >> ... else: >> ... print 'whatever' >> ... >> nudge nudge > > The above is just what the tutorials said would happen. > Can anyone give me a step-by-step in IDLE 2.6 that would make this happen? Type these characters exactly into the IDLE shell window, where is the return or Enter key and is the backspace or delete key (the one next to the ]} key not the one in the numeric keypad): if i<=j:print 'nudge'else:print 'whatever' Kent From kent37 at tds.net Wed Jan 7 23:38:28 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 7 Jan 2009 17:38:28 -0500 Subject: [Tutor] Interactive programming. In-Reply-To: <49652E57.8060000@socal.rr.com> References: <4963AD10.4060003@socal.rr.com> <4963B3FD.1010504@khine.net> <4965227F.608@socal.rr.com> <49652E57.8060000@socal.rr.com> Message-ID: <1c2a2c590901071438s5a835bb3k5dae898d34222127@mail.gmail.com> On Wed, Jan 7, 2009 at 5:36 PM, WM. wrote: > IDLE 2.6 >>>> i = 1 >>>> if i > 1: > print 'x' > else: > print 'y' > > > y >>>> > Last post on this topic, I guess. > I think that the script looks pretty lame, though. It was always lame :-) but you got it to work... Kent From ksarikhani at gmail.com Wed Jan 7 23:50:12 2009 From: ksarikhani at gmail.com (Kayvan Sarikhani) Date: Wed, 7 Jan 2009 17:50:12 -0500 Subject: [Tutor] Opsware Global Shell Scripting In-Reply-To: <20090107225747.502df1d0@o> References: <20090107225747.502df1d0@o> Message-ID: On Wed, Jan 7, 2009 at 4:57 PM, spir wrote: > Le Wed, 7 Jan 2009 16:04:28 -0500, > "Kayvan Sarikhani" a ?crit : > > > #!/bin/bash > > # > > # This script checks the dates on all managed systems. > > OUTFILE="/home/ksarikhani/public/bin/timecheck.txt" > > rm -f \$OUTFILE > > cd "/opsw/Server/@/" > > for SERVER_NAME in * > > do > > echo ---- \$SERVER_NAME > > echo ---- \$SERVER_NAME >> \$OUTFILE > > rosh -n \$SERVER_NAME -l \$LOGNAME \ > > "date" >> \$OUTFILE > > done > > # Last line in date.sh. > > > #!/usr/bin/python > > import os, sys > > sys.stdout = open('timecheck.txt','w') > > for servername in os.listdir('/opsw/Server/@'): > > print '---', servername > > os.system('rosh -n \$SERVER_NAME -l \$LOGNAME') > > os.system('date') > > sys.stdout.close() > > > > The issue is, when comparing the bash script to the python one, that > \$SERVER_NAME makes sense only > for bash -- as well as \$LOGNAME that you properly changed. > > > *os.system('rosh -n', servername, '-l \$LOGNAME')* > > This goes on the right way. Actually, os.system's arg is a plain string. To > construct it out of > several substrings you have to use matching string operators (actually > methods). To be explicit: > > string_shell_command = 'rosh -n' + servername + '-l \$LOGNAME' > or > string_shell_command = 'rosh -n %s -l \$LOGNAME' %servername > and then: > os.system(string_shell_command) > > Than, I'm not fully sure this will be enough unless \$LOGNAME is an env > variable known by the > system (I don't know well linux yet). It seems to be, as it is not defined > in your bash script. > > Denis Ah, that makes sense...I didn't know we could devise our own commands in strings like that. That helps me quite a lot, actually. Thank you very much, Denis! For the record, \$LOGNAME works fine as a variable...it's a standard env variable in Linux to display the current user's username. There's other ways of getting it, but that seems to be the most exact from what I can gather. Thanks again, when I make some progress or complete it (hopefully), I'll post further. Kayvan PS - Sorry for the re-send, forgot to include the tutor list. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ksarikhani at gmail.com Wed Jan 7 23:51:13 2009 From: ksarikhani at gmail.com (Kayvan Sarikhani) Date: Wed, 7 Jan 2009 17:51:13 -0500 Subject: [Tutor] Opsware Global Shell Scripting In-Reply-To: References: Message-ID: On Wed, Jan 7, 2009 at 5:09 PM, Sander Sweers wrote: > On Wed, Jan 7, 2009 at 22:04, Kayvan Sarikhani > wrote: > > > > This is of course not a Python error, but as you might guess from looking > at > > the script, the whole \$SERVER_NAME piece is probably wrong. > > Indeed the variables are wrong > Right...I thought so, but wasn't sure if there was any kind of equivalent within Python...couldn't hurt to try. :) > Almost, look at the below session in idle. The %s are replaced by the > variables servername and logname. See string formatting [1] for more > info. > > >>> servername = 'testserver' > >>> logname = 'logname' > >>> print 'rosh -m %s -l %s' % (servername, logname) > rosh -m testserver -l logname > > So you need to use something like below in your loop. > > roshCommand = 'rosh -m %s -l %s' % (servername, logname) > > os.system(roshCommand) > > I do not see the servername variable being assigned a value in your > script so the above will fail. I assume it will be something like > > logname = '/var/log/somelogfile' > > You might want to look at the subprocess module as this gives you a > lot more control but is also more complicated. > > Greets > Sander > > [1] > http://docs.python.org/library/stdtypes.html#string-formatting-operations > Yes, it did fail...rosh needs the full path or the -n identifier to remote shell into the VM's, and you're right that it didn't find it. As for the \$LOGNAME variable, that piece works for identifying the username which is what I needed for that...it doesn't actually point to a log file or the like. If I misunderstood what you meant, my apologies. Thanks very much though, this is also a lot of help and definitely points me in the right direction. I'll certainly check out string formating and see where I can go from there. I did look at the subprocess module but I'm still not sure I understand it...seems to have a lot of options and is flexible, but I still need to examine how it's used. Thanks! Kayvan -------------- next part -------------- An HTML attachment was scrubbed... URL: From edwin_boyette at yahoo.com Thu Jan 8 00:13:17 2009 From: edwin_boyette at yahoo.com (Edwin Boyette) Date: Wed, 7 Jan 2009 15:13:17 -0800 (PST) Subject: [Tutor] Interactive programming. Message-ID: <499143.66868.qm@web53702.mail.re2.yahoo.com> Don't try to make interactive programming something its not. It's handy if you have something short to try out, want to evaluate a function at some value etc.? Don't?rage at the hammer for not being an allen wrench ---- get an allen wrench. --- On Wed, 1/7/09, Kent Johnson wrote: From: Kent Johnson Subject: Re: [Tutor] Interactive programming. To: "WM." Cc: "Sander Sweers" , tutor at python.org Date: Wednesday, January 7, 2009, 5:38 PM -----Inline Attachment Follows----- On Wed, Jan 7, 2009 at 5:36 PM, WM. wrote: > IDLE 2.6 >>>> i = 1 >>>> if i > 1: >? ? ? ? print 'x' > else: >? ? ? ? print 'y' > > > y >>>> > Last post on this topic, I guess. > I think that the script looks pretty lame, though. It was always lame :-) but you got it to work... Kent _______________________________________________ Tutor maillist? -? Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From damontimm at gmail.com Thu Jan 8 01:02:48 2009 From: damontimm at gmail.com (Damon Timm) Date: Wed, 7 Jan 2009 19:02:48 -0500 Subject: [Tutor] Can subprocess run functions ? Message-ID: <262679b50901071602p5c3c61c5iebf650244b78b1f@mail.gmail.com> Hi everyone - I was playing with subprocess (with some success, I might add) to implement threading in my script (audio conversion). My goal is to be able to spawn off threads to make use of my multiprocessor system (and speed up encoding). With your help, I was successful. Anyhow, subprocess is working -- but I wonder if there is a way I can send the entire *function* into its own subprocess ? Because, in my case, I want my function to: [a] convert files, [b] tag files, [c] do some other stuff to files. Steps [b] and [c] require step [a] to be complete ... but the minute I spawn off step [a] it acts like it is already done (even though it is still working) ... I was hoping they could all run in a single thread, one after another ... I tried just giving subprocess.Popen the function name (rather than the external program) but that didn't work; and I read through the docs over at python.org ... but I can't find my answer. With the code I have, I am not sure how to both wait for my subprocess to finish (in the function) and allow the multithreading bit to work together ... I have experimented myself but didn't really get anywhere. I commented in where I want to "do other stuff" before it finishes ... wonder if you can take a look and show me where I may try to head next? Thanks! ------------------ import time import subprocess totProcs = 2 #number of processes to spawn before waiting flacFiles = [["test.flac","test.mp3"],["test2.flac","test2.mp3"],\ ["test3.flac","test3.mp3"],["test4.flac","test4.mp3"],\ ["test5.flac","test5.mp3"],["test6.flac","test6.mp3"]] procs = [] def flac_to_mp3(flacfile,mp3file): print "beginning to process " + flacfile p = subprocess.Popen(["flac","--decode","--stdout","--silent",flacfile], stdout=subprocess.PIPE) p1 = subprocess.Popen(["lame","--silent","-",mp3file], stdin=p.stdout) # I want to do more stuff before this function ends, but need to wait for p1 to finish first; # and, at the same time, I need to "return" p1 so the while loop (below) works [I think] return p1 while flacFiles or procs: procs = [p for p in procs if p.poll() is None] while flacFiles and len(procs) < totProcs: file = flacFiles.pop(0) procs.append(flac_to_mp3(file[0],file[1])) time.sleep(1) From robert.kern at gmail.com Thu Jan 8 01:23:24 2009 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 07 Jan 2009 19:23:24 -0500 Subject: [Tutor] linked list with cycle structure In-Reply-To: References: <6sjok8F6dqciU1@mid.uni-berlin.de> Message-ID: Terry Reedy wrote: > David Hl??ik wrote: >> But what if i have another condition , and that is *i can use only >> helping memory with constant size* ? This means i am not able to >> create any set and adding elements there. I need to have a constant >> size variables . This is complication a complication for me. > > Interesting problem. If it is homework, there must be an answer. It's also an interview question I've seen reasonably often, particularly with that last complication. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From wescpy at gmail.com Thu Jan 8 01:36:38 2009 From: wescpy at gmail.com (wesley chun) Date: Wed, 7 Jan 2009 16:36:38 -0800 Subject: [Tutor] Can subprocess run functions ? In-Reply-To: <262679b50901071602p5c3c61c5iebf650244b78b1f@mail.gmail.com> References: <262679b50901071602p5c3c61c5iebf650244b78b1f@mail.gmail.com> Message-ID: <78b3a9580901071636v49dac9f2g3ee561634fe475bc@mail.gmail.com> > Anyhow, subprocess is working -- but I wonder if there is a way I can > send the entire *function* into its own subprocess ? this has been a highly-desired feature for quite awhile. starting in 2.6, you can use the new multiprocessing module (originally called pyprocessing): http://docs.python.org/library/multiprocessing.html there is a backport to 2.4 and 2.5 here: http://pypi.python.org/pypi/multiprocessing/2.6.0.2 there are similar packages called pypar and pprocess: http://datamining.anu.edu.au/~ole/pypar/ http://www.boddie.org.uk/python/pprocess.html hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From damontimm at gmail.com Thu Jan 8 01:43:56 2009 From: damontimm at gmail.com (Damon Timm) Date: Wed, 7 Jan 2009 19:43:56 -0500 Subject: [Tutor] Can subprocess run functions ? In-Reply-To: <78b3a9580901071636v49dac9f2g3ee561634fe475bc@mail.gmail.com> References: <262679b50901071602p5c3c61c5iebf650244b78b1f@mail.gmail.com> <78b3a9580901071636v49dac9f2g3ee561634fe475bc@mail.gmail.com> Message-ID: <262679b50901071643h335998ffm2508e0631be3a9aa@mail.gmail.com> On Wed, Jan 7, 2009 at 7:36 PM, wesley chun wrote: > this has been a highly-desired feature for quite awhile. > > starting in 2.6, you can use the new multiprocessing module > (originally called pyprocessing): > http://docs.python.org/library/multiprocessing.html > > there is a backport to 2.4 and 2.5 here: > http://pypi.python.org/pypi/multiprocessing/2.6.0.2 > > there are similar packages called pypar and pprocess: > http://datamining.anu.edu.au/~ole/pypar/ > http://www.boddie.org.uk/python/pprocess.html > > hope this helps! Thanks Wesley - it does! As is often the case, the minute I ask a question like this I have some anxiety that the answer must be right under my nose and I rush about the tubes of the internet searching for a clue ... I also found: http://chrisarndt.de/projects/threadpool/threadpool.py.html Since I have been doing a bit of reading since I started, I was able to download this "threadpool", import it, and it actually get it to work. Here is what I messily put together (using my first referenced script, as an example) ... I think I may stick with this for a while, since it seems well-thought out and, as far as I can tell, works! (No shame in "borrowing" ... though not as cool as making it up myself.) import subprocess import threadpool import os totProcs = 2 #number of processes to spawn before waiting flacFiles = ["test.flac","test2.flac","test3.flac","test4.flac","test5.flac","test6.flac"] def flac_to_mp3(flacfile): print "Processing: " + flacfile mp3file = flacfile.rsplit('.', 1)[0] + '.mp3' p = subprocess.Popen(["flac","--decode","--stdout","--silent",flacfile], stdout=subprocess.PIPE) p1 = subprocess.Popen(["lame","--silent","-",mp3file], stdin=p.stdout) p1.communicate() #Test file size so we know it is actually waiting until it has been created. size = os.path.getsize(mp3file) return str("File: " + mp3file + "* Size: " + str(size)) def print_result(request, result): print "* Result from request #%s: %r" % (request.requestID, result) pool = threadpool.ThreadPool(totProcs) convert = threadpool.makeRequests(flac_to_mp3,flacFiles,print_result) [pool.putRequest(req) for req in convert] pool.wait() print "All Done!" > -- wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2007,2001 > "Python Fundamentals", Prentice Hall, (c)2009 > http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com > From alan.gauld at btinternet.com Thu Jan 8 02:21:24 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 8 Jan 2009 01:21:24 -0000 Subject: [Tutor] Interactive programming. References: <499143.66868.qm@web53702.mail.re2.yahoo.com> Message-ID: "Edwin Boyette" wrote > Don't try to make interactive programming something its not. > It's handy if you have something short to try out, want to > evaluate a function at some value etc. > Don't rage at the hammer for not being an allen wrench But in this case it is a valid complaint. Almost every other IDE with an interactive prompt does pro[per indentation, IDLE is the exception. Yet IDLE is theone most beginners use first! I think this is a really serious bug in Idle and is one of the main reasons I always recommend beginners use Pythonwin or PyCrust or some other shell window. The Idle editor windows are fine but the shell window sucks! -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Thu Jan 8 02:37:27 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 8 Jan 2009 01:37:27 -0000 Subject: [Tutor] Opsware Global Shell Scripting References: <20090107225747.502df1d0@o> Message-ID: "Kayvan Sarikhani" wrote > For the record, \$LOGNAME works fine as a variable...it's a standard > env > variable in Linux to display the current user's username. In that case os.getenv('LOGNAME') should retrieve it for you HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk From artie.ziff at gmail.com Thu Jan 8 03:12:15 2009 From: artie.ziff at gmail.com (Artie Ziff) Date: Wed, 07 Jan 2009 18:12:15 -0800 Subject: [Tutor] simple array access Message-ID: <496560FF.2000201@gmail.com> Hello, I used python list comprehension to create a grid (list of lists) of Objects (instances of MyItem class). Can anyone make recommendations to achieve a simple access to the elements. My attempt at array access (like this: array[1,2] ) does not work. What am I overlooking? Thanks in advance! :) If anyone has time to show a better way to achieve same, then I am interested to learn! :) ### from pprint import * class MyItem: def __init__(self, value): self.data=value def __repr__(self): return 'MyItem(%s)' % (self.data) class Grid: def __init__(self, x, y, value): self.data = [[MyItem(float(value)) for i in range(x)] for j in range(y)] if __name__ == "__main__": grid = Grid(2, 3, 0.42) pprint(grid) pprint(grid.data) # next line fails to access array element pprint (grid.data[1,2]) # EOF # OUTPUT: <__main__.Grid instance at 0x7beb8> [[MyItem(0.42), MyItem(0.42)], [MyItem(0.42), MyItem(0.42)], [MyItem(0.42), MyItem(0.42)]] Traceback (most recent call last): File "multidim04.py", line 20, in pprint (grid.data[1,2]) TypeError: list indices must be integers Cheers, Art From jadrifter at gmail.com Thu Jan 8 03:24:51 2009 From: jadrifter at gmail.com (jadrifter) Date: Wed, 07 Jan 2009 18:24:51 -0800 Subject: [Tutor] simple array access In-Reply-To: <496560FF.2000201@gmail.com> References: <496560FF.2000201@gmail.com> Message-ID: <1231381491.6446.30.camel@ltop> On Wed, 2009-01-07 at 18:12 -0800, Artie Ziff wrote: > Hello, > > I used python list comprehension to create a grid (list of lists) of > Objects (instances of MyItem class). Can anyone make recommendations to > achieve a simple access to the elements. My attempt at array access > (like this: array[1,2] ) does not work. What am I overlooking? Thanks in > advance! :) > Hello, You might want to take a look at NumPy http://numpy.scipy.org/ John Purser From wescpy at gmail.com Thu Jan 8 03:45:13 2009 From: wescpy at gmail.com (wesley chun) Date: Wed, 7 Jan 2009 18:45:13 -0800 Subject: [Tutor] simple array access In-Reply-To: <496560FF.2000201@gmail.com> References: <496560FF.2000201@gmail.com> Message-ID: <78b3a9580901071845y3de4034aqcfd789eaf8030cd5@mail.gmail.com> > My attempt at array access (like this: array[1,2] ) does not work. What am > I overlooking? Thanks in advance! :) > : > pprint (grid.data[1,2]) is that really your name?!? you're famous! ;-) welcome to python! i'd try... pprint(grid.data[0][1]) ... as many languages start counting at 0 instead of 1, and you needed a quick syntax fix too. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com "Python Web Development with Django", Addison Wesley, (c) 2009 http://withdjango.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From s4027340 at student.uq.edu.au Thu Jan 8 03:41:10 2009 From: s4027340 at student.uq.edu.au (Mr Gerard Kelly) Date: Thu, 08 Jan 2009 12:41:10 +1000 Subject: [Tutor] variable number of inputs Message-ID: How can you make a function accept a variable number of inputs without any particular limit? Like when you define a function you usually go: def func(a,b,c,d,e) and if you want to give a default value for e you can use e=0 for example. But what if you want to be able to call the function and put in as many arguments as you want. Say it's a really simple function just adding them all together or something (I know sum does that, but I'm just thinking of a simple example). From bgailer at gmail.com Thu Jan 8 04:01:42 2009 From: bgailer at gmail.com (bob gailer) Date: Wed, 07 Jan 2009 22:01:42 -0500 Subject: [Tutor] variable number of inputs In-Reply-To: References: Message-ID: <49656C96.5070707@gmail.com> Mr Gerard Kelly wrote: > How can you make a function accept a variable number of inputs without > any particular limit? > > Like when you define a function you usually go: > > def func(a,b,c,d,e) > > and if you want to give a default value for e you can use e=0 for example. > > But what if you want to be able to call the function and put in as many > arguments as you want. Say it's a really simple function just adding > them all together or something (I know sum does that, but I'm just > thinking of a simple example). > def func(*a) # a will be a tuple of whatever arguments are passed in the call. -- Bob Gailer Chapel Hill NC 919-636-4239 From wescpy at gmail.com Thu Jan 8 04:22:50 2009 From: wescpy at gmail.com (wesley chun) Date: Wed, 7 Jan 2009 19:22:50 -0800 Subject: [Tutor] variable number of inputs In-Reply-To: <49656C96.5070707@gmail.com> References: <49656C96.5070707@gmail.com> Message-ID: <78b3a9580901071922s584aafcby12bcc5865dd37263@mail.gmail.com> On Wed, Jan 7, 2009 at 7:01 PM, bob gailer wrote: > Mr Gerard Kelly wrote: >> >> How can you make a function accept a variable number of inputs without >> any particular limit? >> : >> But what if you want to be able to call the function and put in as many >> arguments as you want. > > def func(*a) # a will be a tuple of whatever arguments are passed in the call. if any of the variables are keyworded, you'll need a vararg dictionary too, **kwargs. a very popular idiom you'll see in function signatures looks like this: def func(*args, **kwargs) this is the most flexible Python function definition because this function can accept *any* number and type of arguments you can give it, i.e., func() func(a) func(a, b) func(a, b, c, d, e) func(a, b, c, d, e=0) func(a, b, 999, xxx=['foo', 'bar'], yyy=42) : hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From edwin_boyette at yahoo.com Thu Jan 8 08:30:48 2009 From: edwin_boyette at yahoo.com (Edwin Boyette) Date: Wed, 7 Jan 2009 23:30:48 -0800 (PST) Subject: [Tutor] simple array access Message-ID: <707706.95402.qm@web53712.mail.re2.yahoo.com> --- On Wed, 1/7/09, Artie Ziff wrote: From: Artie Ziff Subject: [Tutor] simple array access To: Tutor at python.org Date: Wednesday, January 7, 2009, 9:12 PM Hello, I used python list comprehension to create a grid (list of lists) of Objects (instances of MyItem class). Can anyone make recommendations to achieve a simple access to the elements. My attempt at array access (like this: array[1,2] ) does not work. What am I overlooking? Thanks in advance! :) If anyone has time to show a better way to achieve same, then I am interested to learn! :) ### from pprint import * class MyItem: ? def __init__(self, value): ? ? self.data=value ? def __repr__(self): ? ? return 'MyItem(%s)' % (self.data) class Grid: ? def __init__(self, x, y, value): ? ? self.data = [[MyItem(float(value)) ? ? ? ? ? ? ? ? ? for i in range(x)] for j in range(y)] if __name__ == "__main__": ? grid = Grid(2, 3, 0.42) ? pprint(grid) ? pprint(grid.data) ? # next line fails to access array element ? pprint (grid.data[1,2]) # EOF # OUTPUT: <__main__.Grid instance at 0x7beb8> [[MyItem(0.42), MyItem(0.42)], [MyItem(0.42), MyItem(0.42)], [MyItem(0.42), MyItem(0.42)]] Traceback (most recent call last): ? File "multidim04.py", line 20, in ? ? pprint (grid.data[1,2]) TypeError: list indices must be integers Cheers, Art ? ## There are probably much easier, elegant ways to populate a list ## This is fast enough to generate to express the idea ## There is a row/col method also but I haven't used it ## List comprehensions may be prettier/faster (check Kent's page I believe he has ## write up on them some_sequence = [] i = 0 k = [] for i in range (10): ?k.append(i) for i in range (10): ??? some_sequence.append(k) for stuff in some_sequence: ??? print stuff ??? print "Some sequence has 10 outer indexes beginning at [0] and ending at [9]" print "The first element of index [0] is the value 0, and can be accessed at some_sequence[0][0] :" + str(some_sequence[0][0]) print "The last element of index [9] ## the 10th line or index is the value 9, and can be accessed at some_sequence[9][9] :" + str(some_sequence[9][9]) ?????????????????????????????????????????????????????????????????????????????????????????????????????? ??????????????????? ? ? ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Jan 8 10:22:07 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 8 Jan 2009 09:22:07 -0000 Subject: [Tutor] variable number of inputs References: <49656C96.5070707@gmail.com> <78b3a9580901071922s584aafcby12bcc5865dd37263@mail.gmail.com> Message-ID: "wesley chun" wrote > a very popular idiom you'll see in function signatures looks like > this: > > def func(*args, **kwargs) > > this is the most flexible Python function definition because this > function can accept *any* number and type of arguments you can give But the caveat: With power comes responsibility. You need to make sure your function can cope with this potential wealth of data being thrown at it! Othewise its all a bit pointless! :-) -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From s4027340 at student.uq.edu.au Thu Jan 8 13:12:10 2009 From: s4027340 at student.uq.edu.au (Mr Gerard Kelly) Date: Thu, 08 Jan 2009 22:12:10 +1000 Subject: [Tutor] Chord player Message-ID: I want to thank Emmanuel from the tutor mailing list for showing me a piece of code that let me do exactly what I wanted - making Python play a chord from a input of frequencies. I only needed to make a few adjustments. The code (below) uses Numeric. Emmanuel said that Numeric is out of date and should be replaced everywhere by numpy. When I do that there is no error message but the code doesn't play any sound. So I'm keeping Numeric in there (although I read somewhere that Python automatically converts Numeric to numpy anyway). I did have one problem, which is when you play a chord, you hear a clipping sound every second. I assume that is because of this line: def sine_array(hz, peak, n_samples = sample_rate): #Compute N samples of a sine wave with given frequency and peak amplitude (defaults to one second). return Numeric.resize(sine_array_onecycle(hz, peak), (n_samples,)) I thought I could get rid of the clipping noise by making it return more samples than just for one second. For instance if I put in 2*(n_samples) instead of the default sample_rate value, it might make the clipping sound come every 2 seconds etc. However, I have found that if I put in any other value other than the default value, it cannot calculate. The dimensions are wrong or there is a memory problem or something. I'm not sure how the resize method works and I was wondering if it is actually possible to fix this problem this way. Here's the whole code: *** import pygame, time, random, Numeric, pygame, pygame.sndarray sample_rate = 44100 def sine_array_onecycle(hz, peak): #Compute one cycle of an N-Hz sine wave with given peak amplitude length = sample_rate / float(hz) omega = Numeric.pi * 2 / length xvalues = Numeric.arange(int(length)) * omega return (peak * Numeric.sin(xvalues)).astype(Numeric.Int16) def sine_array(hz, peak, n_samples = sample_rate): #Compute N samples of a sine wave with given frequency and peak amplitude (defaults to one second). return Numeric.resize(sine_array_onecycle(hz, peak), (n_samples,)) def waves(*chord): #Compute the harmonic series for a vector of frequencies #Create square-like waves by adding odd-numbered overtones for each fundamental tone in the chord #the amplitudes of the overtones are inverse to their frequencies. h=9 ot=3 harmonic=sine_array(chord[0],4096) while (ot Hi everyone, I'm a python noob but I have an ambitious (for me) goal: I > want to make a simple program that allows you to hear combinations of > notes according to a vector of frequencies. > > Does anybody know any module that allows you to input a frequency in Hz > and returns a sound with that frequency, and lets you do that with > multiple frequencies, so that you can build chords? The recipe linked below plays sounds composed of a fundamental and a few harmonics. It requires Pygame and NumPy. http://osdir.com/ml/culture.people.kragen.hacks/2007-11/msg00000.html It is out of date, though. I had to change 'Numeric' to 'numpy' and 'Int16' to 'int16' to get it to work. Moreover NumPy doesn't seem to work with Python 2.6. You can also use TkSnack (http://www.speech.kth.se/snack/). Check the example named 'notescale' that comes with the module: it defines a function that receives a frequency as an input and plays a sound; there is also a graphical interface. Regards, Emmanuel -------------- next part -------------- An HTML attachment was scrubbed... URL: From s4027340 at student.uq.edu.au Thu Jan 8 13:38:34 2009 From: s4027340 at student.uq.edu.au (Mr Gerard Kelly) Date: Thu, 08 Jan 2009 22:38:34 +1000 Subject: [Tutor] Chord player Message-ID: Actually, I think I can minimize the clipping sound by setting the sample_rate to be one hundred times the value of the highest frequency in the chord. But it's still there for the notes underneath. Oh well, better than nothing! ----- Original Message ----- From: Mr Gerard Kelly Date: Thursday, January 8, 2009 10:12 pm Subject: [Tutor] Chord player > I want to thank Emmanuel from the tutor mailing list for showing me a > piece of code that let me do exactly what I wanted - making Python > playa chord from a input of frequencies. I only needed to make a few > adjustments. > > The code (below) uses Numeric. Emmanuel said that Numeric is out of > dateand should be replaced everywhere by numpy. When I do that > there is no > error message but the code doesn't play any sound. So I'm keeping > Numeric in there (although I read somewhere that Python automatically > converts Numeric to numpy anyway). > > I did have one problem, which is when you play a chord, you hear a > clipping sound every second. I assume that is because of this line: > > def sine_array(hz, peak, n_samples = sample_rate): > #Compute N samples of a sine wave with given frequency and peak > amplitude (defaults to one second). > return Numeric.resize(sine_array_onecycle(hz, peak), (n_samples,)) > > I thought I could get rid of the clipping noise by making it return > moresamples than just for one second. For instance if I put in > 2*(n_samples)instead of the default sample_rate value, it might > make the clipping > sound come every 2 seconds etc. However, I have found that if I put in > any other value other than the default value, it cannot calculate. The > dimensions are wrong or there is a memory problem or something. I'm > notsure how the resize method works and I was wondering if it is > actuallypossible to fix this problem this way. > > Here's the whole code: > > > *** > > import pygame, time, random, Numeric, pygame, pygame.sndarray > sample_rate = 44100 > > def sine_array_onecycle(hz, peak): > #Compute one cycle of an N-Hz sine wave with given peak amplitude > length = sample_rate / float(hz) > omega = Numeric.pi * 2 / length > xvalues = Numeric.arange(int(length)) * omega > return (peak * Numeric.sin(xvalues)).astype(Numeric.Int16) > > def sine_array(hz, peak, n_samples = sample_rate): > #Compute N samples of a sine wave with given frequency and peak > amplitude (defaults to one second). > > return Numeric.resize(sine_array_onecycle(hz, peak), (n_samples,)) > > def waves(*chord): > #Compute the harmonic series for a vector of frequencies > #Create square-like waves by adding odd-numbered overtones for each > fundamental tone in the chord > #the amplitudes of the overtones are inverse to their frequencies. > h=9 > ot=3 > harmonic=sine_array(chord[0],4096) > while (ot if (ot*chord[0])<(sample_rate/2): > harmonic=harmonic+(sine_array(chord[0]*ot, 4096/(2*ot))) > else: > harmonic=harmonic+0 > ot+=2 > for i in range(1,len(chord)): > harmonic+=(sine_array(chord[i], 4096)) > > > if (ot*chord[i])<(sample_rate/2): > harmonic=harmonic+(sine_array(chord[i]*ot, 4096/(2*ot))) > else: > harmonic=harmonic+0 > ot+=2 > return harmonic > > def play_for(sample_array, ms): > #Play the sample array as a sound for N ms. > pygame.mixer.pre_init(sample_rate, -16, 1) # 44.1kHz, 16-bit > signed, mono > pygame.init() > sound = pygame.sndarray.make_sound(sample_array) > sound.play(-1) > pygame.time.delay(ms) > sound.stop() > > def main(): > #Play a single sine wave, followed by a chord with overtones. > > pygame.mixer.pre_init(sample_rate, -16, 1) # 44.1kHz, 16-bit > signed, mono > pygame.init() > play_for(sine_array(440, 4096), 2500) > play_for(waves(440,550,660,770,880), 5000) > > > if __name__ == '__main__': main() > > > *** > > Thanks for having a look! > > Gerard. > -------------- next part -------------- Gerard Kelly wrote: > Hi everyone, I'm a python noob but I have an ambitious (for me) goal: I > want to make a simple program that allows you to hear combinations of > notes according to a vector of frequencies. > > Does anybody know any module that allows you to input a frequency in Hz > and returns a sound with that frequency, and lets you do that with > multiple frequencies, so that you can build chords? The recipe linked below plays sounds composed of a fundamental and a few harmonics. It requires Pygame and NumPy. http://osdir.com/ml/culture.people.kragen.hacks/2007-11/msg00000.html It is out of date, though. I had to change 'Numeric' to 'numpy' and 'Int16' to 'int16' to get it to work. Moreover NumPy doesn't seem to work with Python 2.6. You can also use TkSnack (http://www.speech.kth.se/snack/). Check the example named 'notescale' that comes with the module: it defines a function that receives a frequency as an input and plays a sound; there is also a graphical interface. Regards, Emmanuel -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From bermanrl at cfl.rr.com Thu Jan 8 16:49:10 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Thu, 08 Jan 2009 10:49:10 -0500 Subject: [Tutor] Suggestions for more efficient and optimized coding technique, Message-ID: <49662076.3040200@cfl.rr.com> Hi, One of the challenges on the challenge you web page appropriately titled 'Brute force' reads as follows: "The password you have to guess is 'loner' . Try all combinations of lowercase letters until you guess it. Try not to loop much for example, save all used combinations in an array so you don't repeat." My code is as follows: #!/usr/bin/env python import random def GetString(): alphabet='abcdefghijklmnopqrstuvwxyz' return ''.join(random.sample(alphabet,5)) def main(): password='loner' errknt = 0 control = True while control is True: if GetString() != password: errknt +=1 else: print 'Password found in ',errknt,' tries.' control = False if __name__ == '__main__': main() The code does work. I am looking for suggestions to learn more about both efficiency and optimization of code. Since the challenge revolves around the use of randomized retrieval, I'm not too sure how to optimize the process. The authors concept of using arrays seem a bit superfluous as I think it takes longer to add an item to a dictionary and retrieve an item from a dictionary than it does to do an if compare of two 5 character strings. So, I left that code out of the program entirely. If that was wrong, or there is a better way to avoid duplication, please point me in the right direction. I think, perhaps, I could make it a tad more efficient if I changed 'alphabet' from a string to a list as I remember reading that lists are significantly faster to manipulate than are strings. Is that true and is it a viable change. I realize my code looks like modified C++ structured code. I am trying to become more Python concise but I think that is a matter of writing more and more python code. All suggestions, ideas, critiques are most welcome. Thank you, Robert From wferguson1 at socal.rr.com Thu Jan 8 17:30:07 2009 From: wferguson1 at socal.rr.com (WM.) Date: Thu, 08 Jan 2009 08:30:07 -0800 Subject: [Tutor] Thank you, Alan. Message-ID: <49662A0F.4080509@socal.rr.com> I felt such a monkey until Kent convinced me that the 'else' only appeared to be un-indented. From michael.langford at gmail.com Thu Jan 8 17:34:49 2009 From: michael.langford at gmail.com (Michael Langford) Date: Thu, 8 Jan 2009 11:34:49 -0500 Subject: [Tutor] Suggestions for more efficient and optimized coding technique, In-Reply-To: <49662076.3040200@cfl.rr.com> References: <49662076.3040200@cfl.rr.com> Message-ID: <82b4f5810901080834j28a668cbq1a1e22bd8d79a7b6@mail.gmail.com> Here is your algorithm made more pythonic. Notice the use of default parameters, doc strings, not abbreviated variable names, unix C style capitolization (very subjective, but often the one found in python libs), the avoidance of control variables when possible, the use of ascii_lowercase instead of your own string and the not calling functions main that aren't __main__. #!/usr/bin/env python import string import random def rand_string(length = 5): """returns a random string of numbers""" return ''.join(random.sample(string.ascii_lowercase,length)) def try_password(match="loner"): """randomly tries 5 letter long passwords until the user finds the correct one""" tries = 0 while True: tries += 1 if rand_string() == match: print 'Password found in ' + str(tries) + ' tries.' return if __name__ == '__main__': try_password() Note: I do not think you're doing the problem the way the author intended. As it wants you to try all combinations, and it's about brute force, not finding it quickly, you most likely should start at "aaaaa" and move to "zzzzz", and cache the results in a list like they ask you too. At the very least, you should be saving these combinations you are generating randomly in a list (as it asks you to) and not testing the password if the generated string was already in the list (as in a real application, that is the time consuming or dangerous operation). --Michael PS: If you wish to assure direct replies reach me On Thu, Jan 8, 2009 at 10:49 AM, Robert Berman wrote: > Hi, > > One of the challenges on the challenge you web page appropriately titled > 'Brute force' reads as follows: > > "The password you have to guess is 'loner' . Try all combinations of > lowercase letters until you guess it. Try not to loop much for example, > save all used combinations in an array so you don't repeat." > > My code is as follows: > > #!/usr/bin/env python > > import random > > def GetString(): > alphabet='abcdefghijklmnopqrstuvwxyz' > return ''.join(random.sample(alphabet,5)) > def main(): > password='loner' > errknt = 0 > control = True > while control is True: > if GetString() != password: > errknt +=1 > else: > print 'Password found in ',errknt,' tries.' > control = False > > if __name__ == '__main__': main() > The code does work. I am looking for suggestions to learn more about both > efficiency and optimization of code. > > Since the challenge revolves around the use of randomized retrieval, I'm not > too sure how to optimize the process. The authors concept of using arrays > seem a bit superfluous as I think it takes longer to add an item to a > dictionary and retrieve an item from a dictionary than it does to do an if > compare of two 5 character strings. So, I left that code out of the program > entirely. If that was wrong, or there is a better way to avoid duplication, > please point me in the right direction. > > I think, perhaps, I could make it a tad more efficient if I changed > 'alphabet' from a string to a list as I remember reading that lists are > significantly faster to manipulate than are strings. Is that true and is it > a viable change. > > I realize my code looks like modified C++ structured code. I am trying to > become more Python concise but I think that is a matter of writing more and > more python code. > > All suggestions, ideas, critiques are most welcome. > > Thank you, > > Robert > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com From kent37 at tds.net Thu Jan 8 18:28:20 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 8 Jan 2009 12:28:20 -0500 Subject: [Tutor] Suggestions for more efficient and optimized coding technique, In-Reply-To: <49662076.3040200@cfl.rr.com> References: <49662076.3040200@cfl.rr.com> Message-ID: <1c2a2c590901080928p4bf1907fy602b5d57c7fd4617@mail.gmail.com> On Thu, Jan 8, 2009 at 10:49 AM, Robert Berman wrote: > Hi, > > One of the challenges on the challenge you web page appropriately titled > 'Brute force' reads as follows: > > "The password you have to guess is 'loner' . Try all combinations of > lowercase letters until you guess it. Try not to loop much for example, > save all used combinations in an array so you don't repeat." This is a strange requirement. If you want to try all combinations of lowercase letters, the simplest way to do that is with nested loops. The loops will generate all combinations without repeating, so there is no need to save the used combinations. > Since the challenge revolves around the use of randomized retrieval, I'm not > too sure how to optimize the process. The authors concept of using arrays > seem a bit superfluous as I think it takes longer to add an item to a > dictionary and retrieve an item from a dictionary than it does to do an if > compare of two 5 character strings. So, I left that code out of the program > entirely. If that was wrong, or there is a better way to avoid duplication, > please point me in the right direction. To avoid duplication you should use a set to hold the passwords already tried. It is probably faster to just compare, but if you are supposed to imagine a true brute-force password attack, the set test would be faster than a failed login. > I think, perhaps, I could make it a tad more efficient if I changed > 'alphabet' from a string to a list as I remember reading that lists are > significantly faster to manipulate than are strings. Is that true and is it > a viable change. I don't think it will make any difference. The place where lists are preferred is when you are concatenating strings in a loop. Kent From roadierich at googlemail.com Thu Jan 8 18:58:33 2009 From: roadierich at googlemail.com (Richard Lovely) Date: Thu, 8 Jan 2009 17:58:33 +0000 Subject: [Tutor] Suggestions for more efficient and optimized coding technique, In-Reply-To: <1c2a2c590901080928p4bf1907fy602b5d57c7fd4617@mail.gmail.com> References: <49662076.3040200@cfl.rr.com> <1c2a2c590901080928p4bf1907fy602b5d57c7fd4617@mail.gmail.com> Message-ID: 2009/1/8 Kent Johnson : > > This is a strange requirement. If you want to try all combinations of > lowercase letters, the simplest way to do that is with nested loops. > The loops will generate all combinations without repeating, so there > is no need to save the used combinations. > or itertools.product --- Richard "Roadie Rich" Lovely, part of the JNP|UK Famile www.theJNP.com From bermanrl at cfl.rr.com Thu Jan 8 19:31:51 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Thu, 08 Jan 2009 13:31:51 -0500 Subject: [Tutor] Suggestions for more efficient and optimized coding technique, In-Reply-To: <82b4f5810901080834j28a668cbq1a1e22bd8d79a7b6@mail.gmail.com> References: <49662076.3040200@cfl.rr.com> <82b4f5810901080834j28a668cbq1a1e22bd8d79a7b6@mail.gmail.com> Message-ID: <49664697.8080700@cfl.rr.com> An HTML attachment was scrubbed... URL: From bermanrl at cfl.rr.com Thu Jan 8 19:44:59 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Thu, 08 Jan 2009 13:44:59 -0500 Subject: [Tutor] Suggestions for more efficient and optimized coding technique, In-Reply-To: <1c2a2c590901080928p4bf1907fy602b5d57c7fd4617@mail.gmail.com> References: <49662076.3040200@cfl.rr.com> <1c2a2c590901080928p4bf1907fy602b5d57c7fd4617@mail.gmail.com> Message-ID: <496649AB.2060201@cfl.rr.com> An HTML attachment was scrubbed... URL: From bermanrl at cfl.rr.com Thu Jan 8 19:49:35 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Thu, 08 Jan 2009 13:49:35 -0500 Subject: [Tutor] Suggestions for more efficient and optimized coding technique, In-Reply-To: References: <49662076.3040200@cfl.rr.com> <1c2a2c590901080928p4bf1907fy602b5d57c7fd4617@mail.gmail.com> Message-ID: <49664ABF.8070302@cfl.rr.com> An HTML attachment was scrubbed... URL: From finde.m at gmail.com Thu Jan 8 20:30:02 2009 From: finde.m at gmail.com (Jonathan Balkind) Date: Thu, 8 Jan 2009 19:30:02 +0000 Subject: [Tutor] Functions and Mainloop() Message-ID: <19a0f0fc0901081130y3471b6aq1be5f469f7e18bac@mail.gmail.com> Hi tutor list, I haven't been programming for long with Python, and I'm currently trying to make a simple game using Tkinter. I was wondering whether it is possible to submit a function to the mainloop so it will run every time the loop goes around? I thought about adding the function to the event handler, but I was hoping I could just submit the function to the mainloop. Thanks in advance, Jonathan. -------------- next part -------------- An HTML attachment was scrubbed... URL: From john at fouhy.net Thu Jan 8 21:14:45 2009 From: john at fouhy.net (John Fouhy) Date: Fri, 9 Jan 2009 09:14:45 +1300 Subject: [Tutor] Functions and Mainloop() In-Reply-To: <19a0f0fc0901081130y3471b6aq1be5f469f7e18bac@mail.gmail.com> References: <19a0f0fc0901081130y3471b6aq1be5f469f7e18bac@mail.gmail.com> Message-ID: <5e58f2e40901081214s85d74f7ye1777a3ff0f4ffd0@mail.gmail.com> 2009/1/9 Jonathan Balkind : > Hi tutor list, > I haven't been programming for long with Python, and I'm currently trying to > make a simple game using Tkinter. I was wondering whether it is possible to > submit a function to the mainloop so it will run every time the loop goes > around? I thought about adding the function to the event handler, but I was > hoping I could just submit the function to the mainloop. Hi Jonathan, You can use the after() method. See here: http://www.pythonware.com/library/tkinter/introduction/x9507-alarm-handlers-and-other.htm -- John. From ig2ar-saf1 at yahoo.co.uk Thu Jan 8 20:51:01 2009 From: ig2ar-saf1 at yahoo.co.uk (culpritNr1) Date: Thu, 8 Jan 2009 11:51:01 -0800 (PST) Subject: [Tutor] casting string to integer in a list of lists Message-ID: <21359600.post@talk.nabble.com> Hi All, Say I have this nice list of lists: LoL = [['chrX', '160944034', '160944035', 'gnfX.145.788', '63.60'], ['chrX', '161109992', '161109993', 'rs13484104', '63.60'], ['chrX', '161414112', '161414113', 'rs13484105', '63.60'], ['chrX', '161544071', '161544072', 'rs13484106', '63.60'], ['chrX', '162030736', '162030737', 'gnfX.146.867', '67.05'], ['chrX', '164171913', '164171914', 'gnfX.148.995', '70.45']] Now I want to cast the second and third "columns" from string to integer, like this LoL = [['chrX', 160944034, 160944035, 'gnfX.145.788', '63.60'], ['chrX', 161109992, 161109993, 'rs13484104', '63.60'], ['chrX', 161414112, 161414113, 'rs13484105', '63.60'], ['chrX', 161544071, 161544072, 'rs13484106', '63.60'], ['chrX', 162030736, 162030737, 'gnfX.146.867', '67.05'], ['chrX', 164171913, 164171914, 'gnfX.148.995', '70.45']] Is there any elegant way to do this? I can't assume that all lines will have the same number of elements. Thank you, Your Culprit -- View this message in context: http://www.nabble.com/casting-string-to-integer-in-a-list-of-lists-tp21359600p21359600.html Sent from the Python - tutor mailing list archive at Nabble.com. From michael.langford at rowdylabs.com Thu Jan 8 21:20:12 2009 From: michael.langford at rowdylabs.com (Michael Langford) Date: Thu, 8 Jan 2009 15:20:12 -0500 Subject: [Tutor] Suggestions for more efficient and optimized coding technique, In-Reply-To: <49664697.8080700@cfl.rr.com> References: <49662076.3040200@cfl.rr.com> <82b4f5810901080834j28a668cbq1a1e22bd8d79a7b6@mail.gmail.com> <49664697.8080700@cfl.rr.com> Message-ID: <11fb08580901081220r4339dd16kf7bac4c876e32f8e@mail.gmail.com> I understand that each response is unique Robert and no caching is required to solve the problem at hand. However in a real program, the chance you're brute forcing just one password is small (usually you would brute force many); additionally, the question posted specifically asked that the trials be cached, which is why I suggest you do so, not out of any real need for just testing on the "loner" testcase. Additionally, the reason the aaaaa->zzzzz method is suggested is that it a much faster algorithm to test every available combination than the random method. The random method may never find the data. I've created a frame work for you to play around with on this problem. It shows how long different methods take in a more realistic scenario. Try some other methods if you want, as well play around with password length, the aaaaa->zzzzz method, etc. I've shorted then password length to 3 to make it run faster as well. Enough procrastination, back to google app engine stuff. --Michael #!/usr/bin/env python import string import random # test code to simulate a computer system under # attack, no need to understand now class Computer(object): def __init__(self): self.reset_password() def reset_password(self,length=3): self.secret_password=''.join(random.sample(string.ascii_lowercase,length)) print('The new password is: ' + self.secret_password) def enter_password(self,teststr): """returns true if the password was correct""" return teststr==self.secret_password # end test code def rand_string(length = 3): """generates a random string of the given length""" return ''.join(random.sample(string.ascii_lowercase,length)) passcache = list() def crack_password(comp): """repeatedly tries passwords on the given computer""" tries = 0 while True: tries += 1 if comp.enter_password(rand_string()): print( 'Password found in ' + str(tries) + ' tries.') return def crack_password_cached(comp): """repeatedly tries passwords on the given computer""" for password in passcache: if comp.enter_password(password): print 'Password found in cache' return tries = 0 while True: tries += 1 s = rand_string() passcache.append(s) if comp.enter_password(s): print( 'Password found in ' + str(tries) + ' tries.') return def hack(): """hacks a computer via a brute force method""" my_computer = Computer() crack_password(my_computer) def hack_cached(): """hacks a computer via a brute force method with cached results""" my_computer = Computer() crack_password_cached(my_computer) def mean(ls): """finds the mean of a list of numbers""" return sum(ls)/len(ls) def test_case(funcname, repeats): """ timeit is a python library for timing code. No need to understand how this works, just that its repeating the command given the number times specified by repeats. It's returning a list of the execution times of each of the trials """ import timeit timer = timeit.Timer("%s()"%funcname,"from __main__ import %s"%funcname) return timer.repeat(number=repeats) if __name__ == '__main__': times_to_repeat = 100 uc_results = test_case("hack",times_to_repeat) c_results = test_case("hack_cached", times_to_repeat) print( "Cached mean time: " + repr(mean(c_results)) ) print( "Cached min. time: " + repr(min(c_results)) ) print( "Uncached mean time: " + repr(mean(uc_results)) ) print( "Uncached min. time: " + repr(min(uc_results)) ) On Thu, Jan 8, 2009 at 1:31 PM, Robert Berman wrote: > Michael, > > Thank you for your code and your commentary. The code tells me this is > really an ongoing learning process; almost as convoluted as linguistics and > certainly every bit as interesting. > > Your concept of brute force in this example is intriguing. It is as if I > have five cogs spinning, 'a' the slowest and 'e' flying as fast as its > spokes can engage, and every click of every wheel produces a viable but > possibly wrong response. However, each response is unique and in the nth > iteration where password is found, all previous iterations are unique so > there is certainly no need to carry the previous responses in either a list > or a dictionary. They do not duplicate since they cannot repeat. Other than > to include extraneous code, why include repetitive checking at all? > > In spite of that, your code and your remarks are most appreciated. > > Robert > > Michael Langford wrote: > > Here is your algorithm made more pythonic. Notice the use of default > parameters, doc strings, not abbreviated variable names, unix C style > capitolization (very subjective, but often the one found in python > libs), the avoidance of control variables when possible, the use of > ascii_lowercase instead of your own string and the not calling > functions main that aren't __main__. > > #!/usr/bin/env python > import string > import random > > def rand_string(length = 5): > """returns a random string of numbers""" > return ''.join(random.sample(string.ascii_lowercase,length)) > > def try_password(match="loner"): > """randomly tries 5 letter long passwords until the user finds the > correct one""" > tries = 0 > while True: > tries += 1 > if rand_string() == match: > print 'Password found in ' + str(tries) + ' tries.' > return > > if __name__ == '__main__': > try_password() > > > Note: I do not think you're doing the problem the way the author > intended. As it wants you to try all combinations, and it's about > brute force, not finding it quickly, you most likely should start at > "aaaaa" and move to "zzzzz", and cache the results in a list like they > ask you too. At the very least, you should be saving these > combinations you are generating randomly in a list (as it asks you to) > and not testing the password if the generated string was already in > the list (as in a real application, that is the time consuming or > dangerous operation). > > --Michael > > PS: If you wish to assure direct replies reach me > > On Thu, Jan 8, 2009 at 10:49 AM, Robert Berman wrote: > > > Hi, > > One of the challenges on the challenge you web page appropriately titled > 'Brute force' reads as follows: > > "The password you have to guess is 'loner' . Try all combinations of > lowercase letters until you guess it. Try not to loop much for example, > save all used combinations in an array so you don't repeat." > > My code is as follows: > > #!/usr/bin/env python > > import random > > def GetString(): > alphabet='abcdefghijklmnopqrstuvwxyz' > return ''.join(random.sample(alphabet,5)) > def main(): > password='loner' > errknt = 0 > control = True > while control is True: > if GetString() != password: > errknt +=1 > else: > print 'Password found in ',errknt,' tries.' > control = False > > if __name__ == '__main__': main() > The code does work. I am looking for suggestions to learn more about both > efficiency and optimization of code. > > Since the challenge revolves around the use of randomized retrieval, I'm not > too sure how to optimize the process. The authors concept of using arrays > seem a bit superfluous as I think it takes longer to add an item to a > dictionary and retrieve an item from a dictionary than it does to do an if > compare of two 5 character strings. So, I left that code out of the program > entirely. If that was wrong, or there is a better way to avoid duplication, > please point me in the right direction. > > I think, perhaps, I could make it a tad more efficient if I changed > 'alphabet' from a string to a list as I remember reading that lists are > significantly faster to manipulate than are strings. Is that true and is it > a viable change. > > I realize my code looks like modified C++ structured code. I am trying to > become more Python concise but I think that is a matter of writing more and > more python code. > > All suggestions, ideas, critiques are most welcome. > > Thank you, > > Robert > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > > -- Michael Langford Phone: 404-386-0495 Web: http://www.RowdyLabs.com From bermanrl at cfl.rr.com Thu Jan 8 21:46:57 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Thu, 08 Jan 2009 15:46:57 -0500 Subject: [Tutor] Suggestions for more efficient and optimized coding technique, In-Reply-To: <11fb08580901081220r4339dd16kf7bac4c876e32f8e@mail.gmail.com> References: <49662076.3040200@cfl.rr.com> <82b4f5810901080834j28a668cbq1a1e22bd8d79a7b6@mail.gmail.com> <49664697.8080700@cfl.rr.com> <11fb08580901081220r4339dd16kf7bac4c876e32f8e@mail.gmail.com> Message-ID: <49666641.2090401@cfl.rr.com> Thank you again. I now have enough to keep me happily busy for days. Robert Michael Langford wrote: > I understand that each response is unique Robert and no caching is > required to solve the problem at hand. However in a real program, the > chance you're brute forcing just one password is small (usually you > would brute force many); additionally, the question posted > specifically asked that the trials be cached, which is why I suggest > you do so, not out of any real need for just testing on the "loner" > testcase. > > Additionally, the reason the aaaaa->zzzzz method is suggested is that > it a much faster algorithm to test every available combination than > the random method. The random method may never find the data. > > I've created a frame work for you to play around with on this problem. > It shows how long different methods take in a more realistic scenario. > Try some other methods if you want, as well play around with password > length, the aaaaa->zzzzz method, etc. I've shorted then password > length to 3 to make it run faster as well. Enough procrastination, > back to google app engine stuff. > > --Michael > > #!/usr/bin/env python > import string > import random > > # test code to simulate a computer system under > # attack, no need to understand now > class Computer(object): > def __init__(self): > self.reset_password() > > def reset_password(self,length=3): > self.secret_password=''.join(random.sample(string.ascii_lowercase,length)) > print('The new password is: ' + self.secret_password) > > def enter_password(self,teststr): > """returns true if the password was correct""" > return teststr==self.secret_password > > # end test code > > > def rand_string(length = 3): > """generates a random string of the given length""" > return ''.join(random.sample(string.ascii_lowercase,length)) > > passcache = list() > > def crack_password(comp): > """repeatedly tries passwords on the given computer""" > tries = 0 > while True: > tries += 1 > if comp.enter_password(rand_string()): > print( 'Password found in ' + str(tries) + ' tries.') > return > > def crack_password_cached(comp): > """repeatedly tries passwords on the given computer""" > for password in passcache: > if comp.enter_password(password): > print 'Password found in cache' > return > > tries = 0 > while True: > tries += 1 > s = rand_string() > passcache.append(s) > if comp.enter_password(s): > print( 'Password found in ' + str(tries) + ' tries.') > return > > > def hack(): > """hacks a computer via a brute force method""" > my_computer = Computer() > crack_password(my_computer) > > def hack_cached(): > """hacks a computer via a brute force method with cached results""" > my_computer = Computer() > crack_password_cached(my_computer) > > > def mean(ls): > """finds the mean of a list of numbers""" > return sum(ls)/len(ls) > > > def test_case(funcname, repeats): > """ > timeit is a python library for timing code. No need to > understand how this works, just that its repeating the > command given the number times specified by repeats. It's > returning a list of the execution times of each of the trials > """ > import timeit > timer = timeit.Timer("%s()"%funcname,"from __main__ import %s"%funcname) > return timer.repeat(number=repeats) > > > if __name__ == '__main__': > > > times_to_repeat = 100 > > uc_results = test_case("hack",times_to_repeat) > c_results = test_case("hack_cached", times_to_repeat) > > print( "Cached mean time: " + repr(mean(c_results)) ) > print( "Cached min. time: " + repr(min(c_results)) ) > print( "Uncached mean time: " + repr(mean(uc_results)) ) > print( "Uncached min. time: " + repr(min(uc_results)) ) > > > > > > > > > > On Thu, Jan 8, 2009 at 1:31 PM, Robert Berman wrote: > >> Michael, >> >> Thank you for your code and your commentary. The code tells me this is >> really an ongoing learning process; almost as convoluted as linguistics and >> certainly every bit as interesting. >> >> Your concept of brute force in this example is intriguing. It is as if I >> have five cogs spinning, 'a' the slowest and 'e' flying as fast as its >> spokes can engage, and every click of every wheel produces a viable but >> possibly wrong response. However, each response is unique and in the nth >> iteration where password is found, all previous iterations are unique so >> there is certainly no need to carry the previous responses in either a list >> or a dictionary. They do not duplicate since they cannot repeat. Other than >> to include extraneous code, why include repetitive checking at all? >> >> In spite of that, your code and your remarks are most appreciated. >> >> Robert >> >> Michael Langford wrote: >> >> Here is your algorithm made more pythonic. Notice the use of default >> parameters, doc strings, not abbreviated variable names, unix C style >> capitolization (very subjective, but often the one found in python >> libs), the avoidance of control variables when possible, the use of >> ascii_lowercase instead of your own string and the not calling >> functions main that aren't __main__. >> >> #!/usr/bin/env python >> import string >> import random >> >> def rand_string(length = 5): >> """returns a random string of numbers""" >> return ''.join(random.sample(string.ascii_lowercase,length)) >> >> def try_password(match="loner"): >> """randomly tries 5 letter long passwords until the user finds the >> correct one""" >> tries = 0 >> while True: >> tries += 1 >> if rand_string() == match: >> print 'Password found in ' + str(tries) + ' tries.' >> return >> >> if __name__ == '__main__': >> try_password() >> >> >> Note: I do not think you're doing the problem the way the author >> intended. As it wants you to try all combinations, and it's about >> brute force, not finding it quickly, you most likely should start at >> "aaaaa" and move to "zzzzz", and cache the results in a list like they >> ask you too. At the very least, you should be saving these >> combinations you are generating randomly in a list (as it asks you to) >> and not testing the password if the generated string was already in >> the list (as in a real application, that is the time consuming or >> dangerous operation). >> >> --Michael >> >> PS: If you wish to assure direct replies reach me >> >> On Thu, Jan 8, 2009 at 10:49 AM, Robert Berman wrote: >> >> >> Hi, >> >> One of the challenges on the challenge you web page appropriately titled >> 'Brute force' reads as follows: >> >> "The password you have to guess is 'loner' . Try all combinations of >> lowercase letters until you guess it. Try not to loop much for example, >> save all used combinations in an array so you don't repeat." >> >> My code is as follows: >> >> #!/usr/bin/env python >> >> import random >> >> def GetString(): >> alphabet='abcdefghijklmnopqrstuvwxyz' >> return ''.join(random.sample(alphabet,5)) >> def main(): >> password='loner' >> errknt = 0 >> control = True >> while control is True: >> if GetString() != password: >> errknt +=1 >> else: >> print 'Password found in ',errknt,' tries.' >> control = False >> >> if __name__ == '__main__': main() >> The code does work. I am looking for suggestions to learn more about both >> efficiency and optimization of code. >> >> Since the challenge revolves around the use of randomized retrieval, I'm not >> too sure how to optimize the process. The authors concept of using arrays >> seem a bit superfluous as I think it takes longer to add an item to a >> dictionary and retrieve an item from a dictionary than it does to do an if >> compare of two 5 character strings. So, I left that code out of the program >> entirely. If that was wrong, or there is a better way to avoid duplication, >> please point me in the right direction. >> >> I think, perhaps, I could make it a tad more efficient if I changed >> 'alphabet' from a string to a list as I remember reading that lists are >> significantly faster to manipulate than are strings. Is that true and is it >> a viable change. >> >> I realize my code looks like modified C++ structured code. I am trying to >> become more Python concise but I think that is a matter of writing more and >> more python code. >> >> All suggestions, ideas, critiques are most welcome. >> >> Thank you, >> >> Robert >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> >> >> >> > > > > From denis.spir at free.fr Thu Jan 8 22:06:30 2009 From: denis.spir at free.fr (spir) Date: Thu, 8 Jan 2009 22:06:30 +0100 Subject: [Tutor] Suggestions for more efficient and optimized coding technique, In-Reply-To: <82b4f5810901080834j28a668cbq1a1e22bd8d79a7b6@mail.gmail.com> References: <49662076.3040200@cfl.rr.com> <82b4f5810901080834j28a668cbq1a1e22bd8d79a7b6@mail.gmail.com> Message-ID: <20090108220630.14a899a7@o> Le Thu, 8 Jan 2009 11:34:49 -0500, "Michael Langford" a ?crit : > Here is your algorithm made more pythonic. Notice the use of default > parameters, doc strings, not abbreviated variable names, unix C style > capitolization (very subjective, but often the one found in python > libs), the avoidance of control variables when possible, the use of > ascii_lowercase instead of your own string and the not calling > functions main that aren't __main__. > > #!/usr/bin/env python > import string > import random > > def rand_string(length = 5): > """returns a random string of numbers""" > return ''.join(random.sample(string.ascii_lowercase,length)) Since you wish to use (not necessary) optional args, it may be worth defining def rand_string(length = 5): """returns a random string of numbers""" return ''.join(random.sample(string.ascii_lowercase,length)) which also avoids reading string.ascii_lowercase in each loop denis From marc.tompkins at gmail.com Thu Jan 8 22:26:28 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 8 Jan 2009 13:26:28 -0800 Subject: [Tutor] casting string to integer in a list of lists In-Reply-To: <21359600.post@talk.nabble.com> References: <21359600.post@talk.nabble.com> Message-ID: <40af687b0901081326l93a793mb9b0158ba7c71373@mail.gmail.com> On Thu, Jan 8, 2009 at 11:51 AM, culpritNr1 wrote: > > Hi All, > > Say I have this nice list of lists: > > LoL = [['chrX', '160944034', '160944035', 'gnfX.145.788', '63.60'], > ['chrX', '161109992', '161109993', 'rs13484104', '63.60'], > ['chrX', '161414112', '161414113', 'rs13484105', '63.60'], > ['chrX', '161544071', '161544072', 'rs13484106', '63.60'], > ['chrX', '162030736', '162030737', 'gnfX.146.867', '67.05'], > ['chrX', '164171913', '164171914', 'gnfX.148.995', '70.45']] > > Now I want to cast the second and third "columns" from string to integer, > like this > > LoL = [['chrX', 160944034, 160944035, 'gnfX.145.788', '63.60'], > ['chrX', 161109992, 161109993, 'rs13484104', '63.60'], > ['chrX', 161414112, 161414113, 'rs13484105', '63.60'], > ['chrX', 161544071, 161544072, 'rs13484106', '63.60'], > ['chrX', 162030736, 162030737, 'gnfX.146.867', '67.05'], > ['chrX', 164171913, 164171914, 'gnfX.148.995', '70.45']] > > Is there any elegant way to do this? I can't assume that all lines will > have > the same number of elements. > Maybe not the most elegant way, but here's a quickie: print(LoL) for lstA in LoL: try: lstA[1] = int(lstA[1]) except: pass try: lstA[2] = int(lstA[2]) except: pass print(LoL) I put them in separate try/excepts in case the first one's not an integer but the second one is. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.spir at free.fr Thu Jan 8 22:57:52 2009 From: denis.spir at free.fr (spir) Date: Thu, 8 Jan 2009 22:57:52 +0100 Subject: [Tutor] casting string to integer in a list of lists In-Reply-To: <21359600.post@talk.nabble.com> References: <21359600.post@talk.nabble.com> Message-ID: <20090108225752.2977c752@o> Le Thu, 8 Jan 2009 11:51:01 -0800 (PST), culpritNr1 a ?crit : > > Hi All, > > Say I have this nice list of lists: > > LoL = [['chrX', '160944034', '160944035', 'gnfX.145.788', '63.60'], > ['chrX', '161109992', '161109993', 'rs13484104', '63.60'], > ['chrX', '161414112', '161414113', 'rs13484105', '63.60'], > ['chrX', '161544071', '161544072', 'rs13484106', '63.60'], > ['chrX', '162030736', '162030737', 'gnfX.146.867', '67.05'], > ['chrX', '164171913', '164171914', 'gnfX.148.995', '70.45']] > > Now I want to cast the second and third "columns" from string to integer, > like this > > LoL = [['chrX', 160944034, 160944035, 'gnfX.145.788', '63.60'], > ['chrX', 161109992, 161109993, 'rs13484104', '63.60'], > ['chrX', 161414112, 161414113, 'rs13484105', '63.60'], > ['chrX', 161544071, 161544072, 'rs13484106', '63.60'], > ['chrX', 162030736, 162030737, 'gnfX.146.867', '67.05'], > ['chrX', 164171913, 164171914, 'gnfX.148.995', '70.45']] > > Is there any elegant way to do this? I can't assume that all lines will have > the same number of elements. In you do not need checking whether specific items are "castable" (i.e. you really know what's in the list) you may use such a pattern: lol = [[1,2,3],[4,5,6],[7,8,9]] new_lol = [[a,b**3,c] for [a,b,c] in lol] print lol print new_lol ==> [[1, 2, 3], [4, 5, 6], [7, 8, 9]] [[1, 8, 3], [4, 125, 6], [7, 512, 9]] denis > Thank you, > > Your Culprit > > ------ la vida e estranya From wescpy at gmail.com Thu Jan 8 23:21:39 2009 From: wescpy at gmail.com (wesley chun) Date: Thu, 8 Jan 2009 14:21:39 -0800 Subject: [Tutor] casting string to integer in a list of lists In-Reply-To: <40af687b0901081326l93a793mb9b0158ba7c71373@mail.gmail.com> References: <21359600.post@talk.nabble.com> <40af687b0901081326l93a793mb9b0158ba7c71373@mail.gmail.com> Message-ID: <78b3a9580901081421q7086bakbdd2a9b54bcfd060@mail.gmail.com> >> LoL = [['chrX', '160944034', '160944035', 'gnfX.145.788', '63.60'], >> : >> Now I want to cast the second and third "columns" from string to integer, >> like this >> >> LoL = [['chrX', 160944034, 160944035, 'gnfX.145.788', '63.60'], >> : >> Is there any elegant way to do this? I can't assume that all lines will >> have the same number of elements. the easiest way to do it is using int(), as in the below. > for lstA in LoL: > try: > lstA[1] = int(lstA[1]) > except: > pass > try: > lstA[2] = int(lstA[2]) > except: > pass it's definitely a *good* idea to check and make sure the numbers are legit, meaning that int() won't throw an exception, but it is a *bad* idea to have any code anywhere that looks like: except: pass try not to code these 2 lines in anything that you do because it will come back to haunt you when something is not working right but you can't find any errors. that's because this code masks and throws away everything!! if you are guaranteed that the strings all contain valid integers, then you don't have to worry about problems calling int(). hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From david at hlacik.eu Thu Jan 8 23:24:21 2009 From: david at hlacik.eu (=?ISO-8859-2?Q?David_Hl=E1=E8ik?=) Date: Thu, 8 Jan 2009 23:24:21 +0100 Subject: [Tutor] linked list with cycle structure In-Reply-To: <6smp37F763pbU2@mid.uni-berlin.de> References: <6sjok8F6dqciU1@mid.uni-berlin.de> <6smp37F763pbU2@mid.uni-berlin.de> Message-ID: Hi, well i am able to find a loop in a list using two iterators.One iterator runs "two times faster than the other", and if he encounters the first, it means that there is a loop. Example : 1,2,3,4,5,6,7,8,9,5 the algorithm would generate: start - 1,2 iteration 1- 2, 4 iteration 2- 3, 6 iteration 3- 4, 8 iteration 4- 5, 5 ( match) But how can this help me with counting list elements? :( Thanks, D. On Thu, Jan 8, 2009 at 5:48 PM, Diez B. Roggisch wrote: > > David Hl??ik wrote: > > > Hi, > > > > so okay, i will create a helping set, where i will be adding elements > > ID, when element ID will be allready in my helping set i will stop and > > count number of elements in helping set. This is how long my cycled > > linked list is. > > > But what if i have another condition , and that is *i can use only > > helping memory with constant size* ? This means i am not able to > > create any set and adding elements there. I need to have a constant > > size variables . This is complication a complication for me. > > This isn't to hard - think about what you are really interested in - knowing > if *all* other elements are already counted, or a specific one? You can get > away with only one, to detect the cycle and abort. > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list From marc.tompkins at gmail.com Fri Jan 9 00:11:13 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 8 Jan 2009 15:11:13 -0800 Subject: [Tutor] casting string to integer in a list of lists In-Reply-To: <78b3a9580901081421q7086bakbdd2a9b54bcfd060@mail.gmail.com> References: <21359600.post@talk.nabble.com> <40af687b0901081326l93a793mb9b0158ba7c71373@mail.gmail.com> <78b3a9580901081421q7086bakbdd2a9b54bcfd060@mail.gmail.com> Message-ID: <40af687b0901081511r5530db39kc03ce880ead73a22@mail.gmail.com> On Thu, Jan 8, 2009 at 2:21 PM, wesley chun wrote: > except: > pass > > try not to code these 2 lines in anything that you do because it will > come back to haunt you when something is not working right but you > can't find any errors. that's because this code masks and throws away > everything!! > > if you are guaranteed that the strings all contain valid integers, > then you don't have to worry about problems calling int(). > OP said we couldn't be sure that all rows would have the same number of elements; I'm afraid I extrapolated that we also might not be sure they were all integers (or, I should say, strings representing integers...), so there are two potential error types: IndexError and ValueError. I assumed that if either one occurred, we would want to leave that particular list member (if it exists) as-is (hence the pass). I see three ways around this: - test each list for length, and each member for integer-ness, before casting anything; - catch the exception, test to see whether it's an IndexError or a ValueError, and if not then do something; - print/log every exception. The first one violates "It's better to ask forgiveness than to ask permission" (and it's slow), the second one's a pain in the butt; the third one gets slow if LoL is large and has many non-standard members. Is there a fourth way? Actually, I'm asking because I've run into similar situations and been dissatisfied with my own solution. Generally, if there are two or more "acceptable" errors that you can foresee, but you still want to catch any others, what's an elegant, readable, and computationally-cheap way to do it? Maybe a dictionary of exceptions...? -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From wescpy at gmail.com Fri Jan 9 00:45:56 2009 From: wescpy at gmail.com (wesley chun) Date: Thu, 8 Jan 2009 15:45:56 -0800 Subject: [Tutor] casting string to integer in a list of lists In-Reply-To: <40af687b0901081511r5530db39kc03ce880ead73a22@mail.gmail.com> References: <21359600.post@talk.nabble.com> <40af687b0901081326l93a793mb9b0158ba7c71373@mail.gmail.com> <78b3a9580901081421q7086bakbdd2a9b54bcfd060@mail.gmail.com> <40af687b0901081511r5530db39kc03ce880ead73a22@mail.gmail.com> Message-ID: <78b3a9580901081545v6a5b89adi70afc930e53c1275@mail.gmail.com> >> except: >> pass >> >> try not to code these 2 lines in anything that you do because it will >> come back to haunt you when something is not working right but you >> can't find any errors. that's because this code masks and throws away >> everything!! > > there are two potential error types: IndexError and ValueError. I assumed that if > either one occurred, we would want to leave that particular list member (if > it exists) as-is (hence the pass). > : > - catch the exception, test to see whether it's an IndexError or a > ValueError, and if not then do something; > : as opposed to the above... except (IndexError, ValueError): pass ...is much more acceptable. there are 2 general conventions: - catch errors explicitly (as to not mask the others) and pass/ignore - catch 'em all (except Exception) and do *some*thing (not pass) both of those cases shows that you did your due diligence and that you're just not blindly throwing things away. > Generally, if there are two or more "acceptable" errors that you can foresee, > but you still want to catch any others, what's an elegant, readable, and > computationally-cheap way to do it? Maybe a dictionary of exceptions...? A tuple of exceptions works, just like what we did above, and more, i.e., (IndexError, ValueError, TypeError, KeyError... hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From alan.gauld at btinternet.com Fri Jan 9 02:18:25 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 9 Jan 2009 01:18:25 -0000 Subject: [Tutor] casting string to integer in a list of lists References: <21359600.post@talk.nabble.com> Message-ID: "culpritNr1" wrote > Say I have this nice list of lists: > > LoL = [['chrX', '160944034', '160944035', 'gnfX.145.788', '63.60'], > ['chrX', '161109992', '161109993', 'rs13484104', > '63.60'], > Now I want to cast the second and third "columns" from string to > integer, > like this > > LoL = [['chrX', 160944034, 160944035, 'gnfX.145.788', '63.60'], > ['chrX', 161109992, 161109993, 'rs13484104', '63.60'], Being picky that's not really casting that's converting. Casting is where you take the same set of binary data and treat it as if it were a different type but without changing the binary. Conversion is where you actually change the data into a new representation. Conversion is relatively easy in Python, casting is a bit more tricky. Alan G. From marc.tompkins at gmail.com Fri Jan 9 02:29:11 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 8 Jan 2009 17:29:11 -0800 Subject: [Tutor] casting string to integer in a list of lists In-Reply-To: <78b3a9580901081545v6a5b89adi70afc930e53c1275@mail.gmail.com> References: <21359600.post@talk.nabble.com> <40af687b0901081326l93a793mb9b0158ba7c71373@mail.gmail.com> <78b3a9580901081421q7086bakbdd2a9b54bcfd060@mail.gmail.com> <40af687b0901081511r5530db39kc03ce880ead73a22@mail.gmail.com> <78b3a9580901081545v6a5b89adi70afc930e53c1275@mail.gmail.com> Message-ID: <40af687b0901081729w12d8f635yc15ad30542049dc7@mail.gmail.com> On Thu, Jan 8, 2009 at 3:45 PM, wesley chun wrote: > A tuple of exceptions works, just like what we did above, and more, > i.e., (IndexError, ValueError, TypeError, KeyError... > > Thank you, thank you, thank you! I'm sure it's been staring me in the face, but I never realized I could use a tuple of exception types - that's why I said it was a pain in the butt, trapping the exception and doing "isinstance" checks against it. How did I miss this? Learn something new every day, no? -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From michael at arpsorensen.dk Fri Jan 9 09:27:19 2009 From: michael at arpsorensen.dk (=?UTF-8?Q?Michael_Bernhard_Arp_S=C3=B8rensen?=) Date: Fri, 9 Jan 2009 09:27:19 +0100 Subject: [Tutor] Python debugger Message-ID: <1618520901090027y5ac4e16fr9cafbba728748099@mail.gmail.com> Hi there. I've just started using the python debugger and I wonder how I could have lived without it earlier. I just wonder if there is a smarter way to show what all the variables contain in any given point in the debugger. I'm using this approach: import sys f = sys._getframe() p f.f_locals.items() It's not exacly pretty in its output, but it's better than nothing. Can this be done in a smarter way? -- Kind regards Michael B. Arp S?rensen Programmer / BOFH "Ride out and meet them." -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Jan 9 12:38:08 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 9 Jan 2009 06:38:08 -0500 Subject: [Tutor] Python debugger In-Reply-To: <1618520901090027y5ac4e16fr9cafbba728748099@mail.gmail.com> References: <1618520901090027y5ac4e16fr9cafbba728748099@mail.gmail.com> Message-ID: <1c2a2c590901090338w2bd9da1fo4981c55f21ff0f42@mail.gmail.com> On Fri, Jan 9, 2009 at 3:27 AM, Michael Bernhard Arp S?rensen wrote: > Hi there. > > I've just started using the python debugger and I wonder how I could have > lived without it earlier. > > I just wonder if there is a smarter way to show what all the variables > contain in any given point in the debugger. I'm using this approach: > > import sys > f = sys._getframe() > p f.f_locals.items() > > It's not exacly pretty in its output, but it's better than nothing. Can this > be done in a smarter way? 'a' will show the arguments to the current function; not the same but shorter. p locals().items() is probably the same as what you are doing. You might want to look at a graphical debugger such as winpdb. Kent From michael at arpsorensen.dk Fri Jan 9 13:36:25 2009 From: michael at arpsorensen.dk (=?UTF-8?Q?Michael_Bernhard_Arp_S=C3=B8rensen?=) Date: Fri, 9 Jan 2009 13:36:25 +0100 Subject: [Tutor] Python debugger In-Reply-To: <1c2a2c590901090338w2bd9da1fo4981c55f21ff0f42@mail.gmail.com> References: <1618520901090027y5ac4e16fr9cafbba728748099@mail.gmail.com> <1c2a2c590901090338w2bd9da1fo4981c55f21ff0f42@mail.gmail.com> Message-ID: <1618520901090436n47d9e0a6ld1f2f1ca64a787d@mail.gmail.com> Hi. Thanks for the input. Your way of doing it is simpler and possible to use as an alias in pdb. I can't use a graphical debugger because i mostly code python over ssh on remote servers in my company. Thanks anyway. It was actually helpfull. :-) /Michael On Fri, Jan 9, 2009 at 12:38 PM, Kent Johnson wrote: > On Fri, Jan 9, 2009 at 3:27 AM, Michael Bernhard Arp S?rensen > wrote: > > Hi there. > > > > I've just started using the python debugger and I wonder how I could have > > lived without it earlier. > > > > I just wonder if there is a smarter way to show what all the variables > > contain in any given point in the debugger. I'm using this approach: > > > > import sys > > f = sys._getframe() > > p f.f_locals.items() > > > > It's not exacly pretty in its output, but it's better than nothing. Can > this > > be done in a smarter way? > > 'a' will show the arguments to the current function; not the same but > shorter. > p locals().items() is probably the same as what you are doing. > > You might want to look at a graphical debugger such as winpdb. > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From T.Gkikopoulos at dundee.ac.uk Fri Jan 9 13:53:54 2009 From: T.Gkikopoulos at dundee.ac.uk (Triantafyllos Gkikopoulos) Date: Fri, 09 Jan 2009 12:53:54 +0000 Subject: [Tutor] casting string to integer in a list of lists Message-ID: <496748E2020000B30000179D@gw-out.dundee.ac.uk> Hi Your, I work with genomic datasets as well and have recently only started working with python (so my advice is a bit naive) I would say although there may be different ways you can cast an integer or float type into your list of lists you may actually no need to do so with your starting file/list... ie: if for example you want to do stuff with the location chrX with start 160944034 and end 160944035 you could: for x in LoL: startstring=LoL[1] #this would be '160944034' startint=int(startstring) #this would be 160944034 now if you also use a counter you can iterate and do all sort of calculations for different genomic locations. I use the csv module and then append into a numpy array that takes type float, so you could work with that as well, cheers Dr Triantafyllos Gkikopoulos >>> culpritNr1 01/08/09 8:42 PM >>> Hi All, Say I have this nice list of lists: LoL = [['chrX', '160944034', '160944035', 'gnfX.145.788', '63.60'], ['chrX', '161109992', '161109993', 'rs13484104', '63.60'], ['chrX', '161414112', '161414113', 'rs13484105', '63.60'], ['chrX', '161544071', '161544072', 'rs13484106', '63.60'], ['chrX', '162030736', '162030737', 'gnfX.146.867', '67.05'], ['chrX', '164171913', '164171914', 'gnfX.148.995', '70.45']] Now I want to cast the second and third "columns" from string to integer, like this LoL = [['chrX', 160944034, 160944035, 'gnfX.145.788', '63.60'], ['chrX', 161109992, 161109993, 'rs13484104', '63.60'], ['chrX', 161414112, 161414113, 'rs13484105', '63.60'], ['chrX', 161544071, 161544072, 'rs13484106', '63.60'], ['chrX', 162030736, 162030737, 'gnfX.146.867', '67.05'], ['chrX', 164171913, 164171914, 'gnfX.148.995', '70.45']] Is there any elegant way to do this? I can't assume that all lines will have the same number of elements. Thank you, Your Culprit -- View this message in context: http://www.nabble.com/casting-string-to-integer-in-a-list-of-lists-tp21359600p21359600.html Sent from the Python - tutor mailing list archive at Nabble.com. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor The University of Dundee is a registered Scottish charity, No: SC015096 From kent37 at tds.net Fri Jan 9 15:14:18 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 9 Jan 2009 09:14:18 -0500 Subject: [Tutor] Python debugger In-Reply-To: <1618520901090436n47d9e0a6ld1f2f1ca64a787d@mail.gmail.com> References: <1618520901090027y5ac4e16fr9cafbba728748099@mail.gmail.com> <1c2a2c590901090338w2bd9da1fo4981c55f21ff0f42@mail.gmail.com> <1618520901090436n47d9e0a6ld1f2f1ca64a787d@mail.gmail.com> Message-ID: <1c2a2c590901090614m65e97814gc1b6554919f7044a@mail.gmail.com> On Fri, Jan 9, 2009 at 7:36 AM, Michael Bernhard Arp S?rensen wrote: > I can't use a graphical debugger because i mostly code python over ssh on > remote servers in my company. Winpdb opens a socket connection between the debugger and debuggee. Perhaps it would run over an ssh tunnel... Kent From ig2ar-saf1 at yahoo.co.uk Fri Jan 9 15:20:26 2009 From: ig2ar-saf1 at yahoo.co.uk (culpritNr1) Date: Fri, 9 Jan 2009 06:20:26 -0800 (PST) Subject: [Tutor] casting string to integer in a list of lists In-Reply-To: <496748E2020000B30000179D@gw-out.dundee.ac.uk> References: <21359600.post@talk.nabble.com> <496748E2020000B30000179D@gw-out.dundee.ac.uk> Message-ID: <21373193.post@talk.nabble.com> Hello Trias and all, Glad to see that somebody recognized the BED genomic annotation format. Your naive approach is probably the first thing that one could try. It is sure to work. The problem is that your code becomes unnecessarily long/cumbersome: every time I would have to use a particular element I would have to cast it first. So, an alternative idea is to modify the entire list of lists and get done with once and for all. This could be done manually with a couple of FOR loops. It would be easy and somebody already provided a solution early on (thank you!). Being a relative newcomer to python, my question was if there was an ELEGANT way to do this casting, perhaps as a list comprehension operation. I wondered if the beauty of python could reach that far. I thank you all for your comments, culpritNr1 trias wrote: > > Hi Your, > > I work with genomic datasets as well and have recently only started > working with python (so my advice is a bit naive) > > I would say although there may be different ways you can cast an integer > or float type into your list of lists you may actually no need to do so > with your starting file/list... ie: > > if for example you want to do stuff with the location chrX with start > 160944034 and end 160944035 > > you could: > for x in LoL: > startstring=LoL[1] #this would be '160944034' > startint=int(startstring) #this would be 160944034 > > now if you also use a counter you can iterate and do all sort of > calculations for different genomic locations. > > I use the csv module and then append into a numpy array that takes type > float, so you could work with that as well, > > cheers > > > Dr Triantafyllos Gkikopoulos >>>> culpritNr1 01/08/09 8:42 PM >>> > > Hi All, > > Say I have this nice list of lists: > > LoL = [['chrX', '160944034', '160944035', 'gnfX.145.788', '63.60'], > ['chrX', '161109992', '161109993', 'rs13484104', '63.60'], > ['chrX', '161414112', '161414113', 'rs13484105', '63.60'], > ['chrX', '161544071', '161544072', 'rs13484106', '63.60'], > ['chrX', '162030736', '162030737', 'gnfX.146.867', '67.05'], > ['chrX', '164171913', '164171914', 'gnfX.148.995', '70.45']] > > Now I want to cast the second and third "columns" from string to integer, > like this > > LoL = [['chrX', 160944034, 160944035, 'gnfX.145.788', '63.60'], > ['chrX', 161109992, 161109993, 'rs13484104', '63.60'], > ['chrX', 161414112, 161414113, 'rs13484105', '63.60'], > ['chrX', 161544071, 161544072, 'rs13484106', '63.60'], > ['chrX', 162030736, 162030737, 'gnfX.146.867', '67.05'], > ['chrX', 164171913, 164171914, 'gnfX.148.995', '70.45']] > > Is there any elegant way to do this? I can't assume that all lines will > have > the same number of elements. > > Thank you, > > Your Culprit > > > -- > View this message in context: > http://www.nabble.com/casting-string-to-integer-in-a-list-of-lists-tp21359600p21359600.html > Sent from the Python - tutor mailing list archive at Nabble.com. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > The University of Dundee is a registered Scottish charity, No: SC015096 > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- View this message in context: http://www.nabble.com/casting-string-to-integer-in-a-list-of-lists-tp21359600p21373193.html Sent from the Python - tutor mailing list archive at Nabble.com. From denis.spir at free.fr Fri Jan 9 16:38:37 2009 From: denis.spir at free.fr (spir) Date: Fri, 9 Jan 2009 16:38:37 +0100 Subject: [Tutor] casting string to integer in a list of lists In-Reply-To: <21373193.post@talk.nabble.com> References: <21359600.post@talk.nabble.com> <496748E2020000B30000179D@gw-out.dundee.ac.uk> <21373193.post@talk.nabble.com> Message-ID: <20090109163837.46e658c8@o> Le Fri, 9 Jan 2009 06:20:26 -0800 (PST), culpritNr1 a ?crit : > > Hello Trias and all, > > Glad to see that somebody recognized the BED genomic annotation format. > Being a relative newcomer to python, my question was if there was an ELEGANT > way to do this casting, perhaps as a list comprehension operation. I > wondered if the beauty of python could reach that far. already given such a solution -- denis > > I thank you all for your comments, > > culpritNr1 > ------ la vida e estranya From dsarmientos at gmail.com Fri Jan 9 16:50:47 2009 From: dsarmientos at gmail.com (Daniel Sarmiento) Date: Fri, 9 Jan 2009 10:50:47 -0500 Subject: [Tutor] casting string to integer in a list of lists Message-ID: I am not an expert and don't know if this is considered 'elegant', but this is what I would try conv = [[j[0], int(j[1]), int(j[2])] + j[3:] for j in LoL] > Hi Your, > > I work with genomic datasets as well and have recently only started > working with python (so my advice is a bit naive) > > I would say although there may be different ways you can cast an integer > or float type into your list of lists you may actually no need to do so with > your starting file/list... ie: > > if for example you want to do stuff with the location chrX with start > 160944034 and end 160944035 > > you could: > for x in LoL: > startstring=LoL[1] #this would be '160944034' > startint=int(startstring) #this would be 160944034 > > now if you also use a counter you can iterate and do all sort of > calculations for different genomic locations. > > I use the csv module and then append into a numpy array that takes type > float, so you could work with that as well, > > cheers > > > Dr Triantafyllos Gkikopoulos > >>> culpritNr1 01/08/09 8:42 PM >>> > > Hi All, > > Say I have this nice list of lists: > > LoL = [['chrX', '160944034', '160944035', 'gnfX.145.788', '63.60'], > ['chrX', '161109992', '161109993', 'rs13484104', '63.60'], > ['chrX', '161414112', '161414113', 'rs13484105', '63.60'], > ['chrX', '161544071', '161544072', 'rs13484106', '63.60'], > ['chrX', '162030736', '162030737', 'gnfX.146.867', '67.05'], > ['chrX', '164171913', '164171914', 'gnfX.148.995', '70.45']] > > Now I want to cast the second and third "columns" from string to integer, > like this > > LoL = [['chrX', 160944034, 160944035, 'gnfX.145.788', '63.60'], > ['chrX', 161109992, 161109993, 'rs13484104', '63.60'], > ['chrX', 161414112, 161414113, 'rs13484105', '63.60'], > ['chrX', 161544071, 161544072, 'rs13484106', '63.60'], > ['chrX', 162030736, 162030737, 'gnfX.146.867', '67.05'], > ['chrX', 164171913, 164171914, 'gnfX.148.995', '70.45']] > > Is there any elegant way to do this? I can't assume that all lines will > have > the same number of elements. > > Thank you, > > Your Culprit > > > -- > View this message in context: > http://www.nabble.com/casting-string-to-integer-in-a-list-of-lists-tp21359600p21359600.html > Sent from the Python - tutor mailing list archive at Nabble.com. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > The University of Dundee is a registered Scottish charity, No: SC015096 > -------------- next part -------------- An HTML attachment was scrubbed... URL: From eduardo.susan at gmail.com Fri Jan 9 17:18:53 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Fri, 9 Jan 2009 09:18:53 -0700 Subject: [Tutor] What does OP stand for? Message-ID: <9356b9f30901090818u5e6a86ecud119df334db4883d@mail.gmail.com> Hello, I'm new to this list, and am enjoying it. I just wonder what "OP" stands for, as I have seen quite a few mentions in the python lists Thanks Edu From ig2ar-saf1 at yahoo.co.uk Fri Jan 9 17:10:27 2009 From: ig2ar-saf1 at yahoo.co.uk (culpritNr1) Date: Fri, 9 Jan 2009 08:10:27 -0800 (PST) Subject: [Tutor] casting string to integer in a list of lists In-Reply-To: <20090108225752.2977c752@o> References: <21359600.post@talk.nabble.com> <20090108225752.2977c752@o> Message-ID: <21375207.post@talk.nabble.com> Hello Denis and All, Your solution does show elegance. To remind people, it's this one: lol = [[1,2,3],[4,5,6],[7,8,9]] new_lol = [[a,b**3,c] for [a,b,c] in lol] print lol print new_lol ==> [[1, 2, 3], [4, 5, 6], [7, 8, 9]] [[1, 8, 3], [4, 125, 6], [7, 512, 9]] Now, as I said in my original post, I can't assume that all inner-lists will have the same number of elements. Common data looks like this LoL = [['chrX', '160944034', '160944035', 'gnfX.145.788', '63.60'], ['chrX', '161109992', '161109993', 'rs13484104', '63.60'], ['chrX', '161414112', '161414113', 'undetermined'], ['chrX', '161544071', '161544072', 'rs13484106', '63.60', 'RNA-BP', 'PLoS Biol 6(10): e255'], ['chrX', '162030736', '162030737', 'gnfX.146.867', '67.05'], ['chrX', '164171913', '164171914', 'gnfX.148.995', '70.45']] Do you still think that this problem can be elegantly tackled by list comprehensions? Thank you, culpritNr1 spir wrote: > > Le Thu, 8 Jan 2009 11:51:01 -0800 (PST), > culpritNr1 a ?crit : > >> >> Hi All, >> >> Say I have this nice list of lists: >> >> LoL = [['chrX', '160944034', '160944035', 'gnfX.145.788', '63.60'], >> ['chrX', '161109992', '161109993', 'rs13484104', '63.60'], >> ['chrX', '161414112', '161414113', 'rs13484105', '63.60'], >> ['chrX', '161544071', '161544072', 'rs13484106', '63.60'], >> ['chrX', '162030736', '162030737', 'gnfX.146.867', '67.05'], >> ['chrX', '164171913', '164171914', 'gnfX.148.995', '70.45']] >> >> Now I want to cast the second and third "columns" from string to integer, >> like this >> >> LoL = [['chrX', 160944034, 160944035, 'gnfX.145.788', '63.60'], >> ['chrX', 161109992, 161109993, 'rs13484104', '63.60'], >> ['chrX', 161414112, 161414113, 'rs13484105', '63.60'], >> ['chrX', 161544071, 161544072, 'rs13484106', '63.60'], >> ['chrX', 162030736, 162030737, 'gnfX.146.867', '67.05'], >> ['chrX', 164171913, 164171914, 'gnfX.148.995', '70.45']] >> >> Is there any elegant way to do this? I can't assume that all lines will >> have >> the same number of elements. > > In you do not need checking whether specific items are "castable" (i.e. > you really know what's in > the list) you may use such a pattern: > > lol = [[1,2,3],[4,5,6],[7,8,9]] > new_lol = [[a,b**3,c] for [a,b,c] in lol] > print lol > print new_lol > ==> > [[1, 2, 3], [4, 5, 6], [7, 8, 9]] > [[1, 8, 3], [4, 125, 6], [7, 512, 9]] > > denis >> Thank you, >> >> Your Culprit >> >> > > > ------ > la vida e estranya > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- View this message in context: http://www.nabble.com/casting-string-to-integer-in-a-list-of-lists-tp21359600p21375207.html Sent from the Python - tutor mailing list archive at Nabble.com. From ig2ar-saf1 at yahoo.co.uk Fri Jan 9 17:23:04 2009 From: ig2ar-saf1 at yahoo.co.uk (culpritNr1) Date: Fri, 9 Jan 2009 08:23:04 -0800 (PST) Subject: [Tutor] casting string to integer in a list of lists In-Reply-To: References: <21359600.post@talk.nabble.com> Message-ID: <21375430.post@talk.nabble.com> Thanks Daniel, That is EXACTLY what I was looking for. Actually, int() does not really work but this does: [ [line[0], eval(line[1]), eval(line[2])] + line[3:] for line in LoL] Again, thanks. culpritNr1 Daniel Sarmiento-2 wrote: > > I am not an expert and don't know if this is considered 'elegant', but > this > is what I would try > > conv = [[j[0], int(j[1]), int(j[2])] + j[3:] for j in LoL] > > >> Hi Your, >> >> I work with genomic datasets as well and have recently only started >> working with python (so my advice is a bit naive) >> >> I would say although there may be different ways you can cast an integer >> or float type into your list of lists you may actually no need to do so >> with >> your starting file/list... ie: >> >> if for example you want to do stuff with the location chrX with start >> 160944034 and end 160944035 >> >> you could: >> for x in LoL: >> startstring=LoL[1] #this would be '160944034' >> startint=int(startstring) #this would be 160944034 >> >> now if you also use a counter you can iterate and do all sort of >> calculations for different genomic locations. >> >> I use the csv module and then append into a numpy array that takes type >> float, so you could work with that as well, >> >> cheers >> >> >> Dr Triantafyllos Gkikopoulos >> >>> culpritNr1 01/08/09 8:42 PM >>> >> >> Hi All, >> >> Say I have this nice list of lists: >> >> LoL = [['chrX', '160944034', '160944035', 'gnfX.145.788', '63.60'], >> ['chrX', '161109992', '161109993', 'rs13484104', '63.60'], >> ['chrX', '161414112', '161414113', 'rs13484105', '63.60'], >> ['chrX', '161544071', '161544072', 'rs13484106', '63.60'], >> ['chrX', '162030736', '162030737', 'gnfX.146.867', '67.05'], >> ['chrX', '164171913', '164171914', 'gnfX.148.995', '70.45']] >> >> Now I want to cast the second and third "columns" from string to integer, >> like this >> >> LoL = [['chrX', 160944034, 160944035, 'gnfX.145.788', '63.60'], >> ['chrX', 161109992, 161109993, 'rs13484104', '63.60'], >> ['chrX', 161414112, 161414113, 'rs13484105', '63.60'], >> ['chrX', 161544071, 161544072, 'rs13484106', '63.60'], >> ['chrX', 162030736, 162030737, 'gnfX.146.867', '67.05'], >> ['chrX', 164171913, 164171914, 'gnfX.148.995', '70.45']] >> >> Is there any elegant way to do this? I can't assume that all lines will >> have >> the same number of elements. >> >> Thank you, >> >> Your Culprit >> >> >> -- >> View this message in context: >> http://www.nabble.com/casting-string-to-integer-in-a-list-of-lists-tp21359600p21359600.html >> Sent from the Python - tutor mailing list archive at Nabble.com. >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> The University of Dundee is a registered Scottish charity, No: SC015096 >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- View this message in context: http://www.nabble.com/casting-string-to-integer-in-a-list-of-lists-tp21359600p21375430.html Sent from the Python - tutor mailing list archive at Nabble.com. From mail at timgolden.me.uk Fri Jan 9 17:51:58 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 09 Jan 2009 16:51:58 +0000 Subject: [Tutor] What does OP stand for? In-Reply-To: <9356b9f30901090818u5e6a86ecud119df334db4883d@mail.gmail.com> References: <9356b9f30901090818u5e6a86ecud119df334db4883d@mail.gmail.com> Message-ID: <496780AE.8030302@timgolden.me.uk> Eduardo Vieira wrote: > Hello, I'm new to this list, and am enjoying it. I just wonder what > "OP" stands for, as I have seen quite a few mentions in the python > lists Original Poster - ie whoever it was who first raised the question we're discussing now. In the case of this thread, you're the OP. TJG From mail at timgolden.me.uk Fri Jan 9 17:52:17 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 09 Jan 2009 16:52:17 +0000 Subject: [Tutor] What does OP stand for? In-Reply-To: <9356b9f30901090818u5e6a86ecud119df334db4883d@mail.gmail.com> References: <9356b9f30901090818u5e6a86ecud119df334db4883d@mail.gmail.com> Message-ID: <496780C1.2060308@timgolden.me.uk> Eduardo Vieira wrote: > Hello, I'm new to this list, and am enjoying it. I just wonder what > "OP" stands for, as I have seen quite a few mentions in the python > lists Original Poster - ie whoever it was who first raised the question we're discussing now. In the case of this thread, you're the OP. TJG From kent37 at tds.net Fri Jan 9 17:57:19 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 9 Jan 2009 11:57:19 -0500 Subject: [Tutor] casting string to integer in a list of lists In-Reply-To: <21375430.post@talk.nabble.com> References: <21359600.post@talk.nabble.com> <21375430.post@talk.nabble.com> Message-ID: <1c2a2c590901090857q2214be78p11640f3fe84bf6bf@mail.gmail.com> On Fri, Jan 9, 2009 at 11:23 AM, culpritNr1 wrote: > That is EXACTLY what I was looking for. > > Actually, int() does not really work but this does: > > [ [line[0], eval(line[1]), eval(line[2])] + line[3:] for line in LoL] That's strange. What happened when you tried int() ? What version of Python are you using? Kent PS Please subscribe to the list From denis.spir at free.fr Fri Jan 9 18:30:21 2009 From: denis.spir at free.fr (spir) Date: Fri, 9 Jan 2009 18:30:21 +0100 Subject: [Tutor] casting string to integer in a list of lists In-Reply-To: <21375207.post@talk.nabble.com> References: <21359600.post@talk.nabble.com> <20090108225752.2977c752@o> <21375207.post@talk.nabble.com> Message-ID: <20090109183021.3c1c5470@o> Le Fri, 9 Jan 2009 08:10:27 -0800 (PST), culpritNr1 a ?crit : > > Hello Denis and All, > > Your solution does show elegance. To remind people, it's this one: > > lol = [[1,2,3],[4,5,6],[7,8,9]] > new_lol = [[a,b**3,c] for [a,b,c] in lol] > print lol > print new_lol > ==> > [[1, 2, 3], [4, 5, 6], [7, 8, 9]] > [[1, 8, 3], [4, 125, 6], [7, 512, 9]] > > Now, as I said in my original post, I can't assume that all inner-lists will > have the same number of elements. Common data looks like this > > LoL = [['chrX', '160944034', '160944035', 'gnfX.145.788', '63.60'], > ['chrX', '161109992', '161109993', 'rs13484104', '63.60'], > ['chrX', '161414112', '161414113', 'undetermined'], > ['chrX', '161544071', '161544072', 'rs13484106', '63.60', > 'RNA-BP', 'PLoS Biol 6(10): e255'], > ['chrX', '162030736', '162030737', 'gnfX.146.867', '67.05'], > ['chrX', '164171913', '164171914', 'gnfX.148.995', '70.45']] > > Do you still think that this problem can be elegantly tackled by list > comprehensions? The straightforward method is indeed to to loop with neccsary checks/trials embedded in loop. Now, there imo is more elegant method which is to define a custom int that integrates such tests. And then to call this custom conversion instead of built-in int. This lets open the possibility of a list comp expression. Below an example: def possible_cube(val): try: return val ** 3 except: return val lol = [[1,2,'x'],[4,'y',6],['z',8,9]] new_lol = [[possible_cube(val) for val in l] for l in lol] print lol print new_lol ==> [[1, 2, 'x'], [4, 'y', 6], ['z', 8, 9]] [[1, 8, 'x'], [64, 'y', 216], ['z', 512, 729]] This may be longer because there is a custom function call in each loop. Now, it's a question of taste and priority. denis ------ la vida e estranya From denis.spir at free.fr Fri Jan 9 18:33:22 2009 From: denis.spir at free.fr (spir) Date: Fri, 9 Jan 2009 18:33:22 +0100 Subject: [Tutor] casting string to integer in a list of lists In-Reply-To: <20090109183021.3c1c5470@o> References: <21359600.post@talk.nabble.com> <20090108225752.2977c752@o> <21375207.post@talk.nabble.com> <20090109183021.3c1c5470@o> Message-ID: <20090109183322.5bde099b@o> Forgot a "detail" > def possible_cube(val): > try: > return val ** 3 > except TypeError: > return val denis From wescpy at gmail.com Fri Jan 9 19:12:06 2009 From: wescpy at gmail.com (wesley chun) Date: Fri, 9 Jan 2009 10:12:06 -0800 Subject: [Tutor] casting string to integer in a list of lists In-Reply-To: <40af687b0901081729w12d8f635yc15ad30542049dc7@mail.gmail.com> References: <21359600.post@talk.nabble.com> <40af687b0901081326l93a793mb9b0158ba7c71373@mail.gmail.com> <78b3a9580901081421q7086bakbdd2a9b54bcfd060@mail.gmail.com> <40af687b0901081511r5530db39kc03ce880ead73a22@mail.gmail.com> <78b3a9580901081545v6a5b89adi70afc930e53c1275@mail.gmail.com> <40af687b0901081729w12d8f635yc15ad30542049dc7@mail.gmail.com> Message-ID: <78b3a9580901091012n4d150fb8o1cfe9ee00e7eb8fb@mail.gmail.com> >> A tuple of exceptions works, just like what we did above, and more, >> i.e., (IndexError, ValueError, TypeError, KeyError... >> > Thank you, thank you, thank you! I'm sure it's been staring me in the face, > but I never realized I could use a tuple of exception types - that's why I > said it was a pain in the butt, trapping the exception and doing > "isinstance" checks against it. How did I miss this? wow, you were really going out of your way. i believe the docs have some examples but cannot confirm this. > Learn something new every day, no? even i do. oh, here's something else for the OP... i forgot to mention there is a useful string method called isdigit() that you can use on the string in question. it returns True if all the chars in the string are digits, meaning that it's likely safe to call int() on it. cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From ig2ar-saf1 at yahoo.co.uk Fri Jan 9 19:24:20 2009 From: ig2ar-saf1 at yahoo.co.uk (culpritNr1) Date: Fri, 9 Jan 2009 10:24:20 -0800 (PST) Subject: [Tutor] casting string to integer in a list of lists In-Reply-To: <1c2a2c590901090857q2214be78p11640f3fe84bf6bf@mail.gmail.com> References: <21359600.post@talk.nabble.com> <21375430.post@talk.nabble.com> <1c2a2c590901090857q2214be78p11640f3fe84bf6bf@mail.gmail.com> Message-ID: <21377706.post@talk.nabble.com> Hello Kent and All, Errata: int() does work. I think that in my test code a number such as '4.5' might have slipped in and then int() protested. eval() worked in all my attempts. So, thanks Daniel Sarmiento, your solution is correct as is. By the way, when I said 'cast' I really meant 'convert'. Sorry, my badness. Thanks for pointing that out. culpritNr1 Kent Johnson wrote: > > On Fri, Jan 9, 2009 at 11:23 AM, culpritNr1 > wrote: >> That is EXACTLY what I was looking for. >> >> Actually, int() does not really work but this does: >> >> [ [line[0], eval(line[1]), eval(line[2])] + line[3:] for line in LoL] > > That's strange. What happened when you tried int() ? What version of > Python are you using? > > Kent > > PS Please subscribe to the list > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- View this message in context: http://www.nabble.com/casting-string-to-integer-in-a-list-of-lists-tp21359600p21377706.html Sent from the Python - tutor mailing list archive at Nabble.com. From vginer at gmail.com Fri Jan 9 19:41:37 2009 From: vginer at gmail.com (Vicent) Date: Fri, 9 Jan 2009 19:41:37 +0100 Subject: [Tutor] Where's Psyco now? Message-ID: <50ed08f40901091041v2602817ar6557fab2087212f1@mail.gmail.com> Hello. This is my first message to the list. In this article written in 2002 http://www.ibm.com/developerworks/library/l-psyco.html they talk about Psyco as a module that makes it possible to accelerate Python. Is it still a state-of-the-art module? I found it here also: http://pypi.python.org/pypi/psyco/1.6 Do you think it's useful, or it depends...? -- Vicent Giner-Bosch, Valencia, Spain -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Fri Jan 9 20:21:28 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 9 Jan 2009 11:21:28 -0800 Subject: [Tutor] Where's Psyco now? In-Reply-To: <50ed08f40901091041v2602817ar6557fab2087212f1@mail.gmail.com> References: <50ed08f40901091041v2602817ar6557fab2087212f1@mail.gmail.com> Message-ID: <50697b2c0901091121u523a506ei40c62d4bce5be107@mail.gmail.com> On Fri, Jan 9, 2009 at 10:41 AM, Vicent wrote: > Hello. This is my first message to the list. > > In this article written in 2002 > > http://www.ibm.com/developerworks/library/l-psyco.html > > they talk about Psyco as a module that makes it possible to accelerate > Python. > > Is it still a state-of-the-art module? > > I found it here also: http://pypi.python.org/pypi/psyco/1.6 > > Do you think it's useful, or it depends...? Its present homepage is http://psyco.sourceforge.net/ , and yes, it is still useful and fairly current. However, it should be used judiciously; only bother with it if you're having a performance problem and would otherwise be tempted to rewrite the algorithm in C. Don't casually use it as an all-purpose accelerator, as that's not what it was built for. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From phr34kc0der at gmx.co.uk Sat Jan 10 00:53:31 2009 From: phr34kc0der at gmx.co.uk (phr34kc0der) Date: Fri, 09 Jan 2009 23:53:31 +0000 Subject: [Tutor] website login Message-ID: <4967E37B.7060206@gmx.co.uk> Hi everyone, I have a python question i would like to ask. Im trying to write a script to login to a website and mirror it. I need to submit a post request to /login.php which is fine, but how can i access other pages on the site. For example data = urllib.urlencode({"username" : "myUser", "password" : "myPass"}) urllib.urlopen("http://www.example.com/login.php", data) page = urllib.urlopen("http://www.example.com/page_on_site.html") when look "page" it is just showing me login.php Thanks for any advice you can give. From jjcrump at myuw.net Sat Jan 10 00:47:38 2009 From: jjcrump at myuw.net (Jon Crump) Date: Fri, 9 Jan 2009 15:47:38 -0800 (PST) Subject: [Tutor] changing string in place Message-ID: Dear all, I've been around and around with this and can't seem to conceptualize it properly. I've got a javascript object in a text file that I'd like to treat as json so that I can import it into a python program via simplejson.loads(); however, it's not proper json because it has new Date() object declarations in it. So I thought to pre-process it by translating the dates into ISO format, but RE is making me cross-eyed. example string: s = """{"title" : "Hebertot, Normandie", "start" : new Date(1203,10,7), "description" : "Hardy's long name: Hebertot, Normandie. <br> <img src=\"document.png\" style=\"cursor: pointer\" onclick=\"SimileAjax.WindowManager.cancelPopups();show_next('tab3');pager('035'); return false\"/>pg.035: 1203-10-10 to 1203-11-18"},{"title" : "Newark-Upon-Trent, Nottinghamshire", "start" : new Date(1216,9,16), "end" : new Date(1216,9,18), "description" : "Hardy's long name: Newark-Upon-Trent, Nottinghamshire. <br> "}""" I can locate the dates with: jdate = re.compile('new Date\(\d{4},\d{1,2},\d{1,2}\)') and: jsdates = jdate.findall(s) I can get a regex pattern that groups the necessary elements: dateElems = re.compile('(\d{4}),(\d{1,2}),(\d{1,2})') But I can't seem to put the bits together with re.sub() (or str.replace() ?) in the right sort of loop. How can I return the string with _all_ the dates changed in place thus: """{"title" : "Hebertot, Normandie", "start" : "1203-11-07"... etc. instead of """{"title" : "Hebertot, Normandie", "start" : new Date(1203,10,7)... etc. (js dates are 0 indexed, so Date(1203,10,7) is Nov. 7, 1203) I'm sure this is a simple matter, but I'm just not looking at it right. Jon From mwalsh at mwalsh.org Sat Jan 10 02:15:41 2009 From: mwalsh at mwalsh.org (Martin Walsh) Date: Fri, 09 Jan 2009 19:15:41 -0600 Subject: [Tutor] changing string in place In-Reply-To: References: Message-ID: <4967F6BD.8090905@mwalsh.org> Jon Crump wrote: > Dear all, > > I've been around and around with this and can't seem to conceptualize it > properly. > > I've got a javascript object in a text file that I'd like to treat as > json so that I can import it into a python program via > simplejson.loads(); however, it's not proper json because it has new > Date() object declarations in it. So I thought to pre-process it by > translating the dates into ISO format, but RE is making me cross-eyed. > > example string: > > s = """{"title" : "Hebertot, Normandie", "start" : new Date(1203,10,7), > "description" : "Hardy's long name: Hebertot, Normandie. <br> > <img src=\"document.png\" style=\"cursor: pointer\" > onclick=\"SimileAjax.WindowManager.cancelPopups();show_next('tab3');pager('035'); > return false\"/>pg.035: 1203-10-10 to 1203-11-18"},{"title" : > "Newark-Upon-Trent, Nottinghamshire", "start" : new Date(1216,9,16), > "end" : new Date(1216,9,18), "description" : "Hardy's long name: > Newark-Upon-Trent, Nottinghamshire. <br> "}""" > > I can locate the dates with: > jdate = re.compile('new Date\(\d{4},\d{1,2},\d{1,2}\)') I think you're pretty close... # note the extra parens jdate = re.compile('new Date\((\d{4}),(\d{1,2}),(\d{1,2})\)') ... then ... print jdate.sub(r'"\1-\2-\3"', s) {"title" : "Hebertot, Normandie", "start" : "1203-10-7", "description" : "Hardy's long name: Hebertot, Normandie. <br> <img src="document.png" style="cursor: pointer" onclick="SimileAjax.WindowManager.cancelPopups();show_next('tab3');pager('035'); return false"/>pg.035: 1203-10-10 to 1203-11-18"},{"title" : "Newark-Upon-Trent, Nottinghamshire", "start" : "1216-9-16", "end" : "1216-9-18", "description" : "Hardy's long name: Newark-Upon-Trent, Nottinghamshire. <br> "} You can also use named groups which *might* help make clearer what's happening above, something like: jdate = re.compile('new Date\((?P\d{4}),(?P\d{1,2}),(?P\d{1,2})\)') print jdate.sub(r'"\g-\g-\g"', s) More info here: http://docs.python.org/library/re.html#re.sub HTH, Marty From kent37 at tds.net Sat Jan 10 03:10:36 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 9 Jan 2009 21:10:36 -0500 Subject: [Tutor] website login In-Reply-To: <4967E37B.7060206@gmx.co.uk> References: <4967E37B.7060206@gmx.co.uk> Message-ID: <1c2a2c590901091810o420dfccfl7b26b75aa59afe1a@mail.gmail.com> On Fri, Jan 9, 2009 at 6:53 PM, phr34kc0der wrote: > Hi everyone, > > I have a python question i would like to ask. > > Im trying to write a script to login to a website and mirror it. I need to > submit a post request to /login.php which is fine, but how can i access > other pages on the site. See the 'Authentication' section on this page: http://personalpages.tds.net/~kent37/kk/00010.html Kent From mwalsh at mwalsh.org Sat Jan 10 04:28:52 2009 From: mwalsh at mwalsh.org (Martin Walsh) Date: Fri, 09 Jan 2009 21:28:52 -0600 Subject: [Tutor] changing string in place In-Reply-To: <4968157F.6020108@mwalsh.org> References: <4967F6BD.8090905@mwalsh.org> <4968157F.6020108@mwalsh.org> Message-ID: <496815F4.6070405@mwalsh.org> Jon Crump wrote: > I'm still faced with the problem of the javascript months being 0 > indexed. I have to add 1 to group \2 in order to get my acurate > date-string. Obviously I can't do > > print jdate.sub(r'"\1-\2+1-\3"', s) > > because the first argument to sub() is a string. How can I act on \2 > before it's substituted for the matched string? > Ah, sorry I missed that part the first time through. The first argument to jdate.sub ('repl') can also be a function that accepts an re.match object and returns a string, so something like the following (*untested*) may be helpful: jdate = re.compile('new Date\((\d{4}),(\d{1,2}),(\d{1,2})\)') def repldate(match): y, m, d = map(int, match.groups()) return '%04d-%02d-%02d' % (y, m+1, d) print jdate.sub(repldate, s) HTH, Marty > Thanks again, > Jon From prasadaraon50 at gmail.com Sat Jan 10 12:01:49 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Sat, 10 Jan 2009 03:01:49 -0800 Subject: [Tutor] multiplication table Message-ID: <9e3fac840901100301h7c13727fwb77beda52bb86d78@mail.gmail.com> HiI tried to print multiplication table using (*args) to pass parameters.and tried to print tables side by side.But the code looks messy .Is there a better way to do it. def mtab(*arg): for x in range(1,11): print '%3d'%(x),'x','%3d'%(arg[0]),'=','%3d'%(x*arg[0]),(' '*5),\ '%3d'%(x),'x','%3d'%(arg[1]),'=','%3d'%(x*arg[1]),(' '*5),\ '%3d'%(x),'x','%3d'%(arg[2]),'=','%3d'%(x*arg[2]),(' '*5) print(('-')*10).center(78) for x in range (1,11): print '%3d'%(x),'x','%3d'%(arg[3]),'=','%3d'%(x*arg[3]),(' '*5),\ '%3d'%(x),'x','%3d'%(arg[4]),'=','%3d'%(x*arg[4]),(' '*5),\ '%3d'%(x),'x','%3d'%(arg[5]),'=','%3d'%(x*arg[5]),(' '*5) Prasad -------------- next part -------------- An HTML attachment was scrubbed... URL: From michael at arpsorensen.dk Sat Jan 10 12:56:39 2009 From: michael at arpsorensen.dk (=?UTF-8?Q?Michael_Bernhard_Arp_S=C3=B8rensen?=) Date: Sat, 10 Jan 2009 12:56:39 +0100 Subject: [Tutor] Python debugger In-Reply-To: <1c2a2c590901090614m65e97814gc1b6554919f7044a@mail.gmail.com> References: <1618520901090027y5ac4e16fr9cafbba728748099@mail.gmail.com> <1c2a2c590901090338w2bd9da1fo4981c55f21ff0f42@mail.gmail.com> <1618520901090436n47d9e0a6ld1f2f1ca64a787d@mail.gmail.com> <1c2a2c590901090614m65e97814gc1b6554919f7044a@mail.gmail.com> Message-ID: <1618520901100356i61404e5cp300425f9d86ae60f@mail.gmail.com> It might and I'll keep it in mind. However, I'm not going to ditch my linux just to get a gui debugger. After all, I do have WingIDE installed in Linux, but I wanted to be free of the GUI limitations I have when I code on a host that I connect to through a minicom on another ssh host. I do that from time to time. Thanks anyway. I got what I needed. :-) /Michael On Fri, Jan 9, 2009 at 3:14 PM, Kent Johnson wrote: > On Fri, Jan 9, 2009 at 7:36 AM, Michael Bernhard Arp S?rensen > wrote: > > > I can't use a graphical debugger because i mostly code python over ssh on > > remote servers in my company. > > Winpdb opens a socket connection between the debugger and debuggee. > Perhaps it would run over an ssh tunnel... > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jadrifter at gmail.com Sat Jan 10 13:37:11 2009 From: jadrifter at gmail.com (jadrifter) Date: Sat, 10 Jan 2009 04:37:11 -0800 Subject: [Tutor] Python debugger In-Reply-To: <1618520901100356i61404e5cp300425f9d86ae60f@mail.gmail.com> References: <1618520901090027y5ac4e16fr9cafbba728748099@mail.gmail.com> <1c2a2c590901090338w2bd9da1fo4981c55f21ff0f42@mail.gmail.com> <1618520901090436n47d9e0a6ld1f2f1ca64a787d@mail.gmail.com> <1c2a2c590901090614m65e97814gc1b6554919f7044a@mail.gmail.com> <1618520901100356i61404e5cp300425f9d86ae60f@mail.gmail.com> Message-ID: <1231591031.3077.2.camel@ltop> Despite the name I believe Winpdb is platform independent I haven't used it myself but I looked into it while following this thread. http://winpdb.org/ John Purser On Sat, 2009-01-10 at 12:56 +0100, Michael Bernhard Arp S?rensen wrote: > It might and I'll keep it in mind. > > However, I'm not going to ditch my linux just to get a gui debugger. > After all, I do have WingIDE installed in Linux, but I wanted to be > free of the GUI limitations I have when I code on a host that I > connect to through a minicom on another ssh host. I do that from time > to time. > > Thanks anyway. I got what I needed. :-) > > /Michael > > On Fri, Jan 9, 2009 at 3:14 PM, Kent Johnson wrote: > On Fri, Jan 9, 2009 at 7:36 AM, Michael Bernhard Arp S?rensen > wrote: > > > I can't use a graphical debugger because i mostly code > python over ssh on > > remote servers in my company. > > > Winpdb opens a socket connection between the debugger and > debuggee. > Perhaps it would run over an ssh tunnel... > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From fatcat1111 at gmail.com Sat Jan 10 04:15:25 2009 From: fatcat1111 at gmail.com (Justin) Date: Fri, 9 Jan 2009 19:15:25 -0800 Subject: [Tutor] Yield and recursion Message-ID: <400c5d8e0901091915g5858047cic3ee942aa8d0fa4@mail.gmail.com> Hello, I am new to Python and I'm having trouble with generators. I have built a tree (and verified that it looks good, and my left() and right() functions are correct as well), and I am able to traverse it as I would expect: def preorder(tree, index, path=[]): if index >= len(tree): return path = path + [tree[index]] print path preorder(tree, left(index), path) preorder(tree, right(index), path) preorder(tree, 0) This prints out a series of lists, each containing a subtree, as expected. E.g., [0] [1, 2] [3, 4, 5, 6] ... However when I attempt to convert preorder() to a generator and iterate over the results things don't go as planned: def preorder(tree, index, path=[]): if index >= len(tree): return path = path + [tree[index]] yield path preorder(tree, left(index), path) preorder(tree, right(index), path) for subtree in preorder(tree, 0): print subtree This results in only the first list being returned: [0] I suspect it has something to do trying to, on the second pass, yield from a generator that hasn't been created. Does that sound right? If so, what can I do? Would somebody please enlighten this poor confused dev? Thank you in advance. From sofdow at yahoo.com Sat Jan 10 06:48:51 2009 From: sofdow at yahoo.com (john dow) Date: Fri, 9 Jan 2009 21:48:51 -0800 (PST) Subject: [Tutor] How do we upload multiple files simultaneously? Message-ID: <21385206.post@talk.nabble.com> Dear All, I a newbie to python... my problem is to upload more than one file on a single go. I have an option open is using some FTP client... Is there any other methods like what mega upload uses??? thanks in advace.. regards, john -- View this message in context: http://www.nabble.com/How-do-we-upload-multiple-files-simultaneously--tp21385206p21385206.html Sent from the Python - tutor mailing list archive at Nabble.com. From sofdow at yahoo.com Sat Jan 10 07:26:39 2009 From: sofdow at yahoo.com (john dow) Date: Fri, 9 Jan 2009 22:26:39 -0800 (PST) Subject: [Tutor] How do we upload multiple files simultaneously? Message-ID: <21385206.post@talk.nabble.com> Dear All, I a newbie to python... my problem is to upload more than one file on a single go. I have an option open is using some FTP client... Is there any other methods like what mega upload uses??? thanks in advace.. regards, john -- View this message in context: http://www.nabble.com/How-do-we-upload-multiple-files-simultaneously--tp21385206p21385206.html Sent from the Python - tutor mailing list archive at Nabble.com. From kent37 at tds.net Sat Jan 10 14:07:23 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 10 Jan 2009 08:07:23 -0500 Subject: [Tutor] multiplication table In-Reply-To: <9e3fac840901100301h7c13727fwb77beda52bb86d78@mail.gmail.com> References: <9e3fac840901100301h7c13727fwb77beda52bb86d78@mail.gmail.com> Message-ID: <1c2a2c590901100507t2bf2e860v51b663bf19dd47b1@mail.gmail.com> On Sat, Jan 10, 2009 at 6:01 AM, prasad rao wrote: > Hi > I tried to print multiplication table using (*args) to pass parameters.and > tried > to print tables side by side.But the code looks messy .Is there a better way > to do it. > def mtab(*arg): > for x in range(1,11): > print '%3d'%(x),'x','%3d'%(arg[0]),'=','%3d'%(x*arg[0]),(' '*5),\ > '%3d'%(x),'x','%3d'%(arg[1]),'=','%3d'%(x*arg[1]),(' '*5),\ > '%3d'%(x),'x','%3d'%(arg[2]),'=','%3d'%(x*arg[2]),(' '*5) > print(('-')*10).center(78) > for x in range (1,11): > print '%3d'%(x),'x','%3d'%(arg[3]),'=','%3d'%(x*arg[3]),(' '*5),\ > '%3d'%(x),'x','%3d'%(arg[4]),'=','%3d'%(x*arg[4]),(' '*5),\ > '%3d'%(x),'x','%3d'%(arg[5]),'=','%3d'%(x*arg[5]),(' '*5) You have a lot of duplicated code. You can reduce the duplication by using functions and loops. The first step is to put all the print code into a function rather than repeating the same three formatting expressions over and over: def show(x, y): print '%3d'%(x),'x','%3d'%(y),'=','%3d'%(x*y),(' '*5), Then mtab() can be written like this: def mtab(*arg): for x in range(1,11): show(x, arg[0]) show(x, arg[1]) show(x, arg[2]) print print(('-')*10).center(78) for x in range (1,11): show(x, arg[3]) show(x, arg[4]) show(x, arg[5]) print Now you can see that the show() statements are still repetitive, they can be put into a loop: def mtab(*arg): for x in range(1,11): for i in range(0, 3): show(x, arg[i]) print print(('-')*10).center(78) for x in range (1,11): for i in range(3, 6): show(x, arg[i]) print This is OK except the interface is awkward; do you really want to tell it each number for the table, or would you rather give it a range of numbers? Also you can use another loop to eliminate the duplicated printing of the tables: def mtab(lower, upper): for start in range(lower, upper+1, 3): for x in range(1,11): for y in range(start, start+3): show(x, y) print print(('-')*10).center(78) mtab(1, 11) This does not give quite the same result as your original - it prints the divider after each table - and it always prints three tables per group, even if you didn't ask for it - but it is much simpler and more flexible than your original. Kent From kent37 at tds.net Sat Jan 10 14:49:10 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 10 Jan 2009 08:49:10 -0500 Subject: [Tutor] Yield and recursion In-Reply-To: <400c5d8e0901091915g5858047cic3ee942aa8d0fa4@mail.gmail.com> References: <400c5d8e0901091915g5858047cic3ee942aa8d0fa4@mail.gmail.com> Message-ID: <1c2a2c590901100549v50be3071l952aa6613859e729@mail.gmail.com> On Fri, Jan 9, 2009 at 10:15 PM, Justin wrote: > However when I attempt to convert preorder() to a generator and > iterate over the results things don't go as planned: > > def preorder(tree, index, path=[]): > if index >= len(tree): return > path = path + [tree[index]] > yield path > preorder(tree, left(index), path) > preorder(tree, right(index), path) You have to explicitly loop over and yield the results of the recursive calls; there is no automatic machinery or shortcut for this: def preorder(tree, index, path=[]): if index >= len(tree): return path = path + [tree[index]] yield path for path in preorder(tree, left(index), path): yield path for path in preorder(tree, right(index), path): yield path You may want to yield just the individual path elements, not the full path, at each step. Kent From kent37 at tds.net Sat Jan 10 14:50:30 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 10 Jan 2009 08:50:30 -0500 Subject: [Tutor] Python debugger In-Reply-To: <1231591031.3077.2.camel@ltop> References: <1618520901090027y5ac4e16fr9cafbba728748099@mail.gmail.com> <1c2a2c590901090338w2bd9da1fo4981c55f21ff0f42@mail.gmail.com> <1618520901090436n47d9e0a6ld1f2f1ca64a787d@mail.gmail.com> <1c2a2c590901090614m65e97814gc1b6554919f7044a@mail.gmail.com> <1618520901100356i61404e5cp300425f9d86ae60f@mail.gmail.com> <1231591031.3077.2.camel@ltop> Message-ID: <1c2a2c590901100550y26eac239j9871ae86ccb60769@mail.gmail.com> On Sat, Jan 10, 2009 at 7:37 AM, jadrifter wrote: > Despite the name I believe Winpdb is platform independent Yes, it is, it is windows as in GUI not windows as in Microsoft. Kent From prasadaraon50 at gmail.com Sat Jan 10 14:52:03 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Sat, 10 Jan 2009 05:52:03 -0800 Subject: [Tutor] Thanks Message-ID: <9e3fac840901100552x7c18d71al7ff70fb3f664374f@mail.gmail.com> Hello Your code is concise and neat.It will take some time for me to understand how it is doing the job. Thank you >You have a lot of duplicated code. You can reduce the duplication by >using functions and loops. >The first step is to put all the print code into a function rather >than repeating the same three formatting expressions over and over: >def show(x, y): > print '%3d'%(x),'x','%3d'%(y),'=','%3d'%(x*y),(' '*5), >Then mtab() can be written like this: >def mtab(*arg): > for x in range(1,11): show(x, arg[0]) show(x, arg[1]) show(x, arg[2]) print print(('-')*10).center(78) for x in range (1,11): show(x, arg[3]) show(x, arg[4]) show(x, arg[5]) print >Now you can see that the show() statements are still repetitive, they >can be put into a loop: >def mtab(*arg): > for x in range(1,11): for i in range(0, 3): show(x, arg[i]) print print(('-')*10).center(78) for x in range (1,11): for i in range(3, 6): show(x, arg[i]) print >This is OK except the interface is awkward; do you really want to tell >it each number for the table, or would you rather give it a range of >numbers? Also you can use another loop to eliminate the duplicated >printing of the tables: >def mtab(lower, upper): for start in range(lower, upper+1, 3): for x in range(1,11): for y in range(start, start+3): show(x, y) print print(('-')*10).center(78) >mtab(1, 11) >This does not give quite the same result as your original - it prints >the divider after each table - and it always prints three tables per >group, even if you didn't ask for it - but it is much simpler and more >flexible than your original. >Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: From ptmcg at austin.rr.com Sat Jan 10 16:32:19 2009 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 10 Jan 2009 09:32:19 -0600 Subject: [Tutor] changing string in place In-Reply-To: References: Message-ID: <1AB0672DAE1C4D5BA98D524B3D466007@AWA2> Sometimes pyparsing is less stressful than struggling with RE's typoglyphics, especially for a one-off conversion (also note handling of quoted strings - if a 'new Date(y,m,d)' occurs inside a quoted string, this script *won't* convert it): from pyparsing import nums,Word,Literal,quotedString # parse a number, return it as an int num = Word(nums).setParseAction(lambda t:int(t[0])) # format of a json 'new Date' - assign names to date fields newdate = ( Literal("new") + "Date" + '(' + num("year") + ',' + num("month") + ',' + num("day") + ')' ) # parse action to convert dates def reformatDate(t): t["month"] += 1 return '"%(year)04d-%(month)02d-%(day)02d"' % t newdate.setParseAction( reformatDate ) # do conversions - explicit parsing of quoted strings # will skip over "new Date" strings if there are any # enclosed in quotes print (quotedString | newdate).transformString(s) -- Paul From lie.1296 at gmail.com Sat Jan 10 23:19:55 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 10 Jan 2009 22:19:55 +0000 (UTC) Subject: [Tutor] How do we upload multiple files simultaneously? References: <21385206.post@talk.nabble.com> Message-ID: On Fri, 09 Jan 2009 21:48:51 -0800, john dow wrote: > Dear All, > > I a newbie to python... > > my problem is to upload more than one file on a single go. I have an > option open is using some FTP client... > You might be interested with Twisted. Alternatively you might also be interested with threading or multiprocessing and also urllib. From srilyk at gmail.com Sun Jan 11 00:13:28 2009 From: srilyk at gmail.com (W W) Date: Sat, 10 Jan 2009 17:13:28 -0600 Subject: [Tutor] How do we upload multiple files simultaneously? In-Reply-To: References: <21385206.post@talk.nabble.com> Message-ID: <333efb450901101513w5af37b18vf7b5d43e014d6ab5@mail.gmail.com> On Sat, Jan 10, 2009 at 4:19 PM, Lie Ryan wrote: > On Fri, 09 Jan 2009 21:48:51 -0800, john dow wrote: > > > Dear All, > > > > I a newbie to python... > > > > my problem is to upload more than one file on a single go. I have an > > option open is using some FTP client... > > > > You might be interested with Twisted. > > Alternatively you might also be interested with threading or > multiprocessing and also urllib. Another option would be a list of files to upload, i.e. def upload(filename): #implementation here files = ['file1.txt', 'file2.txt', 'file3.txt'] for file in files: upload(file) Of course there are various different ways you could perform that type of action, but that should point you in the right direction. HTH, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Sun Jan 11 02:57:11 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 10 Jan 2009 17:57:11 -0800 Subject: [Tutor] Working with IDLE in XP, Set Up for A New Program In-Reply-To: <556845.95820.qm@web86704.mail.ukl.yahoo.com> References: <556845.95820.qm@web86704.mail.ukl.yahoo.com> Message-ID: <496951F7.5070204@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Sun Jan 11 03:08:05 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 10 Jan 2009 18:08:05 -0800 Subject: [Tutor] Working with IDLE in XP, Set Up for A New Program In-Reply-To: <496951F7.5070204@sbcglobal.net> References: <556845.95820.qm@web86704.mail.ukl.yahoo.com> <496951F7.5070204@sbcglobal.net> Message-ID: <49695485.1010500@sbcglobal.net> An HTML attachment was scrubbed... URL: From srilyk at gmail.com Sun Jan 11 16:28:37 2009 From: srilyk at gmail.com (W W) Date: Sun, 11 Jan 2009 09:28:37 -0600 Subject: [Tutor] Working with IDLE in XP, Set Up for A New Program In-Reply-To: <49695485.1010500@sbcglobal.net> References: <556845.95820.qm@web86704.mail.ukl.yahoo.com> <496951F7.5070204@sbcglobal.net> <49695485.1010500@sbcglobal.net> Message-ID: <333efb450901110728h28b49775i4030a293d93c742d@mail.gmail.com> On Sat, Jan 10, 2009 at 8:08 PM, Wayne Watson wrote: > I immediately answered my own question by clicking on a link that took me > to a web site with the pdf; however, it looks like I installed Python 2.6. > It'll be easy to uninstall, but I don't see 2.5 -- yet. > http://www.activestate.com/store/download.aspx?prdGUID=b08b04e0-6872-4d9d-a722-7a0c2dea2758 They have python 2.5.2... something. On the right hand side, as of this message, anyway. HTH, The Other Wayne > Wayne Watson wrote: > > Hi, this is a continuation of my post from way back in August. I just > installed Pythonwin. It's showing me a window for "Dive into Python". > Apparently, it's an extensive document. How do I determine how many pages > there are, and do I print the whole thing section by section? Maybe there's > a PDF? > > ALAN GAULD wrote: > > > > Where do I get pythonwin? > > Either download the Windows extensions as linked from the > Python.org web site, or even better download and install the > Activestate.com version of Python. Its free but you must register. > It has lots of goodies and uses pythonwin as the default IDE. > I use that on all my Windows PCs. > > Alan g > > Alan Gauld wrote: > > > "Wayne Watson" wrote > > would like to know if there's an easier way to start it than what I use? I > pick on a py file, and then use the pull down menu, right-click, to select > IDLE. > > > Yes, it should be on the Start menu possibly listed as Python GUI. > > Or you can set up a shortcut to it by selecting idle.pyw in explorer and > creating a shortcut and dragging it to your desktop. > > Or you could do yourself a favour and get the Pythonwin extensions and use > Pythonwin instead. IDLE is fine for a cross platform IDE but it is ugly and > less feature rich than Pythonwin. And the pythonwin installer sets up the > menus etc for you. > > HTH > > > -- > > Wayne Watson (Watson Adventures, Prop., Nevada City, CA) > > (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) > Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "We are in a race between education and catastrophe." > ? H.G. Wells > > Web Page: > > > -- > > Wayne Watson (Watson Adventures, Prop., Nevada City, CA) > > (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time) * "What killed the electric car? Expensive batteries did." > -- Physics for Future Presidents, Richard A. Muller*** Web Page: > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.orghttp://mail.python.org/mailman/listinfo/tutor > > > -- > > Wayne Watson (Watson Adventures, Prop., Nevada City, CA) > > (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time) * "What killed the electric car? Expensive batteries did." > -- Physics for Future Presidents, Richard A. Muller*** Web Page: > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.spir at free.fr Sun Jan 11 19:11:53 2009 From: denis.spir at free.fr (spir) Date: Sun, 11 Jan 2009 19:11:53 +0100 Subject: [Tutor] indented grammar parsing Message-ID: <20090111191153.16a0b805@o> Hello, this is a rather specific question about parsing an indented grammar. I have a working implementation (presented below) that may be worth a critic review -- if you like it. First issue is: is there a way to express an indented formatfing using a common grammar language such as BNF (or regex)? If yes, how to do that? If not, what kind of formal grammar is actually such a format? Is there any standard way to express it? I have searched python's grammar for this: actually, for any compound statement, a block (= section content) is simply renamed 'suite' with no more format expression. The lexical analysis section on indentation reads: '' The indentation levels of consecutive lines are used to generate INDENT and DEDENT tokens, using a stack, as follows. Before the first line of the file is read, a single zero is pushed on the stack; this will never be popped off again. The numbers pushed on the stack will always be strictly increasing from bottom to top. At the beginning of each logical line, the line?s indentation level is compared to the top of the stack. If it is equal, nothing happens. If it is larger, it is pushed on the stack, and one INDENT token is generated. If it is smaller, it must be one of the numbers occurring on the stack; all numbers on the stack that are larger are popped off, and for each number popped off a DEDENT token is generated. At the end of the file, a DEDENT token is generated for each number remaining on the stack that is larger than zero. '' I guess from this text that python parsers have a pre-parse phase that generate the so-called INDENT and DEDENT tokens -- which are then used during actual parsing. So that a typical section looks like this for the parser: header INDENT line line line DEDENT Which is, in fact, recreating a common block start / stop format (e.g. C's {block}). Is it? Do you know whether python parsers actually do that during a kind of pre-parse phase, or whether their designers have found a way of matching indent/dedent together with the rest of the source text? Thank you, Denis ================== My trial: I have have implemented an overall parser to parse an indented grammar in the simplest (recursive) case I could specify: * no blank line, no comment * a single format of inline pattern * each indent level marked as a single (tab) char * only step 1 indentation increase To do this, I use a set of tricks. Below the grammar (using a pseudo BNF/regex format -- actually it is implemented using a custom parser generator): inline : [a..z0..9_]+ line : Indent inline NL bloc : (section | line)+ section : line IndentMore bloc IndentLess all : <= bloc> Oviously, I use 3 names starting with Indent, that are not defined. They are kinds of pseudo-patterns and all rely on an external variable that holds the current indent level and is hosted as an attribute of Indent: * Indent: matches if a proper indentation is found, meaning equal to current indent level -- advances pointer * IndentMore: matches if the actual indentation found is =level+1 -- does not advance pointer (=lookahead) -- increments current level * IndentLess: matches if the actual indentation found is Right() ''' # match indentation start_pos = pos (result,pos) = ZeroOrMore(TAB)._check(text,pos) # case proper indent decrement indent_level = pos - start_pos if indent_level < Indent.level: Indent.level -= 1 result = Result(self, None, text,start_pos,start_pos) return (result,start_pos) # (no pointer advance) # case no indent decrement (by step 1 or more) # (may also be end-of-text reached) if pos >= len(text): raise EndOfText(self, text, start_pos) message = "No proper indentation decrement:\nindent level %s --> %s"\ %(Indent.level, indent_level) raise NoMatch(self, text, start_pos, message) def _full_expr(self): return "INDENT--" Below a test text and the corresponding parse result shown in tree view: ======= 1 2 3 31 32 4 5 6 61 62 63 631 632 7 ======= ======= all line:1 line:2 section line:3 bloc line:31 line:32 line:4 line:5 section line:6 bloc line:61 line:62 section line:63 bloc line:631 line:632 line:7 ======= I first want to use this structure to parse config files written according to an recursive indented format. So that the result would be a (record) object holding properties which actually each are either a parameter or a nested sub-config, e.g.: config name : val name : val connexion name : val name : val transmission name : val name : val ------ la vida e estranya From julianpaceqb at yahoo.com Sun Jan 11 23:01:25 2009 From: julianpaceqb at yahoo.com (rev pacce) Date: Sun, 11 Jan 2009 14:01:25 -0800 (PST) Subject: [Tutor] help Message-ID: <410633.69344.qm@web62001.mail.re1.yahoo.com> I have no expierence using python. I was following a tutorial and i kept getting a syntax error. it was???>>> print "hello world!"? hello world was not coming up underneath it.. i tried to run the module but that didnt work either. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jadrifter at gmail.com Sun Jan 11 23:53:30 2009 From: jadrifter at gmail.com (jadrifter) Date: Sun, 11 Jan 2009 14:53:30 -0800 Subject: [Tutor] help In-Reply-To: <410633.69344.qm@web62001.mail.re1.yahoo.com> References: <410633.69344.qm@web62001.mail.re1.yahoo.com> Message-ID: <1231714410.6041.4.camel@ltop> On Sun, 2009-01-11 at 14:01 -0800, rev pacce wrote: > I have no expierence using python. I was following a tutorial and i > kept getting a syntax error. it was >>> print "hello world!" hello > world was not coming up underneath it.. i tried to run the module but > that didnt work either. > > _______________________________________________ Hello, Don't type the >>> into python. Just type: print "hello world!" into the interactive prompt and I think it will work for you. John From alan.gauld at btinternet.com Mon Jan 12 00:14:13 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 11 Jan 2009 23:14:13 -0000 Subject: [Tutor] help References: <410633.69344.qm@web62001.mail.re1.yahoo.com> Message-ID: "rev pacce" wrote > I have no expierence using python. > I was following a tutorial and i kept getting a syntax error. > it was >>> print "hello world!" hello world was not coming up OK, I guess that you tried typing the >>> howerver that bit should be produced by the Python interpreter. You need to have an interpreter running before you start typing for most tutorials. You can get an interpreter from your command window or console or by using one of the GUI Python tools such as IDLE or Pythonwin. Can you tell us how you are starting python? Are you getting a >>> prompt anywhere? If you are using IDLE a good place to start is here: http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From sierra_mtnview at sbcglobal.net Mon Jan 12 02:55:36 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 11 Jan 2009 17:55:36 -0800 Subject: [Tutor] Active State Python with IDLE Python 2.5 Message-ID: <496AA318.6020508@sbcglobal.net> An HTML attachment was scrubbed... URL: From brian.mathis at gmail.com Mon Jan 12 03:32:32 2009 From: brian.mathis at gmail.com (Brian Mathis) Date: Sun, 11 Jan 2009 21:32:32 -0500 Subject: [Tutor] help In-Reply-To: <183c528b0901111831t38d62342ia0386358f4fe1d2f@mail.gmail.com> References: <410633.69344.qm@web62001.mail.re1.yahoo.com> <183c528b0901111831t38d62342ia0386358f4fe1d2f@mail.gmail.com> Message-ID: <183c528b0901111832r33faba36u2523d92770a14078@mail.gmail.com> I'm also new to python, but I have another suggestion on what might be going on. If you downloaded the newly released python version 3.0, ' print "hello world" ' is a syntax error because in 3.0 the "print" command has changed into a function. The correct statement would now be: print("Hello World") including the ( ). There are other changes too, which might cause other problems in the tutorial you are using. This is might be more confusing than you want to deal with right now, so I'd recommend installing python 2.6 instead, since most tutorials will probably be written for that. Once you've got a handle on python, upgrade to 3.0. On Sun, Jan 11, 2009 at 5:01 PM, rev pacce wrote: > > I have no experience using python. I was following a tutorial and i kept getting a syntax error. it was >>> print "hello world!" hello world was not coming up underneath it.. i tried to run the module but that didn't work either. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From marco.m.petersen at gmail.com Mon Jan 12 07:31:02 2009 From: marco.m.petersen at gmail.com (Marco Petersen) Date: Mon, 12 Jan 2009 14:31:02 +0800 Subject: [Tutor] 2to3 Help? Message-ID: <496AE3A6.9050304@gmail.com> I have Python 3.0. I tried to use the 2to3 program included with the interpreter to convert some scripts for Python 2.5 to Python 3.0 ones. When I try to start it form the Python command line, it says it is a syntax error. This was the line of code: \$ 2to3 testscript.py Any help would be appreciated. Thanks - Marco From alan.gauld at btinternet.com Mon Jan 12 09:51:18 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 12 Jan 2009 08:51:18 -0000 Subject: [Tutor] Active State Python with IDLE Python 2.5 References: <496AA318.6020508@sbcglobal.net> Message-ID: "Wayne Watson" wrote > I installed "Python" 2.5 a few months ago, and decided I'd like to > try > windowpy from ActiveState. Is having both of these installed going > to > cause me trouble? Multiple versions of Python should not be a problem provided you put them in different folders. C:\python25 and C:\ASpython25 for example You will have to remember which one is the default version (ie will be used when you double click a python file for example) but you can set things up to run both. But there is little point. If you are on Windows I'd personally uninstall the vanilla version and install the ActiveState version, it has a lot more features for Windows users. Alan G. From alan.gauld at btinternet.com Mon Jan 12 09:56:04 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 12 Jan 2009 08:56:04 -0000 Subject: [Tutor] 2to3 Help? References: <496AE3A6.9050304@gmail.com> Message-ID: "Marco Petersen" wrote >I have Python 3.0. I tried to use the 2to3 program included with the >interpreter to convert some scripts for Python 2.5 to Python 3.0 >ones. > When I try to start it form the Python command line, it says it is a > syntax error. > Its always best to send us an actual cut n paste of error messages. Its not clear where the error is coming from by your desription, it could be Python (most likely) or the shell. > This was the line of code: > > \$ 2to3 testscript.py But I suspect... this will run your default python interpreter which is likely to still be your 2.5 version. THe convertion scrpt is almost certainly 3.0. So I think you will need to explicitly call the interpreter: \$ some/path/to/python3 2to3 testscript.py Actually isn't 2to3 a .py file too? ie 2to3.py? Just some guesses... I haven't got around to installing Python 3 yet. Alan G. From sierra_mtnview at sbcglobal.net Mon Jan 12 11:24:38 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 12 Jan 2009 02:24:38 -0800 Subject: [Tutor] Active State Python with IDLE Python 2.5 In-Reply-To: References: <496AA318.6020508@sbcglobal.net> Message-ID: <496B1A66.5050306@sbcglobal.net> An HTML attachment was scrubbed... URL: From kent37 at tds.net Mon Jan 12 12:40:00 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 12 Jan 2009 06:40:00 -0500 Subject: [Tutor] 2to3 Help? In-Reply-To: References: <496AE3A6.9050304@gmail.com> Message-ID: <1c2a2c590901120340n5349c27eh9fcce5e646d1aeb2@mail.gmail.com> On Mon, Jan 12, 2009 at 3:56 AM, Alan Gauld wrote: > "Marco Petersen" wrote >> This was the line of code: >> >> \$ 2to3 testscript.py > > But I suspect... > this will run your default python interpreter which is likely to still > be your 2.5 version. THe convertion scrpt is almost certainly 3.0. > So I think you will need to explicitly call the interpreter: > > \$ some/path/to/python3 2to3 testscript.py > > Actually isn't 2to3 a .py file too? ie 2to3.py? 2to3 is a python program supplied with both Python 2.6 and 3.0. It is a simple launcher that starts lib2to3.main(). It has a shebang line to invoke the interpreter that, on my Mac at least, includes the complete path. That said, I too guess that somehow the OP has a mismatch between the Python version running and the version of lib2to3 being used. I would check on what is in 2to3. Kent From vceder at canterburyschool.org Mon Jan 12 14:07:39 2009 From: vceder at canterburyschool.org (Vern Ceder) Date: Mon, 12 Jan 2009 08:07:39 -0500 Subject: [Tutor] 2to3 Help? In-Reply-To: References: Message-ID: <496B409B.5020205@canterburyschool.org> > "Marco Petersen" wrote > >> > This was the line of code: >> > >> > \$ 2to3 testscript.py > > But I suspect... > this will run your default python interpreter which is likely to still > be your 2.5 version. THe convertion scrpt is almost certainly 3.0. > So I think you will need to explicitly call the interpreter: Right - 2to3 isn't part of Python 2.5, but it is a part of 2.6 and 3.0 > > \$ some/path/to/python3 2to3 testscript.py > > Actually isn't 2to3 a .py file too? ie 2to3.py? It's a Python file, but it doesn't have the .py extension. On my system it explicitly references Python 3 as the interpreter on the she-bang line, though, so that may not be the problem. > > Just some guesses... I haven't got around to installing Python 3 yet. > > Alan G. Cheers, Vern Ceder -- This time for sure! -Bullwinkle J. Moose ----------------------------- Vern Ceder, Director of Technology Canterbury School, 3210 Smith Road, Ft Wayne, IN 46804 vceder at canterburyschool.org; 260-436-0746; FAX: 260-436-5137 From noufal at nibrahim.net.in Mon Jan 12 16:56:55 2009 From: noufal at nibrahim.net.in (Noufal Ibrahim) Date: Mon, 12 Jan 2009 21:26:55 +0530 Subject: [Tutor] Selecting first matching element from a list Message-ID: <496B6847.9080701@nibrahim.net.in> Hello everyone, What is the pythonic was of selecting the first element of a list matching some condition? I often end up using [x for x in lst if cond(x)][0] This looks bad and raises IndexError if nothing is found which is ugly too. Thanks. -- ~noufal http://nibrahim.net.in/ From bgailer at gmail.com Mon Jan 12 18:21:53 2009 From: bgailer at gmail.com (bob gailer) Date: Mon, 12 Jan 2009 12:21:53 -0500 Subject: [Tutor] Selecting first matching element from a list In-Reply-To: <496B6847.9080701@nibrahim.net.in> References: <496B6847.9080701@nibrahim.net.in> Message-ID: <496B7C31.9040104@gmail.com> Noufal Ibrahim wrote: > Hello everyone, > What is the pythonic way of selecting the first element of a > list matching some condition? > I often end up using > > [x for x in lst if cond(x)][0] > > This looks bad and raises IndexError if nothing is found which > is ugly too. 1) itertools.dropwhile(cond, lst) will return a list with the desired element first. 2) "looks bad" and "is ugly" are emotional responses. What are you feeling and wanting when you say those things? 3) You can avoid the index error: lst2 = [x for x in lst if cond(x)] if lst2: desired = lst2[0] else: deal with element not found. OR for x in lst: if cond(x): break else: deal with element not found. -- Bob Gailer Chapel Hill NC 919-636-4239 From wescpy at gmail.com Mon Jan 12 19:00:20 2009 From: wescpy at gmail.com (wesley chun) Date: Mon, 12 Jan 2009 10:00:20 -0800 Subject: [Tutor] Selecting first matching element from a list In-Reply-To: <496B7C31.9040104@gmail.com> References: <496B6847.9080701@nibrahim.net.in> <496B7C31.9040104@gmail.com> Message-ID: <78b3a9580901121000tf1eb67drc8361741429cdd59@mail.gmail.com> > 1) itertools.dropwhile(cond, lst) will return a list with the desired element first. i think in order to use this, the OP needs to invert his Boolean logic because it *drops* elements while the conditional is True. as soon as it hits False the 1st time, all remaining elements (including the one that breaks the "while) is yielded. once he flips it, a single call to next() with a try-except StopIteration will be similar to the code in your msg: results = itertools.dropwhile(invCond, lst) try: desired = results.next() except StopIteration: deal with element not found bob's 2) and 3) are spot on. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From kent37 at tds.net Mon Jan 12 19:09:08 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 12 Jan 2009 13:09:08 -0500 Subject: [Tutor] Selecting first matching element from a list In-Reply-To: <496B7C31.9040104@gmail.com> References: <496B6847.9080701@nibrahim.net.in> <496B7C31.9040104@gmail.com> Message-ID: <1c2a2c590901121009v6a7d1a67l5a653e90c2db91a8@mail.gmail.com> On Mon, Jan 12, 2009 at 12:21 PM, bob gailer wrote: > Noufal Ibrahim wrote: >> >> Hello everyone, >> What is the pythonic way of selecting the first element of a list >> matching some condition? >> I often end up using >> >> [x for x in lst if cond(x)][0] >> >> This looks bad and raises IndexError if nothing is found which is >> ugly too. > > 1) itertools.dropwhile(cond, lst) will return a list with the desired > element first. I think you mean itertools.takewhile(). Note that it returns an iterable, not a list; use next() to get the first element. You can also use a generator expression to do pretty much the same thing: (x for x in lst if cond(x)).next() This will raise StopIteration if no element meets the condition. Compared to the list comp, it has the advantage of stopping when it finds the first matching element; the list comp finds all matches. Kent From alan.gauld at freenet.co.uk Mon Jan 12 20:07:23 2009 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 12 Jan 2009 19:07:23 -0000 Subject: [Tutor] Deleting recursive folder definition Message-ID: <50C11A8B9DB748FA9E6E892067CCE014@xp> I've managed to do something incredibly stupid on my XP box. I've created a folder that is a link to itself - at least I think that's what has happened, it was a CASE tool that I was using that actually did the damage. The symptoms are that I can "infinitely" navigate down to the next level. I can also delete as many folders as I like but the top level properties still report 232 folders... Also I get error messages on the defective folder saying the filename(ie path) is too long. I've tried using Cygwin rm, I've tried renaming the folder to a shorter name., I've tried using the DOS DEL command. My last resort is to try to write a program to do it, but how? Does anyone know enough about Windows filesystem (NTFS) to know which API calls etc I would need? Or is there a better solution? I'm not even sure this approach will work since it will just recurse to inifinity too I suspect! The MSDN and Knowledge Base don't seem to offer any advice either... Any ideas? Alan G. From lawrence.wickline at gmail.com Mon Jan 12 20:46:03 2009 From: lawrence.wickline at gmail.com (Lawrence Wickline) Date: Mon, 12 Jan 2009 11:46:03 -0800 Subject: [Tutor] Deleting recursive folder definition In-Reply-To: <50C11A8B9DB748FA9E6E892067CCE014@xp> References: <50C11A8B9DB748FA9E6E892067CCE014@xp> Message-ID: <6879FE0E-C2A9-4FB9-ABCA-5B72E77F3646@gmail.com> did you try "rd /s /q" from the root directory command prompt? -L On Jan 12, 2009, at 11:07 AM, Alan Gauld wrote: > I've managed to do something incredibly stupid on my XP box. > I've created a folder that is a link to itself - at least I think > that's what has > happened, it was a CASE tool that I was using that actually did the > damage. > > The symptoms are that I can "infinitely" navigate down to the next > level. > I can also delete as many folders as I like but the top level > properties > still report 232 folders... Also I get error messages on the defective > folder saying the filename(ie path) is too long. > > I've tried using Cygwin rm, I've tried renaming the folder to a > shorter > name., I've tried using the DOS DEL command. > > My last resort is to try to write a program to do it, but how? > Does anyone know enough about Windows filesystem (NTFS) to know > which API calls etc I would need? Or is there a better solution? > I'm not even sure this approach will work since it will just recurse > to inifinity too I suspect! > > The MSDN and Knowledge Base don't seem to offer any advice either... > > Any ideas? > > Alan G. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From d.conca at gmail.com Mon Jan 12 21:23:31 2009 From: d.conca at gmail.com (Daniele) Date: Mon, 12 Jan 2009 21:23:31 +0100 Subject: [Tutor] Deleting recursive folder definition Message-ID: <537341c70901121223m1346bf60t91d5fe813905b84c@mail.gmail.com> > From: "Alan Gauld" > Date: Mon, 12 Jan 2009 19:07:23 -0000 > Subject: [Tutor] Deleting recursive folder definition > I've managed to do something incredibly stupid on my XP box. > I've created a folder that is a link to itself - at least I think that's what has > happened, it was a CASE tool that I was using that actually did the damage. > Any ideas? Hi Alan, I would try to boot from a linux live cd and remove the folder that way, also try the unlink unix command. Daniele From malaclypse2 at gmail.com Mon Jan 12 22:32:12 2009 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 12 Jan 2009 16:32:12 -0500 Subject: [Tutor] Deleting recursive folder definition In-Reply-To: <50C11A8B9DB748FA9E6E892067CCE014@xp> References: <50C11A8B9DB748FA9E6E892067CCE014@xp> Message-ID: <16651e80901121332p622f0f10o2c2c3e51e4a922dc@mail.gmail.com> On Mon, Jan 12, 2009 at 2:07 PM, Alan Gauld wrote: > I've managed to do something incredibly stupid on my XP box. > I've created a folder that is a link to itself - at least I think that's > what has > happened, it was a CASE tool that I was using that actually did the damage. Try exploring the options in fsutil.exe. Some (untested!) suggestions: fsutil.exe reparsepoint query fsutil.exe reparsepoint delete If that doesn't do the job, you probably need to figure out *exactly* what type of NTFS object you're dealing with. Some search terms that might get you started: NTFS plus one of: hard link soft link reparse point junction point There are tools out there that make dealing with some of the more exotic NTFS file-like objects easier, but I'm not too familiar with them. You'll probably need to explore some, and probably learn more about NTFS than you ever wanted to know :) -- Jerry From metolone+gmane at gmail.com Mon Jan 12 22:38:05 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Mon, 12 Jan 2009 13:38:05 -0800 Subject: [Tutor] Deleting recursive folder definition References: <50C11A8B9DB748FA9E6E892067CCE014@xp> Message-ID: "Alan Gauld" wrote in message news:50C11A8B9DB748FA9E6E892067CCE014 at xp... > I've managed to do something incredibly stupid on my XP box. > I've created a folder that is a link to itself - at least I think that's > what has > happened, it was a CASE tool that I was using that actually did the > damage. > > The symptoms are that I can "infinitely" navigate down to the next level. > I can also delete as many folders as I like but the top level properties > still report 232 folders... Also I get error messages on the defective > folder saying the filename(ie path) is too long. > > I've tried using Cygwin rm, I've tried renaming the folder to a shorter > name., I've tried using the DOS DEL command. > > My last resort is to try to write a program to do it, but how? > Does anyone know enough about Windows filesystem (NTFS) to know > which API calls etc I would need? Or is there a better solution? > I'm not even sure this approach will work since it will just recurse > to inifinity too I suspect! > > The MSDN and Knowledge Base don't seem to offer any advice either... > > Any ideas? It sounds as if you've created an "NTFS junction point." The XP Help topic shows 3 utilities that may help: Microsoft offers three utilities for creating and manipulating NTFS junction points: Linkd.exe a.. Grafts any target folder onto a Windows 2000 version of NTFS folder b.. Displays the target of an NTFS junction point c.. Deletes NTFS junction points that are created with Linkd.exe d.. Location: Microsoft Windows 2000 Resource Kit Mountvol.exe a.. Grafts the root folder of a local volume onto a Windows 2000 version of NTFS folder (or "mounts" the volume) b.. Displays the target of an NTFS junction point that is used to mount a volume c.. Lists the local file system volumes that are available for use d.. Deletes the volume mount points that are created with mountvol.exe e.. Location: Windows 2000 CD-ROM in the I386 folder Delrp.exe a.. Deletes NTFS junction points b.. Also deletes other types of reparse points, which are the entities that underlie junction points c.. Aimed primarily at developers who create reparse points d.. Location: Microsoft Windows 2000 Resource Kit Linkd or Delrp sound like what you may need. If you want to fix the problem programmatically, try looking up: DeviceIoControl FSCTL_GET_REPARSE_POINT FSCTL_DELETE_REPARSE_POINT FSCTL_SET_REPARSE_POINT -Mark -Mark From wormwood_3 at yahoo.com Mon Jan 12 22:39:30 2009 From: wormwood_3 at yahoo.com (wormwood_3) Date: Mon, 12 Jan 2009 13:39:30 -0800 (PST) Subject: [Tutor] Optional parameter passing Message-ID: <355911.66899.qm@web110805.mail.gq1.yahoo.com> Hello all, I have used *args and **kwargs to have a function accept optional parameters, but is there a lazy way to optionally pass parameters? For example, say my script can accept a number of parameters for a database connection, such as user, password, and database name. The function that makes the MySQL call has a default for user, say "root". So if the user didn't pass in a value for the user option, I don't want to pass it to the function doing the MySQL call. I don't want to have to do: if options.user: do_mysql_query(user) else: do_mysql_query() and so on for each possible option. Is there a better way? Thanks, Sam _______________________ Samuel Huckins Homepage - http://samuelhuckins.com Tech blog - http://dancingpenguinsoflight.com/ Photos - http://www.flickr.com/photos/samuelhuckins/ AIM - samushack | Gtalk - samushack | Skype - shuckins -------------- next part -------------- An HTML attachment was scrubbed... URL: From wormwood_3 at yahoo.com Mon Jan 12 22:42:42 2009 From: wormwood_3 at yahoo.com (wormwood_3) Date: Mon, 12 Jan 2009 13:42:42 -0800 (PST) Subject: [Tutor] Optional parameter passing References: <355911.66899.qm@web110805.mail.gq1.yahoo.com> Message-ID: <928792.59520.qm@web110812.mail.gq1.yahoo.com> A small correction to my code, although the point was hopefully still clear: if options.user: do_mysql_query(options.user) else: do_mysql_query() ________________________________ From: wormwood_3 To: Python Tutorlist Sent: Monday, January 12, 2009 4:39:30 PM Subject: [Tutor] Optional parameter passing Hello all, I have used *args and **kwargs to have a function accept optional parameters, but is there a lazy way to optionally pass parameters? For example, say my script can accept a number of parameters for a database connection, such as user, password, and database name. The function that makes the MySQL call has a default for user, say "root". So if the user didn't pass in a value for the user option, I don't want to pass it to the function doing the MySQL call. I don't want to have to do: if options.user: do_mysql_query(user) else: do_mysql_query() and so on for each possible option. Is there a better way? Thanks, Sam _______________________ Samuel Huckins Homepage - http://samuelhuckins.com Tech blog - http://dancingpenguinsoflight.com/ Photos - http://www.flickr.com/photos/samuelhuckins/ AIM - samushack | Gtalk - samushack | Skype - shuckins -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Mon Jan 12 23:09:31 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 12 Jan 2009 17:09:31 -0500 Subject: [Tutor] Optional parameter passing In-Reply-To: <355911.66899.qm@web110805.mail.gq1.yahoo.com> References: <355911.66899.qm@web110805.mail.gq1.yahoo.com> Message-ID: <1c2a2c590901121409o56825e5epc9cafaf73d74b6c4@mail.gmail.com> On Mon, Jan 12, 2009 at 4:39 PM, wormwood_3 wrote: > Hello all, > > I have used *args and **kwargs to have a function accept optional > parameters, but is there a lazy way to optionally pass parameters? For > example, say my script can accept a number of parameters for a database > connection, such as user, password, and database name. The function that > makes the MySQL call has a default for user, say "root". So if the user > didn't pass in a value for the user option, I don't want to pass it to the > function doing the MySQL call. I don't want to have to do: > > if options.user: > do_mysql_query(user) > else: > do_mysql_query() > > and so on for each possible option. Is there a better way? You would have to put the options into a collection, a list or dict or class. You can use *args and **kwargs at the point of call as well as in a function definition. What about having the defaults in the options object and just passing it to the function? do_mysql_query(options) or pass the options and have the function use code like user = options.user or 'root' Kent From wferguson1 at socal.rr.com Mon Jan 12 23:23:41 2009 From: wferguson1 at socal.rr.com (WM.) Date: Mon, 12 Jan 2009 14:23:41 -0800 Subject: [Tutor] HOW DO I PYTHONIZE A BASICALLY BASIC PROGRAM? Message-ID: <496BC2ED.9060007@socal.rr.com> # The natural numbers(natnum), under 1000, divisible by 3 or by 5 are to be added together. natnum = 0 num3 = 0 num5 = 0 cume = 0 # The 'and' is the 15 filter; the 'or' is the 3 or 5 filter. while natnum <= 999: num3 = natnum/3 num5 = natnum/5 if natnum - (num3 * 3) == 0 and natnum - (num5 * 5) == 0: cume = cume + natnum elif natnum - (num3 * 3) == 0 or natnum - (num5 * 5) == 0: if natnum - (num3 * 3) == 0: cume = cume + natnum elif natnum - (num5 * 5) == 0: cume = cume + natnum natnum = natnum + 1 print cume This problem was kicked around last month and I did not understand any of the scripts. So I tried to recall the BASIC ifs and loops. The project euler guys say it works, but how might it be made more Pythonic? From wormwood_3 at yahoo.com Mon Jan 12 23:34:27 2009 From: wormwood_3 at yahoo.com (wormwood_3) Date: Mon, 12 Jan 2009 14:34:27 -0800 (PST) Subject: [Tutor] Optional parameter passing References: <355911.66899.qm@web110805.mail.gq1.yahoo.com> <1c2a2c590901121409o56825e5epc9cafaf73d74b6c4@mail.gmail.com> Message-ID: <951885.2369.qm@web110814.mail.gq1.yahoo.com> You know, that's a great idea :-) Just using options I could keep my initial checks the same (e.g. making sure needed options were included by looking at options.foo) and pass it along without adding much to the query function. Thanks! _______________________ Samuel Huckins Homepage - http://samuelhuckins.com Tech blog - http://dancingpenguinsoflight.com/ Photos - http://www.flickr.com/photos/samuelhuckins/ AIM - samushack | Gtalk - samushack | Skype - shuckins ________________________________ From: Kent Johnson To: wormwood_3 Cc: Python Tutorlist Sent: Monday, January 12, 2009 5:09:31 PM Subject: Re: [Tutor] Optional parameter passing On Mon, Jan 12, 2009 at 4:39 PM, wormwood_3 wrote: > Hello all, > > I have used *args and **kwargs to have a function accept optional > parameters, but is there a lazy way to optionally pass parameters? For > example, say my script can accept a number of parameters for a database > connection, such as user, password, and database name. The function that > makes the MySQL call has a default for user, say "root". So if the user > didn't pass in a value for the user option, I don't want to pass it to the > function doing the MySQL call. I don't want to have to do: > > if options.user: > do_mysql_query(user) > else: > do_mysql_query() > > and so on for each possible option. Is there a better way? You would have to put the options into a collection, a list or dict or class. You can use *args and **kwargs at the point of call as well as in a function definition. What about having the defaults in the options object and just passing it to the function? do_mysql_query(options) or pass the options and have the function use code like user = options.user or 'root' Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: From emadnawfal at gmail.com Tue Jan 13 00:35:58 2009 From: emadnawfal at gmail.com (=?WINDOWS-1256?Q?Emad_Nawfal_(=DA=E3=C7=CF_=E4=E6=DD=E1)?=) Date: Mon, 12 Jan 2009 18:35:58 -0500 Subject: [Tutor] HOW DO I PYTHONIZE A BASICALLY BASIC PROGRAM? In-Reply-To: <496BC2ED.9060007@socal.rr.com> References: <496BC2ED.9060007@socal.rr.com> Message-ID: <652641e90901121535m4d879de0n18f9c71ef457ce70@mail.gmail.com> On Mon, Jan 12, 2009 at 5:23 PM, WM. wrote: > # The natural numbers(natnum), under 1000, divisible by 3 or by 5 are to be > added together. > natnum = 0 > num3 = 0 > num5 = 0 > cume = 0 > # The 'and' is the 15 filter; the 'or' is the 3 or 5 filter. > while natnum <= 999: > num3 = natnum/3 > num5 = natnum/5 > if natnum - (num3 * 3) == 0 and natnum - (num5 * 5) == 0: > cume = cume + natnum > elif natnum - (num3 * 3) == 0 or natnum - (num5 * 5) == 0: > if natnum - (num3 * 3) == 0: > cume = cume + natnum > elif natnum - (num5 * 5) == 0: > cume = cume + natnum > natnum = natnum + 1 > print cume > > > This problem was kicked around last month and I did not understand any of > the scripts. So I tried to recall the BASIC ifs and loops. The project > euler guys say it works, but how might it be made more Pythonic? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > I guess using a list comprehension will work >>>x = [number for number in range(1000) if number%3 ==0 or number%2 ==0] >>> sum(x) 333167 >>> -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From juryef at yahoo.com Tue Jan 13 01:49:04 2009 From: juryef at yahoo.com (Judith Flores) Date: Mon, 12 Jan 2009 16:49:04 -0800 (PST) Subject: [Tutor] Modify a dictionary using csv.DictWriter Message-ID: <410140.63636.qm@web34704.mail.mud.yahoo.com> Hello, I have been struggling a while trying to figure out how to modify a csv file using the csv.DictWriter class. Let's suppose I have the following code: import csv outfile=open('template.csv','w') # This is a pre-existing file that contains 3 variables (3 columns). The variables will (or will not) have a value each. x='new_value' writing=csv.DictWriter(outfile, fieldnames=['variable1','variable2','variable2']) data={'variable1' : x} # What I intent to do here is to overwrite whatever value exists for variable 1. There will always exist only one value per variable. writing.writerow(data) I have several questions about how DictWriter works, and I am sorry if my questions have a very obvious answer, which I am 'obviously' missing. 1. When I run the code above for the first time, the contents of the pre-existing file disappear, if I run the script a second time, now I can see the value of x. 2. The fieldnames don't appear in the csv file, only the values. 3. Is there a way to let the DictWriter know that the header of the csv file corresponds to all the fieldnames? To avoid typing all the names. As usual, thank you very much for your help. Judith From alan.gauld at btinternet.com Tue Jan 13 02:10:51 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 13 Jan 2009 01:10:51 -0000 Subject: [Tutor] Modify a dictionary using csv.DictWriter References: <410140.63636.qm@web34704.mail.mud.yahoo.com> Message-ID: "Judith Flores" wrote > I have been struggling a while trying to figure out how to modify > a csv > file using the csv.DictWriter class. Let's suppose I have the > following code: I have never used DictWriter but... > outfile=open('template.csv','w') # This is a pre-existing file Opening a file to write will create a new empty file. It will effectively delete the pre existing file! > 1. When I run the code above for the first time, the contents of the > pre-existing > file disappear, if I run the script a second time, now I can see the > value of x. Not sure why you see it on the second run but you are deleting the file with the open call. You probably need to open one file for reading and another for writing thenm at the end delete the first file (or rename it to .bak) and overwrite with the written (modified) file. > 2. The fieldnames don't appear in the csv file, only the values. > 3. Is there a way to let the DictWriter know that the header of the > csv > file corresponds to all the fieldnames? To avoid typing all the > names. I can't help with that bit, sorry. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From john at fouhy.net Tue Jan 13 02:23:37 2009 From: john at fouhy.net (John Fouhy) Date: Tue, 13 Jan 2009 14:23:37 +1300 Subject: [Tutor] Modify a dictionary using csv.DictWriter In-Reply-To: <410140.63636.qm@web34704.mail.mud.yahoo.com> References: <410140.63636.qm@web34704.mail.mud.yahoo.com> Message-ID: <5e58f2e40901121723o34cd59e1v42497dd31ccaff@mail.gmail.com> 2009/1/13 Judith Flores : > Hello, Hi Judith, > 1. When I run the code above for the first time, the contents of the pre-existing file disappear, if I > run the script a second time, now I can see the value of x. This is a consequence of this line: > outfile=open('template.csv','w') # This is a pre-existing file that contains 3 variables (3 In python (and most programming languages), if you open a file for writing (mode 'w'), you automatically get a new, empty file. Any existing file with the same name is lost. If you want to add records to the end of the file, you can open in append mode ('a'). See the python library documentation for "Built-in Functions" for more. (the docs also mention mode 'a+', which is for "updating". I confess that I do not know the difference between 'a' and 'a+' (or 'w' and 'w+' for that matter)) If you want to modify rows in a csv file, your only option is: 1. Read the csv file into a python data structure. 2. Make the appropriate changes. 3. Write all the data out to a new csv file. CSV files aren't really intended as mutable data stores. If this is what you want, perhaps the shelve module would work better for you (it's like a dict, but on disk), or even a relational database such as sqlite3 (included with python 2.5 and up). > 2. The fieldnames don't appear in the csv file, only the values. I don't think the csv module will write a header row. However, it is easy enough to do yourself: just: fieldnames = ['variable1', 'variable2', 'variable3'] outfile.write(','.join(fieldnames) + '\n') > 3. Is there a way to let the DictWriter know that the header of the csv file corresponds to all the > fieldnames? To avoid typing all the names. If you read in the csv file using DictReader, you should have access to the field names as keys of the dictionaries (although possibly not in the same order). Alternatively, just type them out once and give them a name: fieldnames = ['variable1', 'variable2', 'variable3'] After all, your program should probably know what your data looks like :-) HTH. -- John. From bgailer at gmail.com Tue Jan 13 03:20:10 2009 From: bgailer at gmail.com (bob gailer) Date: Mon, 12 Jan 2009 21:20:10 -0500 Subject: [Tutor] HOW DO I PYTHONIZE A BASICALLY BASIC PROGRAM? In-Reply-To: <496BC2ED.9060007@socal.rr.com> References: <496BC2ED.9060007@socal.rr.com> Message-ID: <496BFA5A.7070101@gmail.com> WM. wrote: > # The natural numbers(natnum), under 1000, divisible by 3 or by 5 are > to be added together. > natnum = 0 > num3 = 0 > num5 = 0 > cume = 0 > # The 'and' is the 15 filter; the 'or' is the 3 or 5 filter. > while natnum <= 999: > num3 = natnum/3 > num5 = natnum/5 > if natnum - (num3 * 3) == 0 and natnum - (num5 * 5) == 0: > cume = cume + natnum > elif natnum - (num3 * 3) == 0 or natnum - (num5 * 5) == 0: > if natnum - (num3 * 3) == 0: > cume = cume + natnum > elif natnum - (num5 * 5) == 0: > cume = cume + natnum > natnum = natnum + 1 > print cume > My head hurts trying to follow all that logic and expressions. That is a sign of too much code. Let's simplify: 1) no need to initialize num3 or num5 2) replace while with for 3a) replace natnum - (num3 * 3) == 0 with natnum == (num3 * 3) 3b) replact that with not (natnum % 3) 4) use += and -= for natnum in range(1000): if not (natnum % 3 or natnum % 5): # adds 1 if divisible by 3 and/or 5 cume += 1 if not natnum % 15: # remove one of the ones if divisible by 15 cume -= 1 Since the result of not is True (1) or False (0) one can also write cume += not (natnum % 3 or natnum % 5) cume 1= not (natnum % 15) An alternative: for natnum in range(1000): if not natnum % 15: pass elif not (natnum % 3 or natnum % 5): # adds 1 if divisible by 3 or 5 cume += 1 > > This problem was kicked around last month and I did not understand any > of the scripts. That's really unfortunate. Would you for your learning take one of them, tell us what if any parts of it you understand and let us nudge you toward more understanding. -- Bob Gailer Chapel Hill NC 919-636-4239 From s4027340 at student.uq.edu.au Tue Jan 13 05:28:30 2009 From: s4027340 at student.uq.edu.au (Mr Gerard Kelly) Date: Tue, 13 Jan 2009 14:28:30 +1000 Subject: [Tutor] A list of input arguments Message-ID: I have a problem with understanding how lists, strings, tuples, number types and input arguments all interact with each other. I have this program, in which I can use the *a structure to input unlimited arguments. As an example, if I use three arguments, it looks like this: def main(): #Play a chord pygame.mixer.pre_init(sample_rate, -16, 1) # 44.1kHz, 16-bit signed, mono pygame.init() play_for(waves(440,550,660), 5000) In that final line, I would like to be able to define the input arguments on a different line (I'm hoping to eventually make a Tkinter entry box), but when I try to do this: def main(): #Play a chord pygame.mixer.pre_init(sample_rate, -16, 1) # 44.1kHz, 16-bit signed, mono pygame.init() chord=[440,550,660] play_for(waves(chord), 5000) it doesn't work. It doesn't work with a string or a tuple either. The problem is that another part of the code needs to take float(chord[0]), that is convert the first input value into the float class, and the error message says "TypeError: float() argument must be a string or a number." This is fine when the elements of *chord are listed inside the function's parentheses, but it doesn't work if they're listed outside. Is there any way to list the input arguments without listing them inside the function's parentheses? Thanks. From alan.gauld at btinternet.com Tue Jan 13 10:16:58 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 13 Jan 2009 09:16:58 -0000 Subject: [Tutor] A list of input arguments References: Message-ID: "Mr Gerard Kelly" wrote >I have a problem with understanding how lists, strings, tuples, >number > types and input arguments all interact with each other. OK, they are all different types. Some of them take a single value (sometimes known as a scalar type) and others take a collection of values (sometimes known as a sequence). Strings are unusual in that they can be considered as a scalar type or as a collection of characters! Input parameters are simply local variables for the function to which they are attached. Other than the fact that you can assign them values from outside the function whe you call it they act just like normal variables. def f(): print x x = 42 f() Is the same (almost)) as def f(x): print x > As an example, if I use three arguments, it looks like this: > > def main(): > play_for(waves(440,550,660), 5000) > def main(): > chord=[440,550,660] > play_for(waves(chord), 5000) > > it doesn't work. Because you are passing a single value (a list) into a function that expects 3 values. > It doesn't work with a string or a tuple either. Because strings and tuples are also single (container )entities You must unpack your collection when calling the function: play_for(waves(chord[0],chord[1],chord[2]),5000) > The problem is that another part of the code needs to take > float(chord[0]), that is convert the first input value into the > float > class, and the error message says "TypeError: float() argument must > be a > string or a number." Thats right, and as you did above you must extract the first element since the code can't tell that yopu have passed it a collection instead of a number! > Is there any way to list the input arguments without listing them > inside > the function's parentheses? No, because the function expects 3 arguments so you must pass it 3. That is the contract (or interface) that exists betweeen the writer of the function and you the consumer of it. Programming. particularly on larger projects with multiple teams, is all about defining interfaces and adhering to them! If you want thebenefit of the function you must respect its contract. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From s4027340 at student.uq.edu.au Tue Jan 13 12:32:52 2009 From: s4027340 at student.uq.edu.au (Mr Gerard Kelly) Date: Tue, 13 Jan 2009 21:32:52 +1000 Subject: [Tutor] A list of input arguments Message-ID: <9c0be977ab.977ab9c0be@uq.edu.au> Many thanks for your helpful answer Alan. My only other question is, does there exist a convenient way to unpack a collection of variable length? If you know that there are 3 elements in the collection, you can specify: play_for(waves(chord[0],chord[1],chord[2]),500) But then if you want to change the number of elements in the list "chord", say from 3 to 5, you have to change the code accordingly. Is there some sort of way to instruct the code to unpack its elements for any number of elements? Like i=len(chord) play_for(waves(chord[0],chord[1],...,chord[i-1]),500) If there is a way to do this it would be great! ----- Original Message ----- From: Alan Gauld Date: Tuesday, January 13, 2009 7:16 pm Subject: Re: [Tutor] A list of input arguments > "Mr Gerard Kelly" wrote > > >I have a problem with understanding how lists, strings, tuples, > >number > > types and input arguments all interact with each other. > > OK, they are all different types. Some of them take a single value > (sometimes known as a scalar type) and others take a collection > of values (sometimes known as a sequence). Strings are unusual > in that they can be considered as a scalar type or as a collection > of characters! > > Input parameters are simply local variables for the function to > which they are attached. Other than the fact that you can assign > them values from outside the function whe you call it they act just > like normal variables. > > def f(): > print x > > x = 42 > f() > > Is the same (almost)) as > > def f(x): > print x > > > As an example, if I use three arguments, it looks like this: > > > > def main(): > > play_for(waves(440,550,660), 5000) > > > > def main(): > > chord=[440,550,660] > > play_for(waves(chord), 5000) > > > > it doesn't work. > > Because you are passing a single value (a list) into a function that > expects 3 values. > > > It doesn't work with a string or a tuple either. > > Because strings and tuples are also single (container )entities > > You must unpack your collection when calling the function: > > play_for(waves(chord[0],chord[1],chord[2]),5000) > > > The problem is that another part of the code needs to take > > float(chord[0]), that is convert the first input value into the > > float > > class, and the error message says "TypeError: float() argument > must > > be a > > string or a number." > > Thats right, and as you did above you must extract the first element > since the code can't tell that yopu have passed it a collection > instead > of a number! > > > Is there any way to list the input arguments without listing them > > inside > > the function's parentheses? > > No, because the function expects 3 arguments so you must pass it 3. > That is the contract (or interface) that exists betweeen the writer > of > the > function and you the consumer of it. Programming. particularly on > larger projects with multiple teams, is all about defining interfaces > and adhering to them! If you want thebenefit of the function you must > respect its contract. > > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Tue Jan 13 12:38:41 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 13 Jan 2009 06:38:41 -0500 Subject: [Tutor] HOW DO I PYTHONIZE A BASICALLY BASIC PROGRAM? In-Reply-To: <496BFA5A.7070101@gmail.com> References: <496BC2ED.9060007@socal.rr.com> <496BFA5A.7070101@gmail.com> Message-ID: <1c2a2c590901130338v6a9427dep72681213eae246a5@mail.gmail.com> On Mon, Jan 12, 2009 at 9:20 PM, bob gailer wrote: > for natnum in range(1000): > if not (natnum % 3 or natnum % 5): # adds 1 if divisible by 3 and/or 5 > cume += 1 > if not natnum % 15: # remove one of the ones if divisible by 15 > cume -= 1 This subtraction is not needed because the multiples of 15 are not double-counted. The 'or' condition counts multiples of 15 just once. Kent From kent37 at tds.net Tue Jan 13 12:42:40 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 13 Jan 2009 06:42:40 -0500 Subject: [Tutor] A list of input arguments In-Reply-To: References: Message-ID: <1c2a2c590901130342r195dbcfuf616d3f1cfd0936c@mail.gmail.com> On Tue, Jan 13, 2009 at 4:16 AM, Alan Gauld wrote: > "Mr Gerard Kelly" wrote >> Is there any way to list the input arguments without listing them inside >> the function's parentheses? > > No, because the function expects 3 arguments so you must pass it 3. > That is the contract (or interface) that exists betweeen the writer of the > function and you the consumer of it. Programming. particularly on > larger projects with multiple teams, is all about defining interfaces > and adhering to them! If you want thebenefit of the function you must > respect its contract. You can use *args to pass multiple arguments in a list. For example, In [1]: def show(a, b, c): ...: print a, b, c In [2]: values = [1, 2, 3] In [3]: show(*values) 1 2 3 Kent From kent37 at tds.net Tue Jan 13 13:42:11 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 13 Jan 2009 07:42:11 -0500 Subject: [Tutor] A list of input arguments In-Reply-To: <9c0be977ab.977ab9c0be@uq.edu.au> References: <9c0be977ab.977ab9c0be@uq.edu.au> Message-ID: <1c2a2c590901130442p28bd1565u7ca8a5c36eedf1ab@mail.gmail.com> On Tue, Jan 13, 2009 at 6:32 AM, Mr Gerard Kelly wrote: > My only other question is, does there exist a convenient way to unpack a > collection of variable length? > > If you know that there are 3 elements in the collection, you can specify: > > play_for(waves(chord[0],chord[1],chord[2]),500) > > But then if you want to change the number of elements in the list > "chord", say from 3 to 5, you have to change the code accordingly. Is > there some sort of way to instruct the code to unpack its elements for > any number of elements? > > Like > i=len(chord) > play_for(waves(chord[0],chord[1],...,chord[i-1]),500) Presuming that waves() is defined to take an arbitrary number of arguments, e.g. def waves(*args) you can use play_for(waves(*chord), 500) to call it with a variable number of arguments. Kent From denis.spir at free.fr Tue Jan 13 13:50:49 2009 From: denis.spir at free.fr (spir) Date: Tue, 13 Jan 2009 13:50:49 +0100 Subject: [Tutor] traceback Message-ID: <20090113135049.3e1c11e3@o> Hello, is there a way to read an exception's traceback? Cannot find it in object attributes. [dir() shows no traceback, __dict__ is empty.] t = "a" try: print t[1] except IndexError, e: print e print repr(e) print dir(e) print e. __dict__ print e.args print e.message raise ==> string index out of range IndexError('string index out of range',) ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__getitem__', '__getslice__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__str__', 'args', 'message'] {} ('string index out of range',) string index out of range Traceback (most recent call last): File "___test__.py", line 10, in print t[1] IndexError: string index out of range Denis ------ la vida e estranya From a.t.hofkamp at tue.nl Tue Jan 13 13:55:03 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Tue, 13 Jan 2009 13:55:03 +0100 Subject: [Tutor] traceback In-Reply-To: <20090113135049.3e1c11e3@o> References: <20090113135049.3e1c11e3@o> Message-ID: <496C8F27.9010301@tue.nl> spir wrote: > Hello, > > is there a way to read an exception's traceback? Cannot find it in object attributes. [dir() > shows no traceback, __dict__ is empty.] You should be able to do that with the traceback module. Sincerely, Albert From ji_zhiqiang at 163.com Tue Jan 13 14:42:06 2009 From: ji_zhiqiang at 163.com (jzq) Date: Tue, 13 Jan 2009 21:42:06 +0800 Subject: [Tutor] Python and Abaqus In-Reply-To: <452123.29963.qm@web53903.mail.re2.yahoo.com> Message-ID: <1231854126.31108.3.camel@jzq-laptop> hi,I need your help. Could you give me some examples about the using of python in abaqus? Thanks a lot. From kent37 at tds.net Tue Jan 13 15:21:36 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 13 Jan 2009 09:21:36 -0500 Subject: [Tutor] Python and Abaqus In-Reply-To: <1231854126.31108.3.camel@jzq-laptop> References: <452123.29963.qm@web53903.mail.re2.yahoo.com> <1231854126.31108.3.camel@jzq-laptop> Message-ID: <1c2a2c590901130621y20f0617dq590749c02cbe5d3f@mail.gmail.com> On Tue, Jan 13, 2009 at 8:42 AM, jzq wrote: > hi,I need your help. > Could you give me some examples about the using of python in abaqus? > Thanks a lot. I'm not sure there is anyone on this list who knows abaqus, previous questions have come up pretty dry. We can help with the python part... Googling 'python abaqus' might give a little help. Kent From frenc1z at gmail.com Tue Jan 13 17:45:38 2009 From: frenc1z at gmail.com (frenc1z 1z) Date: Tue, 13 Jan 2009 17:45:38 +0100 Subject: [Tutor] Date comparison across time zones Message-ID: <7b60d8a80901130845s30842deeuba55afec99285a5c@mail.gmail.com> Hello, I'm a novice python (python 2.6.1) user with the following problem. Never though this was going to be so difficult :-). I would like to compare some dates (date+time really). The dates all have the following RFC2822 format: Eg. is d1 < d2? d1 = "Tue, 13 Jan 2009 03:27:29 -0800" d2 = "Tue, 13 Jan 2009 02:40:00 -0600" My thinking is that I first need to make these two dates comparable, and eliminate the impact of time zone and dst. Understand that I can acheive this using strptime. Been trying to parse these dates as follows: print datetime.strptime("Tue, 13 Jan 2009 02:40:00 -0800", "%a, %d %b %Y %H:%M:%S %z"). I get the following error on the conversion "ValueError: 'z' is a bad directive in format '%a, %d %b %Y %H:%M:%S %z'". >From what I have read, I understand that python 2.6 would support the %z directive, so I do not really understand the error. Apart from that, how can I best attach this problem? At first sight it would seem trivial, but unfortunately I can't build on sufficient experience in python to get to a solution. Many thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Jan 13 19:01:02 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 13 Jan 2009 13:01:02 -0500 Subject: [Tutor] Date comparison across time zones In-Reply-To: <7b60d8a80901130845s30842deeuba55afec99285a5c@mail.gmail.com> References: <7b60d8a80901130845s30842deeuba55afec99285a5c@mail.gmail.com> Message-ID: <1c2a2c590901131001p90c778kb7d4c87d6d31d49@mail.gmail.com> On Tue, Jan 13, 2009 at 11:45 AM, frenc1z 1z wrote: > I would like to compare some dates (date+time really). The dates all have > the following RFC2822 format: > > Eg. is d1 < d2? > d1 = "Tue, 13 Jan 2009 03:27:29 -0800" > d2 = "Tue, 13 Jan 2009 02:40:00 -0600" > > Been trying to parse these dates as follows: print datetime.strptime("Tue, > 13 Jan 2009 02:40:00 -0800", "%a, %d %b %Y %H:%M:%S %z"). > > I get the following error on the conversion "ValueError: 'z' is a bad > directive in format '%a, %d %b %Y %H:%M:%S %z'". The correct format code is %Z (upper case). However that still doesn't work, I don't have a complete solution for you. In [8]: datetime.strptime("Tue, 13 Jan 2009 02:40:00 EST", "%a, %d %b %Y %H:%M:%S %Z") --------------------------------------------------------------------------- ValueError Traceback (most recent call last) C:\Project\Play\ in () C:\Python25\lib\_strptime.py in strptime(data_string, format) 328 if not found: 329 raise ValueError("time data did not match format: data=%s fmt=%s" % --> 330 (data_string, format)) 331 if len(data_string) != found.end(): 332 raise ValueError("unconverted data remains: %s" % ValueError: time data did not match format: data=Tue, 13 Jan 2009 02:40:00 EST fmt=%a, %d %b %Y %H:%M:%S %Z Kent From ig2ar-saf1 at yahoo.co.uk Tue Jan 13 19:19:03 2009 From: ig2ar-saf1 at yahoo.co.uk (culpritNr1) Date: Tue, 13 Jan 2009 10:19:03 -0800 (PST) Subject: [Tutor] power of 2.718282 Message-ID: <21441385.post@talk.nabble.com> Hello All, It such a simple question, but because of that, googling for an answer just pulls the wrong results. How do I compute a power of e in Python? Say I need 2.718282 to the 10th. In R for example, I just do exp(10). I would appreciate a low level solution because I have to iteratively call that computation millions of times. Anything more efficient than 2.718182**10 may be good. Thank you, culpritNr1 -- View this message in context: http://www.nabble.com/power-of-2.718282-tp21441385p21441385.html Sent from the Python - tutor mailing list archive at Nabble.com. From marc.tompkins at gmail.com Tue Jan 13 19:25:16 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 13 Jan 2009 10:25:16 -0800 Subject: [Tutor] power of 2.718282 In-Reply-To: <21441385.post@talk.nabble.com> References: <21441385.post@talk.nabble.com> Message-ID: <40af687b0901131025k26fd0773g9b5a5f2917e5be6d@mail.gmail.com> On Tue, Jan 13, 2009 at 10:19 AM, culpritNr1 wrote: > > How do I compute a power of e in Python? > > Say I need 2.718282 to the 10th. In R for example, I just do exp(10). > > I would appreciate a low level solution because I have to iteratively call > that computation millions of times. Anything more efficient than > 2.718182**10 may be good. > Import the "math" module. From the 2.6 docs: Power and logarithmic functions > > math.exp(x) > Return e**x. > > math.log(x[, base]) > Return the logarithm of x to the given base. If the base is not specified, > return the natural logarithm of x (that is, the logarithm to base e). > Changed in version 2.3: base argument added. > > math.log1p(x) > Return the natural logarithm of 1+x (base e). The result is calculated in > a way which is accurate for x near zero. > New in version 2.6. > > math.log10(x) > Return the base-10 logarithm of x. > > math.pow(x, y) > Return x raised to the power y. Exceptional cases follow Annex 'F' of the > C99 standard as far as possible. In particular, pow(1.0, x) and pow(x, 0.0) > always return 1.0, even when x is a zero or a NaN. If both x and y are > finite, x is negative, and y is not an integer then pow(x, y) is undefined, > and raises ValueError. > Changed in version 2.6: The outcome of 1**nan and nan**0 was undefined. > > math.sqrt(x) > Return the square root of x. > -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Jan 13 19:33:53 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 13 Jan 2009 13:33:53 -0500 Subject: [Tutor] power of 2.718282 In-Reply-To: <21441385.post@talk.nabble.com> References: <21441385.post@talk.nabble.com> Message-ID: <1c2a2c590901131033l594f5860ia76c060ed3c0b55@mail.gmail.com> On Tue, Jan 13, 2009 at 1:19 PM, culpritNr1 wrote: > > Hello All, > > It such a simple question, but because of that, googling for an answer just > pulls the wrong results. > > How do I compute a power of e in Python? > > Say I need 2.718282 to the 10th. In R for example, I just do exp(10). import math math.exp(10) http://docs.python.org/library/math.html#math.exp Kent From ig2ar-saf1 at yahoo.co.uk Tue Jan 13 19:38:36 2009 From: ig2ar-saf1 at yahoo.co.uk (culpritNr1) Date: Tue, 13 Jan 2009 10:38:36 -0800 (PST) Subject: [Tutor] power of 2.718282 In-Reply-To: <1c2a2c590901131033l594f5860ia76c060ed3c0b55@mail.gmail.com> References: <21441385.post@talk.nabble.com> <1c2a2c590901131033l594f5860ia76c060ed3c0b55@mail.gmail.com> Message-ID: <21441787.post@talk.nabble.com> Thanks Marc and Kent and all. math.exp() is what I was looking for. culpritNr1 -- View this message in context: http://www.nabble.com/power-of-2.718282-tp21441385p21441787.html Sent from the Python - tutor mailing list archive at Nabble.com. From adam.jtm30 at gmail.com Tue Jan 13 20:11:15 2009 From: adam.jtm30 at gmail.com (Adam Bark) Date: Tue, 13 Jan 2009 19:11:15 +0000 Subject: [Tutor] power of 2.718282 In-Reply-To: <21441787.post@talk.nabble.com> References: <21441385.post@talk.nabble.com> <1c2a2c590901131033l594f5860ia76c060ed3c0b55@mail.gmail.com> <21441787.post@talk.nabble.com> Message-ID: According to a quick interactive session and the timeit module it's quicker to do 2.71828**10 than using math.exp, I'm guessing cos of the function call. >>> t=timeit.Timer("2.718282**10") >>> t.repeat() [0.073765993118286133, 0.066617012023925781, 0.06807398796081543] >>> t=timeit.Timer("math.exp(10)", "import math") >>> t.repeat() [0.42525100708007812, 0.43169903755187988, 0.4239799976348877] >>> t=timeit.Timer("exp(10)", "from math import exp") >>> t.repeat() [0.36061406135559082, 0.36182284355163574, 0.35887718200683594] 2009/1/13 culpritNr1 > > Thanks Marc and Kent and all. math.exp() is what I was looking for. > > culpritNr1 > > > -- > View this message in context: > http://www.nabble.com/power-of-2.718282-tp21441385p21441787.html > Sent from the Python - tutor mailing list archive at Nabble.com. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mwalsh at mwalsh.org Tue Jan 13 20:18:21 2009 From: mwalsh at mwalsh.org (Martin Walsh) Date: Tue, 13 Jan 2009 13:18:21 -0600 Subject: [Tutor] Date comparison across time zones In-Reply-To: <7b60d8a80901130845s30842deeuba55afec99285a5c@mail.gmail.com> References: <7b60d8a80901130845s30842deeuba55afec99285a5c@mail.gmail.com> Message-ID: <496CE8FD.1000908@mwalsh.org> frenc1z 1z wrote: > Hello, > I would like to compare some dates (date+time really). The dates all > have the following RFC2822 format: > > Eg. is d1 < d2? > d1 = "Tue, 13 Jan 2009 03:27:29 -0800" > d2 = "Tue, 13 Jan 2009 02:40:00 -0600" > > My thinking is that I first need to make these two dates comparable, and > eliminate the impact of time zone and dst. Understand that I can acheive > this using strptime. > > Been trying to parse these dates as follows: print > datetime.strptime("Tue, 13 Jan 2009 02:40:00 -0800", "%a, %d %b %Y > %H:%M:%S %z"). > > I get the following error on the conversion "ValueError: 'z' is a bad > directive in format '%a, %d %b %Y %H:%M:%S %z'". > I'm not sure how one would accomplish this with only the stdlib, but there are at least two 3rd party modules which you may find useful. dateutil: http://labix.org/python-dateutil mx.DateTime: http://www.egenix.com/products/python/mxBase/mxDateTime/ Each of these implement a timezone aware date-string parser, here is an (untested) example or two: d1 = "Tue, 13 Jan 2009 03:27:29 -0800" d2 = "Tue, 13 Jan 2009 02:40:00 -0600" from dateutil import parser dparser = parser.parser() p1 = dparser.parse(d1) p2 = dparser.parse(d2) print p1 < p2 from mx.DateTime import DateTimeFrom m1 = DateTimeFrom(d1) m2 = DateTimeFrom(d2) print m1 < m2 HTH, Marty From emadnawfal at gmail.com Tue Jan 13 21:14:09 2009 From: emadnawfal at gmail.com (=?WINDOWS-1256?Q?Emad_Nawfal_(=DA=E3=C7=CF_=E4=E6=DD=E1)?=) Date: Tue, 13 Jan 2009 15:14:09 -0500 Subject: [Tutor] python3.0 and tkinter on ubuntu 8.10 Message-ID: <652641e90901131214l3a1f8a2bkfc91217f15c0da0d@mail.gmail.com> Hi Tutors,I have downloaded Python3.0 and started playing with it. I like it because of the utf-8 default encoding, but I'm having trouble importing tkinter. I get the following: >>> import turtle Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python3.0/turtle.py", line 107, in import tkinter as TK File "/usr/local/lib/python3.0/tkinter/__init__.py", line 39, in import _tkinter # If this fails your Python may not be configured for Tk ImportError: No module named _tkinter >>> import tkinter Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python3.0/tkinter/__init__.py", line 39, in import _tkinter # If this fails your Python may not be configured for Tk ImportError: No module named _tkinter >>> Any idea how this can be solved on Ubuntu 8.10. I don't have this problem with the default Python installation (2.5.2) Thank you -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From bermanrl at cfl.rr.com Tue Jan 13 21:30:06 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Tue, 13 Jan 2009 15:30:06 -0500 Subject: [Tutor] python3.0 and tkinter on ubuntu 8.10 In-Reply-To: <652641e90901131214l3a1f8a2bkfc91217f15c0da0d@mail.gmail.com> References: <652641e90901131214l3a1f8a2bkfc91217f15c0da0d@mail.gmail.com> Message-ID: <496CF9CE.20506@cfl.rr.com> An HTML attachment was scrubbed... URL: From emadnawfal at gmail.com Tue Jan 13 21:39:18 2009 From: emadnawfal at gmail.com (=?WINDOWS-1256?Q?Emad_Nawfal_(=DA=E3=C7=CF_=E4=E6=DD=E1)?=) Date: Tue, 13 Jan 2009 15:39:18 -0500 Subject: [Tutor] python3.0 and tkinter on ubuntu 8.10 In-Reply-To: <496CF9CE.20506@cfl.rr.com> References: <652641e90901131214l3a1f8a2bkfc91217f15c0da0d@mail.gmail.com> <496CF9CE.20506@cfl.rr.com> Message-ID: <652641e90901131239k6640ef5ev8e48c6716a9d2882@mail.gmail.com> On Tue, Jan 13, 2009 at 3:30 PM, Robert Berman wrote: > Emad, > > A number of people in the Ubuntu community have attempted to work with > Python3.0 under Ubuntu 8.10 and almost all have found it to be a frustrating > and painful experience with some having disastrous consequences. I was > looking for the latest discussion thread on this issue in the Ubuntu forums, > but the forums are currently down. > > You might want to use Google to track this under Python 3.0 + Ubuntu 8.10. > > The overall consensus of opinion is to wait until Python 3.0 became the > default under Ubuntu before using it. > YMMV. > > Robert Berman > > Emad Nawfal (???? ????) wrote: > > Hi Tutors,I have downloaded Python3.0 and started playing with it. I like > it because of the utf-8 default encoding, but I'm having trouble importing > tkinter. I get the following: > >>> import turtle > Traceback (most recent call last): > File "", line 1, in > File "/usr/local/lib/python3.0/turtle.py", line 107, in > import tkinter as TK > File "/usr/local/lib/python3.0/tkinter/__init__.py", line 39, in > import _tkinter # If this fails your Python may not be configured for > Tk > ImportError: No module named _tkinter > >>> import tkinter > Traceback (most recent call last): > File "", line 1, in > File "/usr/local/lib/python3.0/tkinter/__init__.py", line 39, in > import _tkinter # If this fails your Python may not be configured for > Tk > ImportError: No module named _tkinter > >>> > > Any idea how this can be solved on Ubuntu 8.10. I don't have this problem > with the default Python installation (2.5.2) > Thank you > > > -- > ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? > ??????? > "No victim has ever been more repressed and alienated than the truth" > > Emad Soliman Nawfal > Indiana University, Bloomington > > -------------------------------------------------------- > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.orghttp://mail.python.org/mailman/listinfo/tutor > > Thanks Robert for the advice about Ubuntu. I did a lot of Googling before I posted my question, but could not find an answer. I do basic things with Python that involve using lots of Arabic text, and this is why python3.0 was supposed to make my life easier, but I'm learning GUI building now, and it has given me the first frustration. -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From vceder at canterburyschool.org Tue Jan 13 22:02:48 2009 From: vceder at canterburyschool.org (Vern Ceder) Date: Tue, 13 Jan 2009 16:02:48 -0500 Subject: [Tutor] python3.0 and tkinter on ubuntu 8.10 In-Reply-To: References: Message-ID: <496D0178.8000009@canterburyschool.org> Hi, I have Python 3.0/Tkinter/IDLE working fine on Ubuntu 8.10, but it takes a certain amount of fiddling. 1. Make sure the stock Ubuntu Python 3.0 package is not installed 2. download the Python 3.0 source from python.org 3. install the following packages: build-essential libsqlite3-dev libreadline5-dev libncurses5-dev zlib1g-dev libbz2-dev libssl-dev libgdbm-dev tk-dev 4. unpack the Python source and switch to that folder 5. build Python using the standard ./configure, make, make install sequence - if you want more detail/help on that process, just ask... I'd be happy to explain this process in more detail if anyone wants... Cheers, Vern > Hi Tutors,I have downloaded Python3.0 and started playing with it. I like it > because of the utf-8 default encoding, but I'm having trouble importing > tkinter. I get the following: >>>> >>> import turtle > Traceback (most recent call last): > File "", line 1, in > File "/usr/local/lib/python3.0/turtle.py", line 107, in > import tkinter as TK > File "/usr/local/lib/python3.0/tkinter/__init__.py", line 39, in > import _tkinter # If this fails your Python may not be configured for Tk > ImportError: No module named _tkinter >>>> >>> import tkinter > Traceback (most recent call last): > File "", line 1, in > File "/usr/local/lib/python3.0/tkinter/__init__.py", line 39, in > import _tkinter # If this fails your Python may not be configured for Tk > ImportError: No module named _tkinter >>>> >>> > > Any idea how this can be solved on Ubuntu 8.10. I don't have this problem > with the default Python installation (2.5.2) > Thank you -- This time for sure! -Bullwinkle J. Moose ----------------------------- Vern Ceder, Director of Technology Canterbury School, 3210 Smith Road, Ft Wayne, IN 46804 vceder at canterburyschool.org; 260-436-0746; FAX: 260-436-5137 From alan.gauld at btinternet.com Tue Jan 13 22:20:10 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 13 Jan 2009 21:20:10 -0000 Subject: [Tutor] A list of input arguments References: <1c2a2c590901130342r195dbcfuf616d3f1cfd0936c@mail.gmail.com> Message-ID: "Kent Johnson" wrote >>> Is there any way to list the input arguments without listing them >>> inside >>> the function's parentheses? >> >> No, because the function expects 3 arguments so you must pass it 3. > > You can use *args to pass multiple arguments in a list. For example, > > In [2]: values = [1, 2, 3] > > In [3]: show(*values) > 1 2 3 Thats true although I read the question as meaning can I pass in an arbitrary list of arguments even though the function takes 3... The follow-on question seemed to back up that understanding. But it could mean what you took it for in which case clearly the answer is yes and *chords would have worked. I cobfess I don;t like the *args style where the function takes a specified number of params because I find it too easy to hide bugs by inadvertantly passing the wrong number of args. Explicit is better etc... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From ig2ar-saf1 at yahoo.co.uk Tue Jan 13 22:27:25 2009 From: ig2ar-saf1 at yahoo.co.uk (culpritNr1) Date: Tue, 13 Jan 2009 13:27:25 -0800 (PST) Subject: [Tutor] Gamma distribution function Message-ID: <21444899.post@talk.nabble.com> Hello All, OK. This time a less trivial question. Is there a function to enable us sample from a Poisson distribution? There is random.uniform, random.normalvariate(), random.expovariate()... Is there some kind of random.poisson()? Thank you, culpritNr1 -- View this message in context: http://www.nabble.com/Gamma-distribution-function-tp21444899p21444899.html Sent from the Python - tutor mailing list archive at Nabble.com. From alan.gauld at btinternet.com Tue Jan 13 22:32:11 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 13 Jan 2009 21:32:11 -0000 Subject: [Tutor] Date comparison across time zones References: <7b60d8a80901130845s30842deeuba55afec99285a5c@mail.gmail.com> Message-ID: "frenc1z 1z" wrote > I'm a novice python (python 2.6.1) user with the following problem. > > Never though this was going to be so difficult :-). Timezones are devilishly difficult to do if you need to be complete. If you are only dealing with the Western world then its not so bad and most libraries will work. > I would like to compare some dates (date+time really). The dates all > have > the following RFC2822 format: > > Eg. is d1 < d2? > d1 = "Tue, 13 Jan 2009 03:27:29 -0800" > d2 = "Tue, 13 Jan 2009 02:40:00 -0600" > > My thinking is that I first need to make these two dates comparable, > and > eliminate the impact of time zone and dst. Understand that I can > acheive > this using strptime. You can convert to UTC time and compare that way. That avoids issues of having two different timezones in the conversion functions and conflicts within the TZ. environment variables. tzset() should work. Be sure to turn the timezone back to wjatever it was before (store tzname) when you are done. HTH, Alan G. From emadnawfal at gmail.com Tue Jan 13 22:32:38 2009 From: emadnawfal at gmail.com (=?WINDOWS-1256?Q?Emad_Nawfal_(=DA=E3=C7=CF_=E4=E6=DD=E1)?=) Date: Tue, 13 Jan 2009 16:32:38 -0500 Subject: [Tutor] python3.0 and tkinter on ubuntu 8.10 In-Reply-To: <496D0178.8000009@canterburyschool.org> References: <496D0178.8000009@canterburyschool.org> Message-ID: <652641e90901131332g60caaa70l5490a85cb49972f2@mail.gmail.com> On Tue, Jan 13, 2009 at 4:02 PM, Vern Ceder wrote: > Hi, > > I have Python 3.0/Tkinter/IDLE working fine on Ubuntu 8.10, but it takes a > certain amount of fiddling. > > 1. Make sure the stock Ubuntu Python 3.0 package is not installed > > 2. download the Python 3.0 source from python.org > > 3. install the following packages: build-essential libsqlite3-dev > libreadline5-dev libncurses5-dev zlib1g-dev libbz2-dev libssl-dev > libgdbm-dev tk-dev > > 4. unpack the Python source and switch to that folder > > 5. build Python using the standard ./configure, make, make install sequence > - if you want more detail/help on that process, just ask... > > I'd be happy to explain this process in more detail if anyone wants... > > Cheers, > Vern > Yes Vern, it works. Thank you so much. I installed the missing packages and downloaded and installed the Python3.0 source and it's now perfect. Thanks again > > Hi Tutors,I have downloaded Python3.0 and started playing with it. I like >> it >> because of the utf-8 default encoding, but I'm having trouble importing >> tkinter. I get the following: >> >>> >>> import turtle >>>>> >>>> Traceback (most recent call last): >> File "", line 1, in >> File "/usr/local/lib/python3.0/turtle.py", line 107, in >> import tkinter as TK >> File "/usr/local/lib/python3.0/tkinter/__init__.py", line 39, in >> import _tkinter # If this fails your Python may not be configured for >> Tk >> ImportError: No module named _tkinter >> >>> >>> import tkinter >>>>> >>>> Traceback (most recent call last): >> File "", line 1, in >> File "/usr/local/lib/python3.0/tkinter/__init__.py", line 39, in >> import _tkinter # If this fails your Python may not be configured for >> Tk >> ImportError: No module named _tkinter >> >>> >>> >>>>> >>>> >> Any idea how this can be solved on Ubuntu 8.10. I don't have this problem >> with the default Python installation (2.5.2) >> Thank you >> > > > -- > This time for sure! > -Bullwinkle J. Moose > ----------------------------- > Vern Ceder, Director of Technology > Canterbury School, 3210 Smith Road, Ft Wayne, IN 46804 > vceder at canterburyschool.org; 260-436-0746; FAX: 260-436-5137 > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Jan 13 22:39:51 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 13 Jan 2009 21:39:51 -0000 Subject: [Tutor] power of 2.718282 References: <21441385.post@talk.nabble.com> Message-ID: "culpritNr1" wrote > I would appreciate a low level solution because I have to > iteratively call > that computation millions of times. Anything more efficient than > 2.718182**10 may be good. Umm, what's wrong with from math import e # more precision than 2.718182 print e**10 e**10 is shorter to type and probably just as fast as a function call (if not faster!). I see others have pointed out that the math module has this covered but I'm curious about your definition of efficiency? Alan G. From denis.spir at free.fr Tue Jan 13 22:45:01 2009 From: denis.spir at free.fr (spir) Date: Tue, 13 Jan 2009 22:45:01 +0100 Subject: [Tutor] python3.0 and tkinter on ubuntu 8.10 In-Reply-To: <496D0178.8000009@canterburyschool.org> References: <496D0178.8000009@canterburyschool.org> Message-ID: <20090113224501.26112f02@o> Le Tue, 13 Jan 2009 16:02:48 -0500, Vern Ceder a ?crit : > Hi, > > I have Python 3.0/Tkinter/IDLE working fine on Ubuntu 8.10, but it takes > a certain amount of fiddling. > > 1. Make sure the stock Ubuntu Python 3.0 package is not installed > > 2. download the Python 3.0 source from python.org > > 3. install the following packages: build-essential libsqlite3-dev > libreadline5-dev libncurses5-dev zlib1g-dev libbz2-dev libssl-dev > libgdbm-dev tk-dev > > 4. unpack the Python source and switch to that folder > > 5. build Python using the standard ./configure, make, make install > sequence - if you want more detail/help on that process, just ask... > > I'd be happy to explain this process in more detail if anyone wants... > > Cheers, > Vern Yes, I would like it, as I'm under ubuntu too and plan to switch to py3.0 soon. Do you know whether there are issues under ubuntu 8.04 with py3.0? (I have both ubuntu 8.04 & 8.10) Thanks, Denis ------ la vida e estranya From bermanrl at cfl.rr.com Tue Jan 13 22:46:22 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Tue, 13 Jan 2009 16:46:22 -0500 Subject: [Tutor] python3.0 and tkinter on ubuntu 8.10 Message-ID: <496D0BAE.3000807@cfl.rr.com> An HTML attachment was scrubbed... URL: From jervisau at gmail.com Tue Jan 13 22:54:15 2009 From: jervisau at gmail.com (Jervis Whitley) Date: Wed, 14 Jan 2009 08:54:15 +1100 Subject: [Tutor] Gamma distribution function In-Reply-To: <21444899.post@talk.nabble.com> References: <21444899.post@talk.nabble.com> Message-ID: <8e63a5ce0901131354p53ea1d0focc0a93f9af5d47f0@mail.gmail.com> On Wed, Jan 14, 2009 at 8:27 AM, culpritNr1 wrote: > > > there some kind of random.poisson()? > > Thank you, > > culpritNr1 > > Hello try the scipy library: >>> from scipy import stats >>> lamb = 10 >>> stats.distributions.poisson.rvs(lamb, loc=0) array([5]) >>> stats.distributions.poisson.rvs(lamb, loc=0) array([14]) http://www.scipy.org/ cheers, -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Tue Jan 13 23:09:18 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 13 Jan 2009 14:09:18 -0800 Subject: [Tutor] power of 2.718282 In-Reply-To: References: <21441385.post@talk.nabble.com> Message-ID: <40af687b0901131409p7007e485r11f796f8f4210e6b@mail.gmail.com> On Tue, Jan 13, 2009 at 1:39 PM, Alan Gauld wrote: > I would appreciate a low level solution because I have to iteratively call >> that computation millions of times. Anything more efficient than >> 2.718182**10 may be good. >> > > Umm, what's wrong with > > from math import e # more precision than 2.718182 > print e**10 > Apparently nothing at all is wrong with it: C:\Python25\Lib>python timeit.py -s "import math" "x=math.exp(10)" 1000000 loops, best of 3: 0.678 usec per loop C:\Python25\Lib>python timeit.py -s "from math import e" "x=e**10" 1000000 loops, best of 3: 0.411 usec per loop -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From ig2ar-saf1 at yahoo.co.uk Tue Jan 13 23:11:05 2009 From: ig2ar-saf1 at yahoo.co.uk (culpritNr1) Date: Tue, 13 Jan 2009 14:11:05 -0800 (PST) Subject: [Tutor] Gamma distribution function In-Reply-To: <8e63a5ce0901131354p53ea1d0focc0a93f9af5d47f0@mail.gmail.com> References: <21444899.post@talk.nabble.com> <8e63a5ce0901131354p53ea1d0focc0a93f9af5d47f0@mail.gmail.com> Message-ID: <21445597.post@talk.nabble.com> Hi Jarvis, I tried the scipy function. I don't understand it. Look, if you go to http://en.wikipedia.org/wiki/Poisson_Distribution wiki's Poisson distribution documentation you'll find that this is the naive way to compute a Poisson probability mass function >>> lam = 1 >>> k = 2 >>> math.exp(-lam) * lam**k / factorial(k) 0.18393972058572117 Notice that it matches the figure in the wiki page (the red curve). Now, the scipy module does this: >>> stats.distributions.poisson.rvs(1, 2) array([3]) >>> stats.distributions.poisson.rvs(1, 2) array([2]) >>> stats.distributions.poisson.rvs(1, 2) array([2]) >>> stats.distributions.poisson.rvs(1, 2) array([4]) >>> stats.distributions.poisson.rvs(1, 2) array([3]) >>> stats.distributions.poisson.rvs(1, 2) array([2]) The python documentation on this functionality is extremely poor. Look >>> help("scipy.stats.distributions.poisson.rvs") Help on method rvs in scipy.stats.distributions.poisson: scipy.stats.distributions.poisson.rvs = rvs(self, *args, **kwds) method of scipy.stats.distributions.poisson_gen instance Do you understand what's going on? Thanks, culpritNr1 -- View this message in context: http://www.nabble.com/Gamma-distribution-function-tp21444899p21445597.html Sent from the Python - tutor mailing list archive at Nabble.com. From kent37 at tds.net Tue Jan 13 23:42:26 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 13 Jan 2009 17:42:26 -0500 Subject: [Tutor] power of 2.718282 In-Reply-To: <40af687b0901131409p7007e485r11f796f8f4210e6b@mail.gmail.com> References: <21441385.post@talk.nabble.com> <40af687b0901131409p7007e485r11f796f8f4210e6b@mail.gmail.com> Message-ID: <1c2a2c590901131442m26032c1dj84e37e7afa638e01@mail.gmail.com> On Tue, Jan 13, 2009 at 5:09 PM, Marc Tompkins wrote: > Apparently nothing at all is wrong with it: > C:\Python25\Lib>python timeit.py -s "import math" "x=math.exp(10)" > 1000000 loops, best of 3: 0.678 usec per loop > > C:\Python25\Lib>python timeit.py -s "from math import e" "x=e**10" > 1000000 loops, best of 3: 0.411 usec per loop Using ** beats exp() because there is an explicit bytecode for exponentiation so no function call is needed. Careful, though; on my computer about 1/2 of the difference between these two is due to the different style of import: C:\Project\Mango> python -m timeit -s "import math" "x=math.exp(10)" 1000000 loops, best of 3: 0.467 usec per loop C:\Project\Mango> python -m timeit -s "from math import exp" "x=exp(10)" 1000000 loops, best of 3: 0.352 usec per loop C:\Project\Mango> python -m timeit -s "from math import e" "x=e**10" 1000000 loops, best of 3: 0.259 usec per loop Name lookup and function call are both expensive in Python. Using a constant instead of the variable e is substantially faster: C:\Project\Mango> python -m timeit "x=2.718182**10" 10000000 loops, best of 3: 0.0399 usec per loop Kent From kent37 at tds.net Tue Jan 13 23:53:36 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 13 Jan 2009 17:53:36 -0500 Subject: [Tutor] Gamma distribution function In-Reply-To: <21445597.post@talk.nabble.com> References: <21444899.post@talk.nabble.com> <8e63a5ce0901131354p53ea1d0focc0a93f9af5d47f0@mail.gmail.com> <21445597.post@talk.nabble.com> Message-ID: <1c2a2c590901131453m28065cddu877c50a37f38cef5@mail.gmail.com> On Tue, Jan 13, 2009 at 5:11 PM, culpritNr1 wrote: > > Hi Jarvis, > > I tried the scipy function. I don't understand it. Look, if you go to > http://en.wikipedia.org/wiki/Poisson_Distribution wiki's Poisson > distribution documentation you'll find that this is the naive way to > compute a Poisson probability mass function > >>>> lam = 1 >>>> k = 2 >>>> math.exp(-lam) * lam**k / factorial(k) > 0.18393972058572117 > > Notice that it matches the figure in the wiki page (the red curve). > > Now, the scipy module does this: >>>> stats.distributions.poisson.rvs(1, 2) > array([3]) > > The python documentation on this functionality is extremely poor. See http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.poisson.html I think you want poisson.pmf(), not poisson.rvs(). See the note at the bottom of the referenced page. I think rvs() is picking random values distributed according to the given poisson distribution, that is why you get different numbers each time. Kent From ig2ar-saf1 at yahoo.co.uk Tue Jan 13 23:40:36 2009 From: ig2ar-saf1 at yahoo.co.uk (culpritNr1) Date: Tue, 13 Jan 2009 14:40:36 -0800 (PST) Subject: [Tutor] Gamma distribution function In-Reply-To: <8e63a5ce0901131354p53ea1d0focc0a93f9af5d47f0@mail.gmail.com> References: <21444899.post@talk.nabble.com> <8e63a5ce0901131354p53ea1d0focc0a93f9af5d47f0@mail.gmail.com> Message-ID: <21446064.post@talk.nabble.com> I just figured it out myself. This is how to do it both the naive and the efficient way, respectively: >>> import math >>> from scipy import factorial >>> lam = 1 >>> k = 2 >>> math.exp(-lam) * lam**k / factorial(k) 0.18393972058572117 >>> from scipy import stats >>> stats.poisson.pmf(2,1) array(0.18393972058572114) thanks all anyway, culpritNr1 Jervis Whitley wrote: > > On Wed, Jan 14, 2009 at 8:27 AM, culpritNr1 > wrote: > >> >> >> there some kind of random.poisson()? >> >> Thank you, >> >> culpritNr1 >> >> Hello try the scipy library: >>>> from scipy import stats >>>> lamb = 10 >>>> stats.distributions.poisson.rvs(lamb, loc=0) > array([5]) >>>> stats.distributions.poisson.rvs(lamb, loc=0) > array([14]) > > http://www.scipy.org/ > > cheers, > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- View this message in context: http://www.nabble.com/Gamma-distribution-function-tp21444899p21446064.html Sent from the Python - tutor mailing list archive at Nabble.com. From jervisau at gmail.com Tue Jan 13 23:59:21 2009 From: jervisau at gmail.com (Jervis Whitley) Date: Wed, 14 Jan 2009 09:59:21 +1100 Subject: [Tutor] Fwd: Gamma distribution function In-Reply-To: <8e63a5ce0901131426y1b7f7b2fne6369b1891213b5e@mail.gmail.com> References: <21444899.post@talk.nabble.com> <8e63a5ce0901131354p53ea1d0focc0a93f9af5d47f0@mail.gmail.com> <21445597.post@talk.nabble.com> <8e63a5ce0901131426y1b7f7b2fne6369b1891213b5e@mail.gmail.com> Message-ID: <8e63a5ce0901131459x3bec3bdes68c36ad3dba8d2db@mail.gmail.com> ---------- Forwarded message ---------- From: Jervis Whitley Date: Wed, Jan 14, 2009 at 9:26 AM Subject: Re: [Tutor] Gamma distribution function To: culpritNr1 On Wed, Jan 14, 2009 at 9:11 AM, culpritNr1 wrote: > > The python documentation on this functionality is extremely poor. Look > >>> help("scipy.stats.distributions.poisson.rvs") > Help on method rvs in scipy.stats.distributions.poisson: > scipy.stats.distributions.poisson.rvs = rvs(self, *args, **kwds) method of > scipy.stats.distributions.poisson_gen instance > > Do you understand what's going on? > > Thanks, > > culpritNr1 > > > -- > View this message in context: > http://www.nabble.com/Gamma-distribution-function-tp21444899p21445597.html > Sent from the Python - tutor mailing list archive at Nabble.com. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Your previous email said you wanted to sample from the poisson function, which is what that rvs method is doing, taking random samples from a poisson distribution of lambda = 1 in your case. They also provide a means to shift the function from a nominal x crossing of 0 using the second argument, in your case you have used 2. So you were sampling from a function of mean 1 shifted right by 2. The below has been taken from the poisson documentation itself: print stats.distributions.poisson.__doc__ A poisson discrete random variable. Discrete random variables are defined from a standard form. The standard form may require some other parameters to complete its specification. The distribution methods also take an optional location parameter using loc= keyword. The default is loc=0. The calling form of the methods follow: poisson.rvs(mu,loc=0) - random variates poisson.pmf(x,mu,loc=0) - probability mass function poisson.cdf(x,mu,loc=0) - cumulative density function poisson.sf(x,mu,loc=0) - survival function (1-cdf --- sometimes more accurate) poisson.ppf(q,mu,loc=0) - percent point function (inverse of cdf --- percentiles) poisson.isf(q,mu,loc=0) - inverse survival function (inverse of sf) poisson.stats(mu,loc=0,moments='mv') - mean('m',axis=0), variance('v'), skew('s'), and/or kurtosis('k') poisson.entropy(mu,loc=0) - entropy of the RV Alternatively, the object may be called (as a function) to fix the shape and location parameters returning a "frozen" discrete RV object: myrv = poisson(mu,loc=0) - frozen RV object with the same methods but holding the given shape and location fixed. You can construct an aribtrary discrete rv where P{X=xk} = pk by passing to the rv_discrete initialization method (through the values= keyword) a tuple of sequences (xk,pk) which describes only those values of X (xk) that occur with nonzero probability (pk). Poisson distribution poisson.pmf(k, mu) = exp(-mu) * mu**k / k! for k >= 0 If you are after a probability at a given k (which it now sounds like you may be after) you might be interested in the pmf method. (Sorry I did a reply instead of reply-all) Cheers, Jervis -------------- next part -------------- An HTML attachment was scrubbed... URL: From jjcrump at myuw.net Wed Jan 14 00:09:26 2009 From: jjcrump at myuw.net (Jon Crump) Date: Tue, 13 Jan 2009 15:09:26 -0800 (PST) Subject: [Tutor] quoting and escaping Message-ID: All, Something I don't understand (so what else is new?) about quoting and escaping: >>> s = """ "some" \"thing\" """ >>> s ' "some" "thing" ' I've got strings like this: s = """[{"title" : "Egton, Yorkshire", "start" : new Date(1201,1,4), "description" : "Hardy's long name: Egton, Yorkshire. <br> "}, {"title" : "Guilsborough, Yorkshire", "start" : new Date(1201,1,5), "description" : "Hardy's long name: Guilsborough, Yorkshire. <br> <img src=\"document.png\" style=\"cursor: pointer\" onclick=\"SimileAjax.WindowManager.cancelPopups();show_next('tab3');pager('006'); return false\"/>pg.006: 1201-02-05 to 1202-03-07"}]""" Thanks to your good help, I can re.sub() to translate the new Date() objects into "datetime.date()" instances, thus: [{"title" : "Egton, Yorkshire", "start" : "date(1201, 02, 04)", "description" : "Hardy's long name: Egton, Yorkshire. <br> "}, {"title" : "Guilsborough, Yorkshire", "start" : "date(1201, 02, 05)", "description" : "Hardy's long name: Guilsborough, Yorkshire. <br> <img src="document.png" style="cursor: pointer" onclick="SimileAjax.WindowManager.cancelPopups();show_next('tab3');pager('006'); return false"/>pg.006: 1201-02-05 to 1202-03-07"}] with the quotation marks, eval() evaluates these date() instances correctly; however, python treats " and \" as if they were identical so I wind up with bad syntax: multiple doublequoted strings in a dictionary value. How can I identify \" in a regex so that I can replace it with something that eval() won't choke on? This is pretty confusing to me, so I've tried to provide clarification below: >>> a = """{"aKey" : "aValue"}""" >>> eval(a) {'aKey': 'aValue'} ## so far so good, but then: >>> b = """{"aKey" : "a value with \"literal quotes\" in it"}""" >>> eval(b) Traceback (most recent call last): File "", line 1, in File "", line 1 {"aKey" : "a value with "literal quotes" in it"} ^ SyntaxError: invalid syntax From steve at alchemy.com Wed Jan 14 01:07:23 2009 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 13 Jan 2009 16:07:23 -0800 (PST) Subject: [Tutor] quoting and escaping In-Reply-To: References: Message-ID: <58113.134.134.136.14.1231891643.squirrel@webmail.alchemy.com> On Tue, January 13, 2009 15:09, Jon Crump wrote: > All, > > Something I don't understand (so what else is new?) about quoting and > escaping: > >>>> s = """ "some" \"thing\" """ >>>> s > ' "some" "thing" ' Correct. Note that """ ... """ is just a string constant the same as "..." is, with the exception that it can easily span multiple physical lines. What happens between the quotes, though, is the same. This includes the fact that \ is used to escape special characters, so \" is how you can type a literal " character without it being interpreted as the end-of-string delimiter. Of course, since this is a triple-double-quoted string, a plain old " won't be confused as such anyway, so yes, in this particular instance they evaluate to the same character when the string object is created. To avoid this, you could either escape the backslashes, so you'd have: s = """ "some" \\"thing\\" """ (now s == ' "some" \"thing\" ') or, I think better, would be to use raw string constants: s = r""" "some" \"thing\" """ (now s == ' "some" \"thing\" ') (note that if you're looking at the representation of s in your interpreter, it'll actually print as ' "some" \\"thing\\" ', since it's showing you that the \s are literal. The actual string value is as intended, though) From john at fouhy.net Wed Jan 14 01:12:10 2009 From: john at fouhy.net (John Fouhy) Date: Wed, 14 Jan 2009 13:12:10 +1300 Subject: [Tutor] quoting and escaping In-Reply-To: References: Message-ID: <5e58f2e40901131612mee8c482hada628206b0234ef@mail.gmail.com> 2009/1/14 Jon Crump : >>>> b = """{"aKey" : "a value with \"literal quotes\" in it"}""" >>>> eval(b) > > Traceback (most recent call last): > File "", line 1, in > File "", line 1 > {"aKey" : "a value with "literal quotes" in it"} > ^ > SyntaxError: invalid syntax Is it an option to just do: >>> b = """{'aKey':'a value with "literal quotes" in it'}""" >>> eval(b) {'aKey': 'a value with "literal quotes" in it'} ? (or, heck, get rid of eval.. do you really need it?) -- John. From steve at alchemy.com Wed Jan 14 01:18:33 2009 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 13 Jan 2009 16:18:33 -0800 (PST) Subject: [Tutor] quoting and escaping In-Reply-To: <5e58f2e40901131612mee8c482hada628206b0234ef@mail.gmail.com> References: <5e58f2e40901131612mee8c482hada628206b0234ef@mail.gmail.com> Message-ID: <59276.134.134.136.14.1231892313.squirrel@webmail.alchemy.com> On Tue, January 13, 2009 16:12, John Fouhy wrote: > (or, heck, get rid of eval.. do you really need it?) As a general comment, especially for beginning to intermediate programmers, the answer to "do you need eval()" is usually "not really." There's almost always a better, easier and more straightforward way to do what eval() is usually naively used for. From damontimm at gmail.com Wed Jan 14 01:34:09 2009 From: damontimm at gmail.com (Damon Timm) Date: Tue, 13 Jan 2009 19:34:09 -0500 Subject: [Tutor] Sys.stdin Question Message-ID: <262679b50901131634h6d252f78t4f2942d8b45f569e@mail.gmail.com> Hi - am writing a script to send myself email messages from the command line ... I want to have the option be able to input the message body via a pipe so I can easily shoot emails to myself (like from: ls, cat, df, du, mount, etc) ... what i want to be able to do is: \$ ls -la | myscript.py and in the script use something like this (just an example to keep it short): cli_input = sys.stdin.read() if cli_input: print "I piped this in:", cli_input else: print "nothing got piped in, moving on." This works when I do have something coming via stdin ... but if I run the script without piping something first ... it just sits there (I assume, waiting for some stdin) ... How do I tell it: if there is no stdin, just move on? Thanks, Damon From alan.gauld at btinternet.com Wed Jan 14 02:15:36 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 14 Jan 2009 01:15:36 -0000 Subject: [Tutor] Gamma distribution function References: <21444899.post@talk.nabble.com><8e63a5ce0901131354p53ea1d0focc0a93f9af5d47f0@mail.gmail.com> <21445597.post@talk.nabble.com> Message-ID: "culpritNr1" wrote > I tried the scipy function. I don't understand it. Try reading about it here: http://numpy.sourceforge.net/numdoc/HTML/numdoc.htm It explains the output format. I believe it applies to the scipy version as well as the numpy. > The python documentation on this functionality is extremely poor. >>>> help("scipy.stats.distributions.poisson.rvs") That will only find the basic help in the doc strings. You need to look at the documented help too. The web page is the best I've found. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Wed Jan 14 02:28:42 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 14 Jan 2009 01:28:42 -0000 Subject: [Tutor] Sys.stdin Question References: <262679b50901131634h6d252f78t4f2942d8b45f569e@mail.gmail.com> Message-ID: "Damon Timm" wrote > \$ ls -la | myscript.py > > cli_input = sys.stdin.read() > > if cli_input: > print "I piped this in:", cli_input > This works when I do have something coming via stdin ... but if I > run > the script without piping something first ... it just sits there (I > assume, waiting for some stdin) ... Yep, if you hit Ctr-D (ie. EOF) it should continue as normal. The way other Unix style programs deal with this is to write the code to read from a general file and if you want to use stdin provide an argument of '-': \$ ls -la | myscript.py - Or sometimes use a if argument to specify a file which can then be '-' for stdin: \$ ls -la | myscript.py -f- Either of these will enable your script to email a file if asked, read from nowhere if no file is specified or from stdin if specifically told to. Of course the standard utility approach is to read from stdin as default in which case no flags are needed but you have to provide the EOF manually. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From john at fouhy.net Wed Jan 14 02:45:53 2009 From: john at fouhy.net (John Fouhy) Date: Wed, 14 Jan 2009 14:45:53 +1300 Subject: [Tutor] Sys.stdin Question In-Reply-To: <262679b50901131634h6d252f78t4f2942d8b45f569e@mail.gmail.com> References: <262679b50901131634h6d252f78t4f2942d8b45f569e@mail.gmail.com> Message-ID: <5e58f2e40901131745v55471568pcf2d879c9d2ad09c@mail.gmail.com> 2009/1/14 Damon Timm : > This works when I do have something coming via stdin ... but if I run > the script without piping something first ... it just sits there (I > assume, waiting for some stdin) ... > > How do I tell it: if there is no stdin, just move on? This might work: import select, sys def isData(): return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], []) if isData(): print 'You typed:', sys.stdin.read() else: print 'Nothing to see here.' I say "might" because it is OS-dependent, but I guess you are using unix/linux. Source: http://www.darkcoding.net/software/non-blocking-console-io-is-not-possible/ I found that by searching for "python stdin non-blocking". This is because "blocking" is jargon for "waiting until something happens". In this case, stdin.read() is blocking until it sees some data with an EOF. HTH! -- John. From steve at alchemy.com Wed Jan 14 02:55:47 2009 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 13 Jan 2009 17:55:47 -0800 (PST) Subject: [Tutor] Sys.stdin Question In-Reply-To: <5e58f2e40901131745v55471568pcf2d879c9d2ad09c@mail.gmail.com> References: <262679b50901131634h6d252f78t4f2942d8b45f569e@mail.gmail.com> <5e58f2e40901131745v55471568pcf2d879c9d2ad09c@mail.gmail.com> Message-ID: <39283.134.134.136.14.1231898147.squirrel@webmail.alchemy.com> On Tue, January 13, 2009 17:45, John Fouhy wrote: > 2009/1/14 Damon Timm : >> This works when I do have something coming via stdin ... but if I run >> the script without piping something first ... it just sits there (I >> assume, waiting for some stdin) ... This is playing a dangerous game, though, of introducing a race condition. Is there nothing on the standard input RIGHT NOW because the source on the other end of the pipe hasn't managed to generate anything yet, or because there's nothing piped? A better approach is either to explicitly specify whether to read from stdin or a file, as Alan demonstrated (and the fileinput module implements this for you, by the way), or to see if stdin is connected to a terminal or not. So instead of seeing if anything's showing up (and introducing timing dependencies and uncertainty), see if it's attached to a real terminal at all. On Unix, os.isatty(sys.stdin) will tell you this. steve From damontimm at gmail.com Wed Jan 14 02:59:19 2009 From: damontimm at gmail.com (Damon Timm) Date: Tue, 13 Jan 2009 20:59:19 -0500 Subject: [Tutor] Sys.stdin Question In-Reply-To: References: <262679b50901131634h6d252f78t4f2942d8b45f569e@mail.gmail.com> Message-ID: <262679b50901131759uf2589eem349266cca7b2ecbf@mail.gmail.com> On Tue, Jan 13, 2009 at 8:28 PM, Alan Gauld wrote: > The way other Unix style programs deal with this is to write the code > to read from a general file and if you want to use stdin provide an > argument of '-': That's a good idea, actually -- I hadn't thought of that. Although I use that "-" a lot in command line programs ... It would force someone to be specific about what it was they wanted the script to do ... then, I guess, I can just have it do an if statement that asks: if args[0] == "-" then ... blah. I may do that ... the script, itself, actually handles attachments, too ... so I could use that flag, also, to say: attach the standard out to an email. On Tue, Jan 13, 2009 at 8:45 PM, John Fouhy wrote: > This might work: > > import select, sys > def isData(): > return select.select([sys.stdin], [], [], 0) == > ([sys.stdin], [], []) > > if isData(): > print 'You typed:', sys.stdin.read() > else: > print 'Nothing to see here.' Oh ho ho! Very neat! I will have to head over to the python docs to see what that is but it seems to work! > I say "might" because it is OS-dependent, but I guess you are using unix/linux. Yea - you guessed right. > Source: http://www.darkcoding.net/software/non-blocking-console-io-is-not-possible/ > > I found that by searching for "python stdin non-blocking". This is > because "blocking" is jargon for "waiting until something happens". > In this case, stdin.read() is blocking until it sees some data with an > EOF. Thanks for that tip -- as you probably guessed, google wasn't turning up too many results for me. But this is working now. However ... reading the next comment has me thinking again: On Tue, Jan 13, 2009 at 8:55 PM, Steve Willoughby wrote: > This is playing a dangerous game, though, of introducing a race condition. > Is there nothing on the standard input RIGHT NOW because the source on > the other end of the pipe hasn't managed to generate anything yet, or > because there's nothing piped? > > A better approach is either to explicitly specify whether to read from > stdin or a file, as Alan demonstrated (and the fileinput module implements > this for you, by the way), or to see if stdin is connected to a terminal > or not. So instead of seeing if anything's showing up (and introducing > timing dependencies and uncertainty), see if it's attached to a real > terminal at all. On Unix, os.isatty(sys.stdin) will tell you this. Does this concern still apply with John's suggestion? I just tested it in my little application and didn't have an issue ... of course, I only ran a couple different command line items before throwing up my hands in celebration. I can go to using the "-" option ... although, to be honest, I like the idea of the script thinking for itself ... that is: if there is stdin, use it -- if not, not ... and, I was thinking of attaching the stdin as a text file, if present. And not attaching anything, if not. Thanks everyone! From steve at alchemy.com Wed Jan 14 03:10:38 2009 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 13 Jan 2009 18:10:38 -0800 (PST) Subject: [Tutor] Sys.stdin Question In-Reply-To: <262679b50901131759uf2589eem349266cca7b2ecbf@mail.gmail.com> References: <262679b50901131634h6d252f78t4f2942d8b45f569e@mail.gmail.com> <262679b50901131759uf2589eem349266cca7b2ecbf@mail.gmail.com> Message-ID: <39742.134.134.136.14.1231899038.squirrel@webmail.alchemy.com> On Tue, January 13, 2009 17:59, Damon Timm wrote: > ... then, I guess, I can just have it do an if statement that asks: if > args[0] == "-" then ... blah. I may do that ... the script, itself, Look at the fileinput module. If you're looking at the command line for a list of filenames, which may include "-" to mean (read stdin at this point in the list of files), your script's logic is reduced to simply: while line in fileinput.input(): # process the line and your script focuses on its specific task. >> or not. So instead of seeing if anything's showing up (and introducing >> timing dependencies and uncertainty), see if it's attached to a real >> terminal at all. On Unix, os.isatty(sys.stdin) will tell you this. > > Does this concern still apply with John's suggestion? I just tested > it in my little application and didn't have an issue ... of course, I Yes, it does. And in a trivial case, it will usually work. But don't base your solutions on something that looks like it sorta works most of the time but isn't really the recommended practice, because it will break later and you'll spend a lot of time figuring out why it's not being reliable. > I can go to using the "-" option ... although, to be honest, I like > the idea of the script thinking for itself ... that is: if there is > stdin, use it -- if not, not ... and, I was thinking of attaching the > stdin as a text file, if present. And not attaching anything, if not. As the Zen of Python states, "explicit is better than implicit." Scripts which just magically "do the right thing" can be cool to play with, but they have a nasty tendency to guess wrong about what the right thing might be. In this case, you're making assumptions about how to *guess* whether there's standard input piped at your script, and running with those assumptions... but there are easily identified cases where those assumptions don't hold true. Also, think of anyone other than you (or you at a later date) using this script. The number of things the script does for no apparent reason can lead to frustration and doubt that you really know, as a user, what the script is really going to try to do in a given situation, and what you'll have to do on your end to "trick" it into doing what you really wanted in the first place. It's cute, but ultimately implicit behavior doesn't make for good, long-lasting solid applications. From john at fouhy.net Wed Jan 14 03:05:27 2009 From: john at fouhy.net (John Fouhy) Date: Wed, 14 Jan 2009 15:05:27 +1300 Subject: [Tutor] Sys.stdin Question In-Reply-To: <262679b50901131759uf2589eem349266cca7b2ecbf@mail.gmail.com> References: <262679b50901131634h6d252f78t4f2942d8b45f569e@mail.gmail.com> <262679b50901131759uf2589eem349266cca7b2ecbf@mail.gmail.com> Message-ID: <5e58f2e40901131805r50628b65ue8290b95e128ef13@mail.gmail.com> 2009/1/14 Damon Timm : > On Tue, Jan 13, 2009 at 8:55 PM, Steve Willoughby wrote: >> This is playing a dangerous game, though, of introducing a race condition. >> Is there nothing on the standard input RIGHT NOW because the source on >> the other end of the pipe hasn't managed to generate anything yet, or >> because there's nothing piped? > Does this concern still apply with John's suggestion? I just tested > it in my little application and didn't have an issue ... of course, I > only ran a couple different command line items before throwing up my > hands in celebration. It's easy to test: ### test.py ### import time time.sleep(1) print 'foo' ### \$ python test.py | python stdintest.py Nothing to see here. close failed: [Errno 32] Broken pipe [not shown: the 1 second pause after "Nothing to see here." showed up] You could "fix" it by adding a delay to your consumer script.. as long as none of your input scripts take longer than the delay to generate output. Or do things differently, which might be smarter :-) -- John. From metolone+gmane at gmail.com Wed Jan 14 03:48:39 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Tue, 13 Jan 2009 18:48:39 -0800 Subject: [Tutor] Date comparison across time zones References: <7b60d8a80901130845s30842deeuba55afec99285a5c@mail.gmail.com> Message-ID: "frenc1z 1z" wrote in message news:7b60d8a80901130845s30842deeuba55afec99285a5c at mail.gmail.com... > Hello, > > I'm a novice python (python 2.6.1) user with the following problem. > > Never though this was going to be so difficult :-). > > I would like to compare some dates (date+time really). The dates all have > the following RFC2822 format: > > Eg. is d1 < d2? > d1 = "Tue, 13 Jan 2009 03:27:29 -0800" > d2 = "Tue, 13 Jan 2009 02:40:00 -0600" Check out the email.utils module, specifically the parsedate_tz and mktime_tz functions. -Mark From kent37 at tds.net Wed Jan 14 04:13:10 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 13 Jan 2009 22:13:10 -0500 Subject: [Tutor] quoting and escaping In-Reply-To: References: Message-ID: <1c2a2c590901131913i3cba55f6k642fafc557a6d8a0@mail.gmail.com> On Tue, Jan 13, 2009 at 6:09 PM, Jon Crump wrote: > I've got strings like this: > > s = """[{"title" : "Egton, Yorkshire", "start" : new Date(1201,1,4), > "description" : "Hardy's long name: Egton, Yorkshire. <br> "}, > {"title" : "Guilsborough, Yorkshire", "start" : new Date(1201,1,5), > "description" : "Hardy's long name: Guilsborough, Yorkshire. <br> > <img src=\"document.png\" style=\"cursor: pointer\" > onclick=\"SimileAjax.WindowManager.cancelPopups();show_next('tab3');pager('006'); > return false\"/>pg.006: 1201-02-05 to 1202-03-07"}]""" Where does this come from? It looks like the string representation of a dict. Can you get the actual dict? Perhaps there is a better way to do whatever you are doing? Kent From noufal at nibrahim.net.in Wed Jan 14 11:36:54 2009 From: noufal at nibrahim.net.in (Noufal Ibrahim) Date: Wed, 14 Jan 2009 16:06:54 +0530 Subject: [Tutor] Selecting first matching element from a list In-Reply-To: <496B7C31.9040104@gmail.com> References: <496B6847.9080701@nibrahim.net.in> <496B7C31.9040104@gmail.com> Message-ID: <496DC046.5060604@nibrahim.net.in> bob gailer wrote: > > 2) "looks bad" and "is ugly" are emotional responses. What are you > feeling and wanting when you say those things? It's hard for me to qualify really but my general idea of list comprehensions is that they transform and filter lists creating other lists. For instance, I'd call this if key in foo: return foo[key] else: return 'unknown' 'ugly' when compared to return foo.get(key,'unknown') I guess I'm looking for the idiomatic way of performing such an operation. My gut feel tells me that the zeroth element of a list comprehension is not the right way to go but I wanted confirmation/rebuttal. Peace. -- ~noufal http://nibrahim.net.in/ From s4027340 at student.uq.edu.au Wed Jan 14 11:52:21 2009 From: s4027340 at student.uq.edu.au (Mr Gerard Kelly) Date: Wed, 14 Jan 2009 20:52:21 +1000 Subject: [Tutor] lists and Entry Message-ID: There is a little Tkinter program. It lets you type something in a box, and will display it at the command line. from Tkinter import * master = Tk() e = Entry(master) e.pack() e.focus_set() def callback(): s=e.get() print s b = Button(master, text="get", width=10, command=callback) b.pack() mainloop() The get() method returns a string, how do I make it return a list? I want to be able to type in 1,2,3 into the box and get [1,2,3] to appear on the command line. If I change the callback() method so that it says s=[e.get()] I just get a list with one element, the string: ['1,2,3'] If I make it s=list(e.get()) I get a list with every character as an element: ['1', ',', '2', ',', '3'] How to just get plain [1,2,3]? many thanks From roadierich at googlemail.com Wed Jan 14 12:17:28 2009 From: roadierich at googlemail.com (Richard Lovely) Date: Wed, 14 Jan 2009 11:17:28 +0000 Subject: [Tutor] Active State Python with IDLE Python 2.5 In-Reply-To: <496B1A66.5050306@sbcglobal.net> References: <496AA318.6020508@sbcglobal.net> <496B1A66.5050306@sbcglobal.net> Message-ID: The Activestate package IS vanilla python. It just comes packaged with a few addon modules for things such as ActiveX and with windows GUI libraries. If it works with Vanilla Python, there's virtually no reason it won't work with the activestate distribution, and vice versa, as long as you don't use any of the activestate modules in applications you want to work on other operating systems. It's like the TK modules, if you don't import them, you don't need to worry about whether your users have them or not. On 12/01/2009, Wayne Watson wrote: > Thanks. Is it possible to just disable the vanilla version? I may want to > switch between the two. Most users of the program I'm about to modify use > the vanilla version. At some point, I may want to go back to it to verify > that in their world all is OK. > > > Alan Gauld wrote: > > "Wayne Watson" wrote > > I installed "Python" 2.5 a few months ago, and decided I'd like to try > windowpy from ActiveState. Is having both of these installed going to > cause me trouble? > > Multiple versions of Python should not be a problem provided you put > them in different folders. > > C:\python25 > > and > > C:\ASpython25 > > for example > > You will have to remember which one is the default version (ie will > be used when you double click a python file for example) but you > can set things up to run both. But there is little point. If you are > on Windows I'd personally uninstall the vanilla version and install > the ActiveState version, it has a lot more features for Windows users. > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- > Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.01 Deg. W, > 39.26 Deg. N) GMT-8 hr std. time) "What killed the electric car? > Expensive batteries did." -- Physics for Future Presidents, Richard A. > Muller Web Page: > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Richard "Roadie Rich" Lovely, part of the JNP|UK Famile www.theJNP.com From andreengels at gmail.com Wed Jan 14 12:39:54 2009 From: andreengels at gmail.com (Andre Engels) Date: Wed, 14 Jan 2009 12:39:54 +0100 Subject: [Tutor] lists and Entry In-Reply-To: References: Message-ID: <6faf39c90901140339n127e747cgaf5712c99784cd3e@mail.gmail.com> On Wed, Jan 14, 2009 at 11:52 AM, Mr Gerard Kelly wrote: > There is a little Tkinter program. It lets you type something in a box, > and will display it at the command line. > > > from Tkinter import * > > master = Tk() > > e = Entry(master) > e.pack() > > e.focus_set() > > def callback(): > s=e.get() > print s > > b = Button(master, text="get", width=10, command=callback) > b.pack() > > mainloop() > > > > The get() method returns a string, how do I make it return a list? > I want to be able to type in 1,2,3 into the box and get [1,2,3] to > appear on the command line. > > If I change the callback() method so that it says > s=[e.get()] > I just get a list with one element, the string: ['1,2,3'] > > If I make it > s=list(e.get()) > I get a list with every character as an element: ['1', ',', '2', ',', '3'] > > How to just get plain [1,2,3]? You'll have to work with the string. Assuming that the string will always be a couple of integers, separated by commas (if getting input from the keyboard, create a loop so that data are being called again and again until it parses correctly), you can get what you want with: s=[int(n) for n in e.get().split(',')] Explaining this Python: e.get(), as you have noticed, is a string consisting of whatever has been put in, in this case '1,2,3'. e.get.split(',') means "split e.get() into pieces at each comma, and make a list out of it'. This gives: ['1','2','3']. And finally [int(n) for n in A] with A being a list (or more generally, anything enumerable) gives a list consisting of the int value of the items in A. -- Andr? Engels, andreengels at gmail.com From emadnawfal at gmail.com Wed Jan 14 12:43:38 2009 From: emadnawfal at gmail.com (=?WINDOWS-1256?Q?Emad_Nawfal_(=DA=E3=C7=CF_=E4=E6=DD=E1)?=) Date: Wed, 14 Jan 2009 06:43:38 -0500 Subject: [Tutor] lists and Entry In-Reply-To: References: Message-ID: <652641e90901140343s4c1b209ai28ba90d715268cb5@mail.gmail.com> On Wed, Jan 14, 2009 at 5:52 AM, Mr Gerard Kelly wrote: > There is a little Tkinter program. It lets you type something in a box, > and will display it at the command line. > > > from Tkinter import * > > master = Tk() > > e = Entry(master) > e.pack() > > e.focus_set() > > def callback(): > s=e.get() > print s > > b = Button(master, text="get", width=10, command=callback) > b.pack() > > mainloop() > > > > The get() method returns a string, how do I make it return a list? > I want to be able to type in 1,2,3 into the box and get [1,2,3] to > appear on the command line. > > If I change the callback() method so that it says > s=[e.get()] > I just get a list with one element, the string: ['1,2,3'] > > If I make it > s=list(e.get()) > I get a list with every character as an element: ['1', ',', '2', ',', '3'] > > How to just get plain [1,2,3]? > > many thanks One possibility is to split the string on the comma. If you have a string like : s = '1,2,3' then s.split(',') = [1,2,3] If you later want to change this into a list of integers for example, you might use something like a list comprehension. Look at the following interactive session: >>> s = "1,2,3" >>> m = s.split(',') >>> m ['1', '2', '3'] >>> f = [int(i) for i in m] >>> f [1, 2, 3] >>> This is a reply from a programming amateur, so I think you might consider it until you get a better solution. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From wesbrooks at gmail.com Wed Jan 14 16:37:36 2009 From: wesbrooks at gmail.com (Wesley Brooks) Date: Wed, 14 Jan 2009 15:37:36 +0000 Subject: [Tutor] Small python web server suitable for web cam streams? Message-ID: Dear Users, I'm aware that there is a large array of web toolkits available in python and I would like to hear some opinions on which may be best suited to my specification so I can research them further. I have a machine which runs for extended periods of time, and often into days rather than just hours. I would like to set up the computer so that it hosts a simple web page displaying current status information, and a feed from a web camera which is viewing the business end of the machine. This web site will not be opened to the wider internet, just kept as open access to all machines on the local network. There is currently no requirement for any control from the user end, just to view the page or pages. This will be running on a windows machine. Yours Faithfully, Wesley Brooks -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Jan 14 17:21:56 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 14 Jan 2009 11:21:56 -0500 Subject: [Tutor] Small python web server suitable for web cam streams? In-Reply-To: References: Message-ID: <1c2a2c590901140821q75841c08m4a09965688774013@mail.gmail.com> On Wed, Jan 14, 2009 at 10:37 AM, Wesley Brooks wrote: > I have a machine which runs for extended periods of time, and often into > days rather than just hours. I would like to set up the computer so that it > hosts a simple web page displaying current status information, and a feed > from a web camera which is viewing the business end of the machine. This web > site will not be opened to the wider internet, just kept as open access to > all machines on the local network. There is currently no requirement for any > control from the user end, just to view the page or pages. Will the web server generate the status page and talk to the camera, or is it just showing static data that comes from somewhere else? If the data is generated outside the server you can use IIS or Apache to display them. If you are generating pages in the server then something simple like CherryPy might be a good choice, rather than one of the full-featured web frameworks. Kent From bgailer at gmail.com Wed Jan 14 17:25:51 2009 From: bgailer at gmail.com (bob gailer) Date: Wed, 14 Jan 2009 11:25:51 -0500 Subject: [Tutor] Selecting first matching element from a list In-Reply-To: <496DC046.5060604@nibrahim.net.in> References: <496B6847.9080701@nibrahim.net.in> <496B7C31.9040104@gmail.com> <496DC046.5060604@nibrahim.net.in> Message-ID: <496E120F.2020201@gmail.com> Noufal Ibrahim wrote: > bob gailer wrote: > >> >> 2) "looks bad" and "is ugly" are emotional responses. What are you >> feeling and wanting when you say those things? > > It's hard for me to qualify really but my general idea of list > comprehensions is that they transform and filter lists creating other > lists. > > For instance, I'd call this > if key in foo: > return foo[key] > else: > return 'unknown' > > 'ugly' when compared to > > return foo.get(key,'unknown') > > I guess I'm looking for the idiomatic way of performing such an > operation. My gut feel tells me that the zeroth element of a list > comprehension is not the right way to go but I wanted > confirmation/rebuttal. I suggest writing the algorithm in step-by-step pseudocode then asking "how can I write this in Python"? High level goal: Given a list of numbers, return the first that meets a condition. If none meet the condition, return 'unknown'. Step-by-step process in pseudocode: for each element in list see if it meets the condition if it does stop and return the element if we have not stopped return 'unknown' How many ways are there in Python to go thru a list (and apply a function to each element)? The ones I know are: while for list comprehension map() I discard while as for takes less code and is easier to understand. I discard map() as it is the "old way" to do a comprehension. That leaves for and comprehension. The advantage of for is that you can stop the process once you find the desired element. The advantage of comprehension is compactness and readability. You must work with the tools available (or write your own). But the heart of anything you write will be the original pseudocode. Then you must live with any emotional reactions. -- Bob Gailer Chapel Hill NC 919-636-4239 From denis.spir at free.fr Wed Jan 14 18:09:51 2009 From: denis.spir at free.fr (spir) Date: Wed, 14 Jan 2009 18:09:51 +0100 Subject: [Tutor] traceback Message-ID: <20090114180951.6095bbb3@o> Hello, I rather often use exceptions as information providers at design or debug time. A typical use of mine is to have a test version of methods that wrap standard version: def run(): do stuff that may raise exc def testRun(): try: run() except Error,error: sys.error.write(str(error)) So that I can run a bunch of (possibly failing) tests and still get all worthful info. Now, the drawback is that I then lose python provided traceback, as for any reason str(exc) does not return tracback, only the "message". To have the traceback I planned to catch the traceback manually. The aims whare: * be able to output the tracback prepended to the message, when useful * try to find a more readable (for me) format * filter it: e.g. print only last trace mark of each module If you have ideas on the best way to do this, thanks. I tried to use sys.exc_info() that returns a (type,value,traceback) tuple and the format_tb() function of the traceback module. *Sometimes* I get the traceback as expected and all is fine. But in most cases sys.exc_info() returns (None,None,None) like if there was absolutely no active exception. I cannot consistently reproduce the issue to make a clear diagnosis. Thank you, Denis ------ la vida e estranya From kent37 at tds.net Wed Jan 14 18:31:55 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 14 Jan 2009 12:31:55 -0500 Subject: [Tutor] Selecting first matching element from a list In-Reply-To: <496E120F.2020201@gmail.com> References: <496B6847.9080701@nibrahim.net.in> <496B7C31.9040104@gmail.com> <496DC046.5060604@nibrahim.net.in> <496E120F.2020201@gmail.com> Message-ID: <1c2a2c590901140931i5ec3b7a3o15509b9448c4b4d6@mail.gmail.com> On Wed, Jan 14, 2009 at 11:25 AM, bob gailer wrote: > How many ways are there in Python to go thru a list (and apply a function to > each element)? The ones I know are: > while > for > list comprehension > map() filter() is more appropriate than map() for this problem generator expression itertools functions Kent From kent37 at tds.net Wed Jan 14 18:34:54 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 14 Jan 2009 12:34:54 -0500 Subject: [Tutor] traceback In-Reply-To: <20090114180951.6095bbb3@o> References: <20090114180951.6095bbb3@o> Message-ID: <1c2a2c590901140934pa3bc2c4k622e462ea5754b3b@mail.gmail.com> On Wed, Jan 14, 2009 at 12:09 PM, spir wrote: > Hello, > > I rather often use exceptions as information providers at design or debug time. A typical use > of mine is to have a test version of methods that wrap standard version: > > def run(): > do stuff > that may > raise exc > def testRun(): > try: > run() > except Error,error: > sys.error.write(str(error)) I use traceback.print_exc() for this. Kent From wesbrooks at gmail.com Wed Jan 14 18:53:55 2009 From: wesbrooks at gmail.com (Wesley Brooks) Date: Wed, 14 Jan 2009 17:53:55 +0000 Subject: [Tutor] Small python web server suitable for web cam streams? In-Reply-To: <1c2a2c590901140821q75841c08m4a09965688774013@mail.gmail.com> References: <1c2a2c590901140821q75841c08m4a09965688774013@mail.gmail.com> Message-ID: At the minimum the page would need to display progress through a job, any error messages, and a picture from the web camera. I've used something that grabbed images from a USB camera using python a while back so at the simplest I could be just after something to display a html page with an image and just update the page on the server end once every second or so and rely on the user to hit the refresh to get a new image. For the next level it would be great to have something as above but with a video stream from the camera, and various pages displaying temperatures etc. The very best would have time plots for various temperatures (these of course could be images generated by seperate scripts as before) and email alerts out to users when a job is complete or an error occurs. Is this best solved using two different toolkits? One to make the page and another to host it? Thanks for your help. I'll have a look at CherryPy. Wesley. 2009/1/14 Kent Johnson > On Wed, Jan 14, 2009 at 10:37 AM, Wesley Brooks > wrote: > > I have a machine which runs for extended periods of time, and often into > > days rather than just hours. I would like to set up the computer so that > it > > hosts a simple web page displaying current status information, and a feed > > from a web camera which is viewing the business end of the machine. This > web > > site will not be opened to the wider internet, just kept as open access > to > > all machines on the local network. There is currently no requirement for > any > > control from the user end, just to view the page or pages. > > Will the web server generate the status page and talk to the camera, > or is it just showing static data that comes from somewhere else? > > If the data is generated outside the server you can use IIS or Apache > to display them. If you are generating pages in the server then > something simple like CherryPy might be a good choice, rather than one > of the full-featured web frameworks. > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From damontimm at gmail.com Wed Jan 14 19:27:03 2009 From: damontimm at gmail.com (Damon Timm) Date: Wed, 14 Jan 2009 13:27:03 -0500 Subject: [Tutor] Sys.stdin Question In-Reply-To: <39742.134.134.136.14.1231899038.squirrel@webmail.alchemy.com> References: <262679b50901131634h6d252f78t4f2942d8b45f569e@mail.gmail.com> <262679b50901131759uf2589eem349266cca7b2ecbf@mail.gmail.com> <39742.134.134.136.14.1231899038.squirrel@webmail.alchemy.com> Message-ID: <262679b50901141027p3f44f9c4q52f2cab3dd2310b1@mail.gmail.com> On Tue, Jan 13, 2009 at 9:05 PM, John Fouhy wrote: > It's easy to test: > > ### test.py ### > import time > time.sleep(1) > print 'foo' > ### > > \$ python test.py | python stdintest.py > Nothing to see here. > close failed: [Errno 32] Broken pipe > > [not shown: the 1 second pause after "Nothing to see here." showed up] > > You could "fix" it by adding a delay to your consumer script.. as long > as none of your input scripts take longer than the delay to generate > output. Or do things differently, which might be smarter :-) Yea - I can see where that would become a problem ... hmm ... I think I am going to look into what Steve is suggesting with the fileinput module ... On Tue, Jan 13, 2009 at 9:10 PM, Steve Willoughby wrote: > As the Zen of Python states, "explicit is better than implicit." > > Scripts which just magically "do the right thing" can be cool to play > with, but they have a nasty tendency to guess wrong about what the right > thing might be. In this case, you're making assumptions about how to > *guess* whether there's standard input piped at your script, and running > with those assumptions... but there are easily identified cases where > those assumptions don't hold true. That's a good point ... here is more of what I am trying to do ... minus exceptions and the actual functions that sends the mail ... I could use the "-" stdin bit to either signify the body message of the email, or an attachment ... or, I guess, both ... (I left out the details of actually emailing stuff and all the imports): def sendMail(recipient, subject, text, *attachmentFilePaths): #here is the function used to send the mail and attachments... def main(): parser = OptionParser(usage="%prog [options: -s -t -m ] [attachemnts, if any...]") parser.add_option("-q", "--quiet", action="store_true", dest="quiet") parser.add_option("-s", "--subject", action="store", type="string", dest="subject", default=default_subject) parser.add_option("-t", "--to", action="store", type="string", dest="recipient", default=default_recipient) parser.add_option("-m", "--message", action="store", type="string", dest="message") (options, args) = parser.parse_args() sendMail(options.recipient, options.subject, options.text, args) \$ sendmail.py -t me at me.com -s "my subject" -m - attament.jpg or maybe \$ dmesg | sendmail.py -t me at me.com -s "my subject" -m "here is output from dmesg" - someotherattachmenttoo.doc Thanks for all this help. On Tue, Jan 13, 2009 at 9:10 PM, Steve Willoughby wrote: > On Tue, January 13, 2009 17:59, Damon Timm wrote: >> ... then, I guess, I can just have it do an if statement that asks: if >> args[0] == "-" then ... blah. I may do that ... the script, itself, > > Look at the fileinput module. If you're looking at the command line for a > list of filenames, which may include "-" to mean (read stdin at this point > in the list of files), your script's logic is reduced to simply: > > while line in fileinput.input(): > # process the line > > and your script focuses on its specific task. > >>> or not. So instead of seeing if anything's showing up (and introducing >>> timing dependencies and uncertainty), see if it's attached to a real >>> terminal at all. On Unix, os.isatty(sys.stdin) will tell you this. >> >> Does this concern still apply with John's suggestion? I just tested >> it in my little application and didn't have an issue ... of course, I > > Yes, it does. And in a trivial case, it will usually work. But don't > base your solutions on something that looks like it sorta works most of > the time but isn't really the recommended practice, because it will break > later and you'll spend a lot of time figuring out why it's not being > reliable. > >> I can go to using the "-" option ... although, to be honest, I like >> the idea of the script thinking for itself ... that is: if there is >> stdin, use it -- if not, not ... and, I was thinking of attaching the >> stdin as a text file, if present. And not attaching anything, if not. > > As the Zen of Python states, "explicit is better than implicit." > > Scripts which just magically "do the right thing" can be cool to play > with, but they have a nasty tendency to guess wrong about what the right > thing might be. In this case, you're making assumptions about how to > *guess* whether there's standard input piped at your script, and running > with those assumptions... but there are easily identified cases where > those assumptions don't hold true. > > Also, think of anyone other than you (or you at a later date) using this > script. The number of things the script does for no apparent reason can > lead to frustration and doubt that you really know, as a user, what the > script is really going to try to do in a given situation, and what you'll > have to do on your end to "trick" it into doing what you really wanted in > the first place. It's cute, but ultimately implicit behavior doesn't make > for good, long-lasting solid applications. > > From kent37 at tds.net Wed Jan 14 20:05:24 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 14 Jan 2009 14:05:24 -0500 Subject: [Tutor] Small python web server suitable for web cam streams? In-Reply-To: References: <1c2a2c590901140821q75841c08m4a09965688774013@mail.gmail.com> Message-ID: <1c2a2c590901141105w5dd74c92m1bdf19f1a8ced6be@mail.gmail.com> On Wed, Jan 14, 2009 at 12:53 PM, Wesley Brooks wrote: > The very best would have time plots for various temperatures (these of > course could be images generated by seperate scripts as before) and email > alerts out to users when a job is complete or an error occurs. I've used matplotlib to dynamically create and display charts on a web page. There are also some interesting JavaScript chart packages. smtplib (in the Python lib) can send your emails. > Is this best solved using two different toolkits? One to make the page and > another to host it? I would start out putting it in the server and change it if there are performance problems. Depending on how complex your HTML is, you might want to use one of the template libraries - Mako, Genshi, Jinja, Kid, Cheetah, ... I can't recommend a specific one. Kent From vanden at gmail.com Wed Jan 14 20:20:28 2009 From: vanden at gmail.com (Brian van den Broek) Date: Wed, 14 Jan 2009 14:20:28 -0500 Subject: [Tutor] help with getting python to run from command prompt on Windows XP Message-ID: <496E3AFC.7030909@gmail.com> Hi all, I'm trying, via email, to help a friend set up python on his Windows XP computer. I've been strictly linux for some time now, and don't have a Windows machine on which to investigate. We've hit a problem, and I'd appreciate a push. He's got python 2.6.1 installed as evidenced by the Startbar program icon for Idle launching as expected. When run from IDLE, `print sys.executable' yields `C:\\Python26\\pythonw.exe'. He reports that C:\Python26 contains both python.exe and pythonw.exe. I've had him add the text `;C:\Python26' (without quotes) to the end of his Path environment variable via the Control Panel|System Properties way of editing Environment variables. I've had him reboot afterwards. After all of that, he reports that an attempt to run python from the command prompt produces a complaint that `` `python' is not recognized as an internal or external command, operable program or batch file.'' Can someone with Windows knowledge please tell me what I am missing? Am I wrong in recalling that from the command prompt on Windows, one wants python, rather than pythonw? (I seem to recollect that pythonw.exe is what you associate with .py files to prevent a double-click on a .py icon from producing the `DOS box flash' and *not* what one wants to use from the prompt itself.) Thanks and best, Brian vdB From broek at cc.umanitoba.ca Wed Jan 14 20:36:20 2009 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Wed, 14 Jan 2009 14:36:20 -0500 Subject: [Tutor] help with getting python to run from command prompt on Windows XP Message-ID: <496E3EB4.20207@cc.umanitoba.ca> Hi all, I'm trying, via email, to help a friend set up python on his Windows XP computer. I've been strictly linux for some time now, and don't have a Windows machine on which to investigate. We've hit a problem, and I'd appreciate a push. He's got python 2.6.1 installed as evidenced by the Startbar program icon for Idle launching as expected. When run from IDLE, `print sys.executable' yields `C:\\Python26\\pythonw.exe'. He reports that C:\Python26 contains both python.exe and pythonw.exe. I've had him add the text `;C:\Python26' (without quotes) to the end of his Path environment variable via the Control Panel|System Properties way of editing Environment variables. I've had him reboot afterwards. After all of that, he reports that an attempt to run python from the command prompt produces a complaint that `` `python' is not recognized as an internal or external command, operable program or batch file.'' Can someone with Windows knowledge please tell me what I am missing? Am I wrong in recalling that from the command prompt on Windows, one wants python, rather than pythonw? (I seem to recollect that pythonw.exe is what you associate with .py files to prevent a double-click on a .py icon from producing the `DOS box flash' and *not* what one wants to use from the prompt itself.) Thanks and best, Brian vdB From kent37 at tds.net Wed Jan 14 21:01:50 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 14 Jan 2009 15:01:50 -0500 Subject: [Tutor] help with getting python to run from command prompt on Windows XP In-Reply-To: <496E3EB4.20207@cc.umanitoba.ca> References: <496E3EB4.20207@cc.umanitoba.ca> Message-ID: <1c2a2c590901141201q3a771d15o48336f61a44cc82d@mail.gmail.com> On Wed, Jan 14, 2009 at 2:36 PM, Brian van den Broek wrote: > Hi all, > > I'm trying, via email, to help a friend set up python on his Windows > XP computer. I've been strictly linux for some time now, and don't > have a Windows machine on which to investigate. We've hit a problem, > and I'd appreciate a push. > > He's got python 2.6.1 installed as evidenced by the Startbar program > icon for Idle launching as expected. When run from IDLE, `print > sys.executable' yields `C:\\Python26\\pythonw.exe'. > He reports that C:\Python26 contains both python.exe and pythonw.exe. > > I've had him add the text `;C:\Python26' (without quotes) to the end > of his Path environment variable via the Control Panel|System > Properties way of editing Environment variables. I've had him reboot > afterwards. > > After all of that, he reports that an attempt to run python from the > command prompt produces a complaint that `` `python' is not recognized > as an internal or external command, operable program or batch file.'' > > Can someone with Windows knowledge please tell me what I am missing? > Am I wrong in recalling that from the command prompt on Windows, one > wants python, rather than pythonw? (I seem to recollect that > pythonw.exe is what you associate with .py files to prevent a > double-click on a .py icon from producing the `DOS box flash' and > *not* what one wants to use from the prompt itself.) It sounds to me like you have asked him to do the right thing. I would try - check the Path setting by typing 'set path' at a command prompt and verify that C:\Python26 is in the displayed path - try running Python with a full path, i.e. at the command prompt try 'C:\Python26\python.exe' Kent From wescpy at gmail.com Wed Jan 14 21:09:27 2009 From: wescpy at gmail.com (wesley chun) Date: Wed, 14 Jan 2009 12:09:27 -0800 Subject: [Tutor] help with getting python to run from command prompt on Windows XP In-Reply-To: <1c2a2c590901141201q3a771d15o48336f61a44cc82d@mail.gmail.com> References: <496E3EB4.20207@cc.umanitoba.ca> <1c2a2c590901141201q3a771d15o48336f61a44cc82d@mail.gmail.com> Message-ID: <78b3a9580901141209r5c8b4d42pab71a3ce07b8f6d4@mail.gmail.com> On Wed, Jan 14, 2009 at 12:01 PM, Kent Johnson wrote: > On Wed, Jan 14, 2009 at 2:36 PM, Brian van den Broek > wrote: >> >> He's got python 2.6.1 installed as evidenced by the Startbar program >> icon for Idle launching as expected. When run from IDLE, `print >> sys.executable' yields `C:\\Python26\\pythonw.exe'. >> He reports that C:\Python26 contains both python.exe and pythonw.exe. >> >> I've had him add the text `;C:\Python26' (without quotes) to the end >> of his Path environment variable via the Control Panel|System >> Properties way of editing Environment variables. I've had him reboot >> afterwards. >> >> After all of that, he reports that an attempt to run python from the >> command prompt produces a complaint that `` `python' is not recognized >> as an internal or external command, operable program or batch file.'' > > It sounds to me like you have asked him to do the right thing. I would try > - check the Path setting by typing 'set path' at a command prompt and > verify that C:\Python26 is in the displayed path > - try running Python with a full path, i.e. at the command prompt try > 'C:\Python26\python.exe' i fully agree with kent's comments/suggestions. you appeared to have them do the right thing. fwiw, the only time i run into that error after doing the same thing as you is that i'm trying that command in an already-opened command window -- i need to close that and open another that takes in the changes to the environment variables. but you did tell them to reboot, so this shouldn't be your problem. also, i think (but cannot confirm as i'm on a mac now that) there are two PATH env vars... one for the current user and one for all users (if you have administrative privileges. good luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From w.richert at gmx.net Wed Jan 14 21:19:11 2009 From: w.richert at gmx.net (Willi Richert) Date: Wed, 14 Jan 2009 21:19:11 +0100 Subject: [Tutor] traceback In-Reply-To: <20090114180951.6095bbb3@o> References: <20090114180951.6095bbb3@o> Message-ID: <200901142119.11994.w.richert@gmx.net> Hi, do you observe the same behavior with traceback.format_exc()? I've used that always in such situations which worked all the time. Regards, wr Am Mittwoch, 14. Januar 2009 18:09:51 schrieb spir: > Hello, > > I rather often use exceptions as information providers at design or debug > time. A typical use of mine is to have a test version of methods that wrap > standard version: > > def run(): > do stuff > that may > raise exc > def testRun(): > try: > run() > except Error,error: > sys.error.write(str(error)) > > So that I can run a bunch of (possibly failing) tests and still get all > worthful info. Now, the drawback is that I then lose python provided > traceback, as for any reason str(exc) does not return tracback, only the > "message". To have the traceback I planned to catch the traceback manually. > The aims whare: > * be able to output the tracback prepended to the message, when useful > * try to find a more readable (for me) format > * filter it: e.g. print only last trace mark of each module > If you have ideas on the best way to do this, thanks. > > I tried to use sys.exc_info() that returns a (type,value,traceback) tuple > and the format_tb() function of the traceback module. *Sometimes* I get the > traceback as expected and all is fine. But in most cases sys.exc_info() > returns (None,None,None) like if there was absolutely no active exception. > I cannot consistently reproduce the issue to make a clear diagnosis. > > Thank you, > Denis > > ------ > la vida e estranya > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From vceder at canterburyschool.org Wed Jan 14 21:38:20 2009 From: vceder at canterburyschool.org (Vern Ceder) Date: Wed, 14 Jan 2009 15:38:20 -0500 Subject: [Tutor] Python3.0 and Tkinter on ubuntu 8.10 HOWTO In-Reply-To: <652641e90901131332g60caaa70l5490a85cb49972f2@mail.gmail.com> References: <496D0178.8000009@canterburyschool.org> <652641e90901131332g60caaa70l5490a85cb49972f2@mail.gmail.com> Message-ID: <496E4D3C.1000301@canterburyschool.org> Since there was some interest in the question of how to get a full Python 3.0, including Tkinter and IDLE, compiled on Ubuntu Intrepid 8.10, I've written up what I've done and posted it at http://learnpython.wordpress.com/2009/01/14/installing-python-30-on-ubuntu/ Cheers, Vern Ceder -- This time for sure! -Bullwinkle J. Moose ----------------------------- Vern Ceder, Director of Technology Canterbury School, 3210 Smith Road, Ft Wayne, IN 46804 vceder at canterburyschool.org; 260-436-0746; FAX: 260-436-5137 From bermanrl at cfl.rr.com Wed Jan 14 21:53:15 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Wed, 14 Jan 2009 15:53:15 -0500 Subject: [Tutor] Python3.0 and Tkinter on ubuntu 8.10 HOWTO In-Reply-To: <496E4D3C.1000301@canterburyschool.org> References: <496D0178.8000009@canterburyschool.org> <652641e90901131332g60caaa70l5490a85cb49972f2@mail.gmail.com> <496E4D3C.1000301@canterburyschool.org> Message-ID: <496E50BB.6040601@cfl.rr.com> Very good and most welcome. Robert Berman Vern Ceder wrote: > Since there was some interest in the question of how to get a full > Python 3.0, including Tkinter and IDLE, compiled on Ubuntu Intrepid > 8.10, I've written up what I've done and posted it at > http://learnpython.wordpress.com/2009/01/14/installing-python-30-on-ubuntu/ > > > Cheers, > Vern Ceder > From marc.tompkins at gmail.com Wed Jan 14 22:06:18 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Wed, 14 Jan 2009 13:06:18 -0800 Subject: [Tutor] help with getting python to run from command prompt on Windows XP In-Reply-To: <78b3a9580901141209r5c8b4d42pab71a3ce07b8f6d4@mail.gmail.com> References: <496E3EB4.20207@cc.umanitoba.ca> <1c2a2c590901141201q3a771d15o48336f61a44cc82d@mail.gmail.com> <78b3a9580901141209r5c8b4d42pab71a3ce07b8f6d4@mail.gmail.com> Message-ID: <40af687b0901141306n66fa4787ma3a6844dae5938ac@mail.gmail.com> On Wed, Jan 14, 2009 at 12:09 PM, wesley chun wrote: > > i fully agree with kent's comments/suggestions. you appeared to have > them do the right thing. fwiw, the only time i run into that error > after doing the same thing as you is that i'm trying that command in > an already-opened command window -- i need to close that and open > another that takes in the changes to the environment variables. but > you did tell them to reboot, so this shouldn't be your problem. > > also, i think (but cannot confirm as i'm on a mac now that) there are > two PATH env vars... one for the current user and one for all users > (if you have administrative privileges. > > - As wesley said, you don't have to reboot anymore (as you did in the old days when you set environment variables through AUTOEXEC.BAT). Changes to environment variables take effect as soon as you click Apply or OK, but they only affect subsequently-opened command prompts - so if you have a prompt open, just close it and open a new one. Rebooting will certainly do the trick, but if you need to try more than once, this will save a LOT of time. - Also as wesley said, there MAY BE two separate PATHs - in my experience, the user-level one is usually empty and can be deleted to avoid confusion. If it's _not_ empty, it's usually by mistake... (there may be exceptions, but every single time I've seen a program that added something to the user-level path, it's turned out to have been unintentional.) - There's also a PATHEXT variable that holds a list of extensions that Windows should consider executable - its contents should look like this: ".COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH" If something has edited this variable and removed .EXE from the list... - The #1 problem I run into in providing telephone support is misunderstandings over the names of punctuation characters. I hate to ask, but is there a possibility of confusion between the colon and semicolon? (e.g. ":C;\Python26" instead of ";C:\Python26") That would do it... -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From jjcrump at myuw.net Wed Jan 14 23:14:15 2009 From: jjcrump at myuw.net (Jon Crump) Date: Wed, 14 Jan 2009 14:14:15 -0800 (PST) Subject: [Tutor] quoting and escaping In-Reply-To: <1c2a2c590901131913i3cba55f6k642fafc557a6d8a0@mail.gmail.com> References: <1c2a2c590901131913i3cba55f6k642fafc557a6d8a0@mail.gmail.com> Message-ID: Kent, Steve, Marty, et alia, On Tue, 13 Jan 2009, Kent Johnson wrote: > Where does this come from? It looks like the string representation of > a dict. Can you get the actual dict? Perhaps there is a better way to > do whatever you are doing? It does look like that doesn't it, but it's actually a javascript object in a file Itinerary.js This file is in the format expected by the Simile Timeline software (if you're interested, you can see the working web application at ). The data for this application was prepared by means of a python script that you all have been helping me with from time to time. The script isn't pretty and bears everywhere the marks of inexperience, but I've learned a lot doing it and it works. Having created the js file, I found that I might wish to edit the data in a variety of ways, so I thought, well, it looks like a python dictionary, maybe I can make it act like one. simplejson.loads() was the obvious thing to try, but since the data format isn't really json that didn't work. The new Date() object declarations needed to be modified to look like datetime.date() instances. Marty Walsh very helpfully reminded me that re.sub() can take a function as its first argument, so once I got the regex string right, it was easy to turn new Date(1216,9,18) into "datetime.date(12,10,18)". In experimenting at the interpreter command line I was confused by the fact that the interpreter was interpreting the escaped quotation marks in my string fragment rather than rendering the escape character. Steve Willoughby's kind message explained the business of 'raw' strings which put me on the right track to understanding what was happening. In the event, however, the escapes were not a problem because file.read() returns a raw string. So now I can put the pieces together and do this: >>> itin = file('/PathToFile/Itinerary.js', 'r') >>> >>> jdate = re.compile('new Date\((\d{4}),(\d{1,2}),(\d{1,2})\)') >>> >>> def repldate(match): ... y, m, d = map(int, match.groups()) ... return '\"date(%04d, %02d, %02d)\"' % (y, m+1, d) ... >>> print type(eval(jdate.sub(repldate, itin.read()))) And that's what I wanted all along. I'm mindful of the security implications of eval() and understand that it's bad form, but since this processing is entirely internal I don't think that'll be a problem. I agree that there's probably a better way of doing things, especially in the generation of Itinerary.js in the first place. Creating in python a data structure for another language by means of string formatting seemed like a kluge to me even at the time, but being the tyro that I am, I didn't know how else to proceed. The data file in question is at and the python used for the original text processing is in the same directory at itin-processing.py. It's a big ugly mess full of naive notes to myself, if anyone cares to look at it and offer any comments or advice I could not be anything but grateful. I've learned so much from you guys, and thank you Kent for following up, but, given my long-windedness, aren't you sorry you asked? ;-) Thanks again, Jon From emadnawfal at gmail.com Wed Jan 14 23:39:43 2009 From: emadnawfal at gmail.com (=?WINDOWS-1256?Q?Emad_Nawfal_(=DA=E3=C7=CF_=E4=E6=DD=E1)?=) Date: Wed, 14 Jan 2009 17:39:43 -0500 Subject: [Tutor] Python3.0 and Tkinter on ubuntu 8.10 HOWTO In-Reply-To: <496E50BB.6040601@cfl.rr.com> References: <496D0178.8000009@canterburyschool.org> <652641e90901131332g60caaa70l5490a85cb49972f2@mail.gmail.com> <496E4D3C.1000301@canterburyschool.org> <496E50BB.6040601@cfl.rr.com> Message-ID: <652641e90901141439q1acbf00o4f6e1d1f287b0aa2@mail.gmail.com> Great source for Unicode lovers On Wed, Jan 14, 2009 at 3:53 PM, Robert Berman wrote: > Very good and most welcome. > > Robert Berman > > Vern Ceder wrote: > >> Since there was some interest in the question of how to get a full Python >> 3.0, including Tkinter and IDLE, compiled on Ubuntu Intrepid 8.10, I've >> written up what I've done and posted it at >> http://learnpython.wordpress.com/2009/01/14/installing-python-30-on-ubuntu/ >> >> Cheers, >> Vern Ceder >> >> _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From s4027340 at student.uq.edu.au Thu Jan 15 01:14:28 2009 From: s4027340 at student.uq.edu.au (Mr Gerard Kelly) Date: Thu, 15 Jan 2009 10:14:28 +1000 Subject: [Tutor] strings and int() Message-ID: If you have a string "6", and you do int("6"), you get the number 6. But if you have a string "2*3" and you do int("2*3") you get a name error. How do you take an expression in a string, and evaluate the expression to get a number? I want to be able to turn the string "2*3" into the number 6. thanks From alan.gauld at btinternet.com Thu Jan 15 01:27:00 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Jan 2009 00:27:00 -0000 Subject: [Tutor] lists and Entry References: Message-ID: "Mr Gerard Kelly" wrote > There is a little Tkinter program. It lets you type something in a > box, > and will display it at the command line. > > e = Entry(master) > e.pack() > def callback(): > s=e.get() > print s > > b = Button(master, text="get", width=10, command=callback) > The get() method returns a string, how do I make it return a list? You don't. The Entry widget returns a list just like you get when you use raw_input() in a console program. Its up to you to parse and convert that string into whatever you require. You can use other widget types of course and they return slightly different types of data but they will all generally be string oriented. An editable list entry can return a list of strings for example... This is not really a fault of Tkinter BTW, its how nearly all GUIs work. They just capture what the user types and display strings that you provide. The processing of those input and output strings is the "business logic" of your program - in other words its up to you! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Thu Jan 15 01:34:14 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Jan 2009 00:34:14 -0000 Subject: [Tutor] help with getting python to run from command prompt onWindows XP References: <496E3AFC.7030909@gmail.com> Message-ID: "Brian van den Broek" wrote > icon for Idle launching as expected. When run from IDLE, `print > sys.executable' yields `C:\\Python26\\pythonw.exe'. > He reports that C:\Python26 contains both python.exe and > pythonw.exe. > > I've had him add the text `;C:\Python26' (without quotes) to the end > of his Path environment variable via the Control Panel|System > Properties way of editing Environment variables. I've had him reboot > afterwards. Get him to type SET > env.txt at the DOS prompt that should list all environment variables into env.txt Get him to email that file to you and check what it says about PATH. > After all of that, he reports that an attempt to run python from the > command prompt produces a complaint that `` `python' is not > recognized as an internal or external command, operable program or > batch file.'' What happens if he types C:PROMPT> C:\Python26\python.exe In other words uses the full path? > Can someone with Windows knowledge please tell me what I am missing? Nothing so far as I can tell, but from experience you need to double check the settings at every stage, its very easy to make a mistake - like using a colon instead of semi colon etc. > pythonw.exe is what you associate with .py files to prevent a > double-click on a .py icon from producing the `DOS box flash' and > *not* what one wants to use from the prompt itself.) pythonw is used for running GUI apps without a console appearing in the background. You definitely don;t want to runpythonw from the command line! -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk From jadrifter at gmail.com Thu Jan 15 01:37:39 2009 From: jadrifter at gmail.com (jadrifter) Date: Wed, 14 Jan 2009 16:37:39 -0800 Subject: [Tutor] strings and int() In-Reply-To: References: Message-ID: <1231979859.6496.6.camel@ltop> Try eval("2*3") On Thu, 2009-01-15 at 10:14 +1000, Mr Gerard Kelly wrote: > If you have a string "6", and you do int("6"), you get the number 6. > > But if you have a string "2*3" and you do int("2*3") you get a name error. > > How do you take an expression in a string, and evaluate the expression > to get a number? > > I want to be able to turn the string "2*3" into the number 6. > > thanks > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Thu Jan 15 01:42:40 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Jan 2009 00:42:40 -0000 Subject: [Tutor] help with getting python to run from command prompt onWindows XP References: <496E3EB4.20207@cc.umanitoba.ca><1c2a2c590901141201q3a771d15o48336f61a44cc82d@mail.gmail.com><78b3a9580901141209r5c8b4d42pab71a3ce07b8f6d4@mail.gmail.com> <40af687b0901141306n66fa4787ma3a6844dae5938ac@mail.gmail.com> Message-ID: "Marc Tompkins" wrote > - Also as wesley said, there MAY BE two separate PATHs - in my > experience, > the user-level one is usually empty and can be deleted to avoid > confusion. > If it's _not_ empty, it's usually by mistake... It should be used where multiple users use a single machine and they each install their own programs for their own exclusive use. Then the programs will set the local path not the all-user one. Unfortunately XP tends to spoil the usefulness of this by making users administrators by default instead of regular users or power users! Administrators install things for all users by default... It has always frustrated me that Microsoft took a decision that effectively bypassed one of the most powerful security devices on a multi user computer by making Admin rights the default! And then compounded it by making the only other option so brain dead nobody would use it! How many ordinary PC owners are going to go to the hassle of starting up the policy editor etc to access the other levels of access that XP provides?? And thats assuming you have XP Pro.... XP Home users dont even get the policy editor. Alan G. From artie.ziff at gmail.com Thu Jan 15 01:44:11 2009 From: artie.ziff at gmail.com (Artie Ziff) Date: Wed, 14 Jan 2009 16:44:11 -0800 Subject: [Tutor] running & debugging in python interactive shell Message-ID: <496E86DB.20202@gmail.com> Greetings. I am attempting to search archives, however I thought it would be OK to ask while I search... thank you to those who responded to my previous inquiry. Your response was very helpful to me. My environment is embedded so I have only a python interactive shell for running python scripts. Does anyone know of an article that describes best practices for running and debugging scripts inside the python shell? Of course, I use import directive to run my script for first run. I am seeking techniques for invoking parts of script after initial import. I hope this makes sense to those persons reading. :) Cheers, AZ From s4027340 at student.uq.edu.au Thu Jan 15 03:19:04 2009 From: s4027340 at student.uq.edu.au (Mr Gerard Kelly) Date: Thu, 15 Jan 2009 12:19:04 +1000 Subject: [Tutor] eval and floating point Message-ID: Thanks very much I've noticed that the eval() function gives an integer, so eval("3/2") gives back 1. float(eval("3/2")) doesn't seem to work, any way to get a floating point number back with eval()? I know you can just do ("3./2."), but is there any way to do it with just ("3/2")? From pine508 at hotmail.com Thu Jan 15 03:18:30 2009 From: pine508 at hotmail.com (Che M) Date: Wed, 14 Jan 2009 21:18:30 -0500 Subject: [Tutor] running & debugging in python interactive shell In-Reply-To: <496E86DB.20202@gmail.com> References: <496E86DB.20202@gmail.com> Message-ID: > Date: Wed, 14 Jan 2009 16:44:11 -0800 > From: artie.ziff at gmail.com > To: tutor at python.org > Subject: [Tutor] running & debugging in python interactive shell > > Greetings. > > I am attempting to search archives, however I thought it would be OK to > ask while I search... thank you to those who responded to my previous > inquiry. Your response was very helpful to me. > > My environment is embedded so I have only a python interactive shell for > running python scripts. Does anyone know of an article that describes > best practices for running and debugging scripts inside the python > shell? Of course, I use import directive to run my script for first run. > I am seeking techniques for invoking parts of script after initial > import. I hope this makes sense to those persons reading. :) > > Cheers, > AZ I'd like to add to this question and expand it: can anyone point me to a good resource on debugging *generally*? Particularly using a debugger. I have never learned any "right" way to debug my code, just sort of read off the errors generated and do what I can. I use Boa Constructor, which has a built-in debugger, but I don't quite grok how best to use it (some of that is lack of practice, some is lack of understanding), though I get the sense that they are more-or-less the same across IDEs. I thought maybe there is an existing tutorial somewhere on how best to make use of a debugger. Thanks, Che _________________________________________________________________ Windows Live?: Keep your life in sync. http://windowslive.com/howitworks?ocid=TXT_TAGLM_WL_t1_allup_howitworks_012009 -------------- next part -------------- An HTML attachment was scrubbed... URL: From jervisau at gmail.com Thu Jan 15 03:26:29 2009 From: jervisau at gmail.com (Jervis Whitley) Date: Thu, 15 Jan 2009 13:26:29 +1100 Subject: [Tutor] eval and floating point In-Reply-To: References: Message-ID: <8e63a5ce0901141826w73ee61efs8c71853763d5aab5@mail.gmail.com> On Thu, Jan 15, 2009 at 1:19 PM, Mr Gerard Kelly wrote: > Thanks very much > > I've noticed that the eval() function gives an integer, so eval("3/2") > gives back 1. float(eval("3/2")) doesn't seem to work, any way to get a > floating point number back with eval()? > > I know you can just do ("3./2."), but is there any way to do it with > just ("3/2")? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Hi, at the top of your script you can write: from __future__ import division now >>> eval("4/3") 1.33333 You can read up on it here if you are interested.. http://www.python.org/dev/peps/pep-0238/ Cheers -------------- next part -------------- An HTML attachment was scrubbed... URL: From vceder at canterburyschool.org Thu Jan 15 03:31:13 2009 From: vceder at canterburyschool.org (Vern Ceder) Date: Wed, 14 Jan 2009 21:31:13 -0500 Subject: [Tutor] eval and floating point In-Reply-To: References: Message-ID: <496E9FF1.6070805@canterburyschool.org> Mr Gerard Kelly wrote: > Thanks very much > > I've noticed that the eval() function gives an integer, so eval("3/2") > gives back 1. float(eval("3/2")) doesn't seem to work, any way to get a > floating point number back with eval()? > > I know you can just do ("3./2."), but is there any way to do it with > just ("3/2")? If you are using a current version of Python, the line: from __future__ import division will make division with the "/" return a float; you then use "//" for integer division.... >>> from __future__ import division >>> eval("3/2") 1.5 >>> eval("3//2") 1 >>> Cheers, Vern -- This time for sure! -Bullwinkle J. Moose ----------------------------- Vern Ceder, Director of Technology Canterbury School, 3210 Smith Road, Ft Wayne, IN 46804 vceder at canterburyschool.org; 260-436-0746; FAX: 260-436-5137 From jadrifter at gmail.com Thu Jan 15 03:33:06 2009 From: jadrifter at gmail.com (jadrifter) Date: Wed, 14 Jan 2009 18:33:06 -0800 Subject: [Tutor] eval and floating point In-Reply-To: References: Message-ID: <1231986786.6496.12.camel@ltop> On Thu, 2009-01-15 at 12:19 +1000, Mr Gerard Kelly wrote: > Thanks very much > > I've noticed that the eval() function gives an integer, so eval("3/2") > gives back 1. float(eval("3/2")) doesn't seem to work, any way to get a > floating point number back with eval()? > > I know you can just do ("3./2."), but is there any way to do it with > just ("3/2")? That's not the eval function returning that integer so much as it is Python itself. You might try: eval ("1.0 * 3/2") From bill at celestial.net Thu Jan 15 05:12:31 2009 From: bill at celestial.net (Bill Campbell) Date: Wed, 14 Jan 2009 20:12:31 -0800 Subject: [Tutor] eval and floating point In-Reply-To: <1231986786.6496.12.camel@ltop> References: <1231986786.6496.12.camel@ltop> Message-ID: <20090115041231.GA8730@ayn.mi.celestial.com> On Wed, Jan 14, 2009, jadrifter wrote: >On Thu, 2009-01-15 at 12:19 +1000, Mr Gerard Kelly wrote: >> Thanks very much >> >> I've noticed that the eval() function gives an integer, so eval("3/2") >> gives back 1. float(eval("3/2")) doesn't seem to work, any way to get a >> floating point number back with eval()? >> >> I know you can just do ("3./2."), but is there any way to do it with >> just ("3/2")? > >That's not the eval function returning that integer so much as it is >Python itself. You might try: >eval ("1.0 * 3/2") Make either the numerator or denominator floating point. eval ('3.0/2') Python does the Right Thing(tm) when dividing two integers, returning an integer result. Bill -- INTERNET: bill at celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax: (206) 232-9186 The essence of all slavery consists in taking the produce of another's labor by force. It is immaterial whether this force be founded on ownership of the slave or ownership of the money that he must get to live on. Leo Tolstoy 1891 From s4027340 at student.uq.edu.au Thu Jan 15 06:41:32 2009 From: s4027340 at student.uq.edu.au (Mr Gerard Kelly) Date: Thu, 15 Jan 2009 15:41:32 +1000 Subject: [Tutor] tkinter canvas Message-ID: I am trying to make a simple Tkinter program using the canvas widget. All it does take a number (6 in this case) and draw that number of blue boxes on a canvas. from Tkinter import * master = Tk() numboxes=6 width=40*(numboxes+2) height=200 w = Canvas(master, width=width, height=height) w.pack() size=width/(numboxes+2) box=[0]*numboxes for i in range(numboxes): box[i]=w.create_rectangle((1+i)*40, 40, (2+i)*40, height-40, fill="blue") mainloop() I want to be able to bind these boxes to an event - so that I can either click on them, or hold the mouse cursor over them, and have them change color. However I haven't been able to find any examples of related tkinter code on google, and the tutorials and documentation about binding and events with canvas items is very confusing without being able to see it used in examples. From andorphin at gmail.com Thu Jan 15 07:00:58 2009 From: andorphin at gmail.com (David Williams) Date: Wed, 14 Jan 2009 22:00:58 -0800 Subject: [Tutor] Non-blocking non-interactive graphics display Message-ID: <4a289b480901142200k3e376eaeg39de1ed8de1e239c@mail.gmail.com> Hi All, I am still getting my python legs (similar to sea legs but more scale-y) and ran across a decision that I'd like some advice on. I am looking for the simplest way of displaying a little positional data as a line graphic in a window as a script runs. Something like: #Set up some points pt1 = (0,0) pt2 = (2,1) pt3 = (3,2) #Create a window that displays the points as two lines connected at pt2 import somethingsomething #maybe something like import enthought.enable window = somethingsomething.graph_points_as_line(pt1,pt2,pt3) #Iterate for i in range(0,100): #Change the points slightly, this takes a bit of time [pt1, pt2, pt3] = update_points_with_derived_values(pt1,pt2,pt3) #Update the display window.graph_points(pt1,pt2,pt3) My problem is that using tkinter, it looks to be a bit difficult to get this to work since showing the window blocks the rest of the script from running. I am not terribly familiar with threads and keen to avoid them if they are unnecessary. The display is non-interactive and so communication with it can be one-way. Ideally I would just be able to get some interaction with a library that is similar to processing (the graphics environment) which just lets me throw some graphics primitives at it and gives me a nice window or saved file. Bonus points if it is part of the Enthought Python Distribution and pleasingly anti-aliased. Does anyone have any recommendations for a package to use for this and a pointer to a particularly good tutorial or snippet of sample code? Thanks much, Dave From agent.krycek at gmail.com Thu Jan 15 07:29:14 2009 From: agent.krycek at gmail.com (Alex Krycek) Date: Wed, 14 Jan 2009 23:29:14 -0700 Subject: [Tutor] Creating simple windows in XP Message-ID: Hello, I'd like to create very simple GUI's in XP. For the sake of simplicity, I'm trying to avoid downloading and installing anything (although I am considering EasyGui). To see how well it works, I've tried having my program run a Visual Basic script ( i.e. subprocess.call(someScript.vbs, shell = True) ). It seemed to work ok. I was just wondering if there was a better and/or easier way of doing this. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From wescpy at gmail.com Thu Jan 15 08:08:53 2009 From: wescpy at gmail.com (wesley chun) Date: Wed, 14 Jan 2009 23:08:53 -0800 Subject: [Tutor] strings and int() In-Reply-To: References: Message-ID: <78b3a9580901142308ve703477ob12aa94e373a3550@mail.gmail.com> > If you have a string "6", and you do int("6"), you get the number 6. > But if you have a string "2*3" and you do int("2*3") you get a name error. the reason you get this error is because "2*3" is not a string representation of an integer whereas "6" is. in other words 2*3 is not a number. > How do you take an expression in a string, and evaluate the expression to get a number? you just said the answer yourself... *evaluate the expression*. to do just that, use the eval() built-in function. eval("2*3") takes that string, turns it into Python executable code and returns the expression that results from the evaluation of that code. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From ballerz4ishi at sbcglobal.net Thu Jan 15 08:14:16 2009 From: ballerz4ishi at sbcglobal.net (Ishan Puri) Date: Wed, 14 Jan 2009 23:14:16 -0800 (PST) Subject: [Tutor] NLTK Message-ID: <37301.92756.qm@web83304.mail.sp1.yahoo.com> Hi, I have download NLTK for Python 2.5. It download automatically to C:\Program Files\Python25\libs\site-packages\nltk. When I try to open a module in python, it says that no such module exists. What do I need to do? -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Thu Jan 15 09:05:28 2009 From: andreengels at gmail.com (Andre Engels) Date: Thu, 15 Jan 2009 09:05:28 +0100 Subject: [Tutor] strings and int() In-Reply-To: References: Message-ID: <6faf39c90901150005o7dc91624h45ff04ca36bf8088@mail.gmail.com> On Thu, Jan 15, 2009 at 1:14 AM, Mr Gerard Kelly wrote: > If you have a string "6", and you do int("6"), you get the number 6. > > But if you have a string "2*3" and you do int("2*3") you get a name error. > > How do you take an expression in a string, and evaluate the expression > to get a number? > > I want to be able to turn the string "2*3" into the number 6. There is a method for that, namely eval. eval("2*3") evaluates 2*3 as a Python expression and thus gives the integer 6. However, usage of eval is very much discouraged, because it is a very unsafe function. The problem is that a Python expression can be formed to do whatever Python can, and that's a lot. If you use it on something coming from outside the program, you open up your program to an attack by providing malevolent data. If you use it on something from inside your program, it is usually is better to look more precisely on what you are creating. Still, I guess it could be used provided that you _first_ check whether the string is of a form that does not have anything dangerous coming from it. In your case, you might execute eval only if the string that it is to be executed on consists only of numbers and the characters -+/*%(). I _think_ there is nothing bad that can happen then. -- Andr? Engels, andreengels at gmail.com From orsenthil at gmail.com Thu Jan 15 11:04:25 2009 From: orsenthil at gmail.com (Senthil Kumaran) Date: Thu, 15 Jan 2009 15:34:25 +0530 Subject: [Tutor] NLTK In-Reply-To: <37301.92756.qm@web83304.mail.sp1.yahoo.com> References: <37301.92756.qm@web83304.mail.sp1.yahoo.com> Message-ID: <7c42eba10901150204t3e7379eeqf9f78509136367fb@mail.gmail.com> > Ishan Puri wrote: > Hi, > I have download NLTK for Python 2.5. It download automatically to > C:\Program Files\Python25\libs\site-packages\nltk. When I try to open a > module in python, it says that no such module exists. What do I need to do? There are ways to install the module in the site-packages. Just downloading and copying to site-packages may not be enough. After you have downloaded the NLTK page, extract it to a separate directory, and find a file called setup.py If it is present, do python setup.py install That sould do. If setup.py is not present, locate README.txt and follow the instructions. Even after following the instructions, if you get any error message, copy/paste the error message here so that we would be able to assist you better. -- Senthil From orsenthil at gmail.com Thu Jan 15 11:13:09 2009 From: orsenthil at gmail.com (Senthil Kumaran) Date: Thu, 15 Jan 2009 15:43:09 +0530 Subject: [Tutor] eval and floating point In-Reply-To: <20090115041231.GA8730@ayn.mi.celestial.com> References: <1231986786.6496.12.camel@ltop> <20090115041231.GA8730@ayn.mi.celestial.com> Message-ID: <7c42eba10901150213k6824820ehc067cd15e1098c44@mail.gmail.com> On Thu, Jan 15, 2009 at 9:42 AM, Bill Campbell wrote: > Python does the Right Thing(tm) when dividing two integers, > returning an integer result. > Unless it is python 3k, in which integer division (single /) can result in float. Because int is a long by default. :-) -- Senthil From denis.spir at free.fr Thu Jan 15 11:54:50 2009 From: denis.spir at free.fr (spir) Date: Thu, 15 Jan 2009 11:54:50 +0100 Subject: [Tutor] traceback In-Reply-To: <200901142119.11994.w.richert@gmx.net> References: <20090114180951.6095bbb3@o> <200901142119.11994.w.richert@gmx.net> Message-ID: <20090115115450.4fcab2c6@o> Le Wed, 14 Jan 2009 21:19:11 +0100, Willi Richert a ?crit : > Hi, > > do you observe the same behavior with traceback.format_exc()? I've used that > always in such situations which worked all the time. > > Regards, > wr Actually yes, for the traceback object returned by sys.exc_info() is None. (sys.exc_info() --> (None,None,None)). Like if there was no exception raised, or like if it had been clear()ed. But when I don't catch the exception launched by a test program, I get the standard python error message and the prog stops -- which proves that there *is* an active exception. Simply, I cannot have it returned by sys.exc_info(). I will try more today to understand why/when/how this happens. As I said, in some circomstances all works well (sys.exc_info() returns a filled (type,value,traceback) tuple) but as of now I cannot understand why. Denis > Am Mittwoch, 14. Januar 2009 18:09:51 schrieb spir: > > Hello, > > > > I rather often use exceptions as information providers at design or debug > > time. A typical use of mine is to have a test version of methods that wrap > > standard version: > > > > def run(): > > do stuff > > that may > > raise exc > > def testRun(): > > try: > > run() > > except Error,error: > > sys.error.write(str(error)) > > > > So that I can run a bunch of (possibly failing) tests and still get all > > worthful info. Now, the drawback is that I then lose python provided > > traceback, as for any reason str(exc) does not return tracback, only the > > "message". To have the traceback I planned to catch the traceback manually. > > The aims whare: > > * be able to output the tracback prepended to the message, when useful > > * try to find a more readable (for me) format > > * filter it: e.g. print only last trace mark of each module > > If you have ideas on the best way to do this, thanks. > > > > I tried to use sys.exc_info() that returns a (type,value,traceback) tuple > > and the format_tb() function of the traceback module. *Sometimes* I get the > > traceback as expected and all is fine. But in most cases sys.exc_info() > > returns (None,None,None) like if there was absolutely no active exception. > > I cannot consistently reproduce the issue to make a clear diagnosis. > > > > Thank you, > > Denis > > > > ------ > > la vida e estranya > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > ------ la vida e estranya From denis.spir at free.fr Thu Jan 15 12:48:00 2009 From: denis.spir at free.fr (spir) Date: Thu, 15 Jan 2009 12:48:00 +0100 Subject: [Tutor] single key ordered sequence Message-ID: <20090115124800.6637f730@o> Hello, a little algorithmic question. I have a list of tuples element, in which the first item is a kind of key. I need a target list with only one tuple per key. But the order must be kept -- so that I cannot use a temp dictionary. Additionally, in this case the chosen element for a repeted key is the last one occurring in source list. How would you do that? I used the following method that walks through the list with indexes in top-down order, and "marks" items to delete by "None-ing" them. But this a ugly trick imo, and I find the overall method to complicated for such a simple task. There shold be a clear one-liner for that, I guess. Also, how to practically walk in reverse order in a list without copying it (e.g. items[::-1]), especially if i need both indexes and items (couldn't find with enumerate()). items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'),(3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')] keys = [] for index in range(len(items)-1,-1,-1): key = items[index][0] if key in keys: items[index] = None else: keys.append(key) items = [item for item in items if item is not None] denis ------ la vida e estranya From richert at c-lab.de Thu Jan 15 12:02:28 2009 From: richert at c-lab.de (Willi Richert) Date: Thu, 15 Jan 2009 12:02:28 +0100 Subject: [Tutor] traceback In-Reply-To: <20090115115450.4fcab2c6@o> References: <20090114180951.6095bbb3@o> <200901142119.11994.w.richert@gmx.net> <20090115115450.4fcab2c6@o> Message-ID: <200901151202.28733.richert@c-lab.de> Hi, from http://effbot.org/pyref/sys.exc_info.htm: "The information returned is specific both to the current thread and to the current stack frame. If the current stack frame is not handling an exception, the information is taken from the calling stack frame, or its caller, and so on until a stack frame is found that is handling an exception." Maybe you are actually in two different threads? Take also a look at http://pbe.lightbird.net/traceback-module.html Regards, wr Am Donnerstag, 15. Januar 2009 11:54:50 schrieb spir: > Le Wed, 14 Jan 2009 21:19:11 +0100, > > Willi Richert a ?crit : > > Hi, > > > > do you observe the same behavior with traceback.format_exc()? I've used > > that always in such situations which worked all the time. > > > > Regards, > > wr > > Actually yes, for the traceback object returned by sys.exc_info() is None. > (sys.exc_info() --> (None,None,None)). Like if there was no exception > raised, or like if it had been clear()ed. But when I don't catch the > exception launched by a test program, I get the standard python error > message and the prog stops -- which proves that there *is* an active > exception. Simply, I cannot have it returned by sys.exc_info(). > I will try more today to understand why/when/how this happens. As I said, > in some circomstances all works well (sys.exc_info() returns a filled > (type,value,traceback) tuple) but as of now I cannot understand why. > > Denis > > > Am Mittwoch, 14. Januar 2009 18:09:51 schrieb spir: > > > Hello, > > > > > > I rather often use exceptions as information providers at design or > > > debug time. A typical use of mine is to have a test version of methods > > > that wrap standard version: > > > > > > def run(): > > > do stuff > > > that may > > > raise exc > > > def testRun(): > > > try: > > > run() > > > except Error,error: > > > sys.error.write(str(error)) > > > > > > So that I can run a bunch of (possibly failing) tests and still get all > > > worthful info. Now, the drawback is that I then lose python provided > > > traceback, as for any reason str(exc) does not return tracback, only > > > the "message". To have the traceback I planned to catch the traceback > > > manually. The aims whare: > > > * be able to output the tracback prepended to the message, when useful > > > * try to find a more readable (for me) format > > > * filter it: e.g. print only last trace mark of each module > > > If you have ideas on the best way to do this, thanks. > > > > > > I tried to use sys.exc_info() that returns a (type,value,traceback) > > > tuple and the format_tb() function of the traceback module. *Sometimes* > > > I get the traceback as expected and all is fine. But in most cases > > > sys.exc_info() returns (None,None,None) like if there was absolutely no > > > active exception. I cannot consistently reproduce the issue to make a > > > clear diagnosis. > > > > > > Thank you, > > > Denis > > > > > > ------ > > > la vida e estranya > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > ------ > la vida e estranya > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Dipl.-Inform. Willi Richert C-LAB - Cooperative Computing & Communication Laboratory der Universit?t Paderborn und Siemens FU.323 F?rstenallee 11 D-33102 Paderborn Tel: +49 5251 60 6120 Fax: +49 5251 60 6065 http://www.c-lab.de From alan.gauld at btinternet.com Thu Jan 15 13:00:39 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Jan 2009 12:00:39 -0000 Subject: [Tutor] tkinter canvas References: Message-ID: "Mr Gerard Kelly" wrote > All it does take a number (6 in this case) and draw that number of > blue > boxes on a canvas. > > I want to be able to bind these boxes to an event - so that I can > either > click on them, or hold the mouse cursor over them, and have them > change > color. I don;t think you can bind events to an object on a canvas, the events can only be bound to the canvas. So you would need to determine which object was being highlighted using the x,y coordinates of the event at the canvas level and then manipulate the shapes accordingly. This might be easier if you create a series of shape objects and hold a list of those. You can then iterate over the list to lovcate which object contains the point and that object can update itself. This also makes handling the case of overlapping objects easier. There might be a more Tkinter'ish way of doing this but I've not come across it. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Thu Jan 15 13:08:39 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Jan 2009 12:08:39 -0000 Subject: [Tutor] eval and floating point References: Message-ID: "Mr Gerard Kelly" wrote > I've noticed that the eval() function gives an integer, so > eval("3/2") > gives back 1. float(eval("3/2")) doesn't seem to work, any way to > get a > floating point number back with eval()? Move the float inside the eval: eval("float(3/2)") It's nothing to do with eval but with Python. eval just asks the interpreter to evaluate the string. Which is why you hardly ever need to use eval, you can usually work with the string in your own code and execute it that way. Alan G From alan.gauld at btinternet.com Thu Jan 15 13:04:50 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Jan 2009 12:04:50 -0000 Subject: [Tutor] Non-blocking non-interactive graphics display References: <4a289b480901142200k3e376eaeg39de1ed8de1e239c@mail.gmail.com> Message-ID: "David Williams" wrote > I am looking for the simplest way of displaying a little positional > data as a line graphic in a window as a script runs. I got a bit lost in the description which followed but a couple of things stood out: > My problem is that using tkinter, it looks to be a bit difficult to > get this to work since showing the window blocks the rest of the > script from running. That shouldn't happen if your code is event driven. You manipulate the data, update the screen then stop and wait for the next evernt (which could be a timer) > I am not terribly familiar with threads and keen > to avoid them if they are unnecessary. It doesn't sound like you need threads for this. > The display is non-interactive and so communication with it > can be one-way. You still want to use events but probabnly driven by timers > Bonus points if it is part of the Enthought Python Distribution and > pleasingly anti-aliased. Sorry, I've never come across Envision before. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Thu Jan 15 13:14:16 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Jan 2009 12:14:16 -0000 Subject: [Tutor] running & debugging in python interactive shell References: <496E86DB.20202@gmail.com> Message-ID: "Artie Ziff" wrote > running python scripts. Does anyone know of an article that > describes > best practices for running and debugging scripts inside the python > shell? Of course, I use import directive to run my script for first > run. > I am seeking techniques for invoking parts of script after initial > import. I hope this makes sense to those persons reading. :) Provided you have built the module as a set of functions/classes then after import you can just call those functions from the shell. You cannot invoke arbitrary lines of code (as you can in the Smalltalk workspace for example). Accessing functions etc is normal practice in the shell so I'm not sure what you are really asking here? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk From alan.gauld at btinternet.com Thu Jan 15 13:18:46 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Jan 2009 12:18:46 -0000 Subject: [Tutor] Creating simple windows in XP References: Message-ID: "Alex Krycek" wrote > I'd like to create very simple GUI's in XP. For the sake of > simplicity, I'm > trying to avoid downloading and installing anything (although I am > considering EasyGui). The basic GUI framework in Python is Tkinter and that works fine on XP. See my tutorial topic on GUI programming for a very simople intro before trying any of themore fully featured Tkinter tutorials... > To see how well it works, I've tried having my > program run a Visual Basic script ( i.e. > subprocess.call(someScript.vbs, > shell = True) ). It seemed to work ok. I was just wondering if > there was a > better and/or easier way of doing this. That does of course work but is not really you creating a GUI its just running another program. You could start Word or Excel just as easily! There are many other Python GUI frameworks, some have GUI builders somewhat like VB. But they are all downloadable add-ons. Tkinter is the only one that comes as sandard. Its primitive, but easy to learn and use for basic form style applications. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From andreengels at gmail.com Thu Jan 15 13:21:47 2009 From: andreengels at gmail.com (Andre Engels) Date: Thu, 15 Jan 2009 13:21:47 +0100 Subject: [Tutor] eval and floating point In-Reply-To: References: Message-ID: <6faf39c90901150421n6374587dl4b237dc3f9bf1803@mail.gmail.com> On Thu, Jan 15, 2009 at 1:08 PM, Alan Gauld wrote: > > "Mr Gerard Kelly" wrote > >> I've noticed that the eval() function gives an integer, so eval("3/2") >> gives back 1. float(eval("3/2")) doesn't seem to work, any way to get a >> floating point number back with eval()? > > Move the float inside the eval: > > eval("float(3/2)") That still does not work, because the 'float' comes after the division. 3/2 equals 1, so float(3/2) equals 1.0. To make it work, you'll have to put the float inside the division: eval("float(3)/2") or eval("3/float(2)") Which, as said before, is written less complicatedly as: eval("3.0/2") -- Andr? Engels, andreengels at gmail.com From kent37 at tds.net Thu Jan 15 13:24:29 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 15 Jan 2009 07:24:29 -0500 Subject: [Tutor] tkinter canvas In-Reply-To: References: Message-ID: <1c2a2c590901150424k4181b8fs94b79270d1f941c2@mail.gmail.com> On Thu, Jan 15, 2009 at 12:41 AM, Mr Gerard Kelly wrote: > I want to be able to bind these boxes to an event - so that I can either > click on them, or hold the mouse cursor over them, and have them change > color. Here is a version of your program that binds the Enter and Leave events to each box and changes the box color when the mouse is over it: ######################### from Tkinter import * master = Tk() numboxes=6 width=40*(numboxes+2) height=200 w = Canvas(master, width=width, height=height) w.pack() size=width/(numboxes+2) box=[0]*numboxes def enter(e, i): e.widget.itemconfigure(box[i], fill='red') def leave(e, i): e.widget.itemconfigure(box[i], fill='blue') for i in range(numboxes): box[i]=w.create_rectangle((1+i)*40, 40, (2+i)*40, height-40, fill="blue") w.tag_bind(box[i], '', lambda e, i=i: enter(e, i)) w.tag_bind(box[i], '', lambda e, i=i: leave(e, i)) mainloop() ####################### The 'i=i' in the lambda is needed due to the (surprising) way that variables are bound to closures; without it, every event would be bound to the same value of i. Some explanation here: http://code.activestate.com/recipes/502271/ Kent From kent37 at tds.net Thu Jan 15 13:32:05 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 15 Jan 2009 07:32:05 -0500 Subject: [Tutor] Non-blocking non-interactive graphics display In-Reply-To: <4a289b480901142200k3e376eaeg39de1ed8de1e239c@mail.gmail.com> References: <4a289b480901142200k3e376eaeg39de1ed8de1e239c@mail.gmail.com> Message-ID: <1c2a2c590901150432x57bb750m5653b9565201e9ef@mail.gmail.com> On Thu, Jan 15, 2009 at 1:00 AM, David Williams wrote: > I am looking for the simplest way of displaying a little positional > data as a line graphic in a window as a script runs. > > Something like: > > #Set up some points > pt1 = (0,0) > pt2 = (2,1) > pt3 = (3,2) > #Create a window that displays the points as two lines connected at pt2 > import somethingsomething #maybe something like import enthought.enable > window = somethingsomething.graph_points_as_line(pt1,pt2,pt3) > #Iterate > for i in range(0,100): > #Change the points slightly, this takes a bit of time > [pt1, pt2, pt3] = update_points_with_derived_values(pt1,pt2,pt3) > #Update the display > window.graph_points(pt1,pt2,pt3) > > My problem is that using tkinter, it looks to be a bit difficult to > get this to work since showing the window blocks the rest of the > script from running. A little more context might help. What is the rest of the script doing? Is it the update points that is being blocked? tkinter supports animation. Here is an example of animation in tkinter that might help: http://effbot.org/zone/tkinter-animation.htm Kent From kent37 at tds.net Thu Jan 15 13:33:47 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 15 Jan 2009 07:33:47 -0500 Subject: [Tutor] Creating simple windows in XP In-Reply-To: References: Message-ID: <1c2a2c590901150433t4f02b82fkab416c105669d97c@mail.gmail.com> On Thu, Jan 15, 2009 at 1:29 AM, Alex Krycek wrote: > Hello, > > I'd like to create very simple GUI's in XP. For the sake of simplicity, I'm > trying to avoid downloading and installing anything (although I am > considering EasyGui). To see how well it works, I've tried having my > program run a Visual Basic script ( i.e. subprocess.call(someScript.vbs, > shell = True) ). It seemed to work ok. I was just wondering if there was a > better and/or easier way of doing this. Tkinter is the only GUI framework that comes with Python. If EasyGUI meets your needs, why not use it? Kent From denis.spir at free.fr Thu Jan 15 14:19:22 2009 From: denis.spir at free.fr (spir) Date: Thu, 15 Jan 2009 14:19:22 +0100 Subject: [Tutor] traceback -- how it works? In-Reply-To: <200901142119.11994.w.richert@gmx.net> References: <20090114180951.6095bbb3@o> <200901142119.11994.w.richert@gmx.net> Message-ID: <20090115141922.17e0fdf4@o> Le Wed, 14 Jan 2009 21:19:11 +0100, Willi Richert a ?crit : > Hi, > > do you observe the same behavior with traceback.format_exc()? I've used that > always in such situations which worked all the time. > > Regards, > wr Hello again, Willi & all, I guess I got the point. I thought that tracebacks where generated when an exception occurs, and then the exception itself was in a way linked to the matching traceback. Actually I thought that because the trace path exists before the exception. But I was wrong. It seems instead that the exception is first generated and only a traceback object. Maybe python generates the traceback only when it needs to print out the exception report, a part of which beeing the traceback. As a consequence, when an exception is created, no traceback exists at all, so that it may not be possible to have custom exceptions know about their own tracbacks. I wanted for a trial to have an "Error" type print out traceback in a different form. With rather complicated tests using a project of mine, I got what seemed unpredictable results where sometimes only a traceback existed. But simply launching an Error gives this: raise Error("TEST") ==> Traceback (most recent call last): File "tools.py", line 324, in testError() File "tools.py", line 287, in testError raise Error("TEST") __main__.Error: TEST Now, if I catch the first exception by nesting it inside a try...except, I will get the traceback of the first exception inside the second one: try: print 1/0 except ZeroDivisionError,error: raise Error(str(error) + " -- CAUGHT") ==> Traceback (most recent call last): File "tools.py", line 324, in testError() File "tools.py", line 291, in testError raise Error(str(error) + " -- CAUGHT") __main__.Error: module 'tools.py'-- in testError(): line 00289: print 1/0 integer division or modulo by zero -- CAUGHT Another more complex test involving an exception generated from within en external module gives: ### module tools.py ### from throw_error import throw_error def raise_uncaught_error(): try: throw_error() except TypeError: raise Error("A set cannot hold a mutable item.") ### module throw_error.py ### from sets import Set def build_set(l): s = Set(l) def throw_error(): build_set([[1,2,3]]) ==> Traceback (most recent call last): File "tools.py", line 318, in testError() File "tools.py", line 310, in testError raise_uncaught_error() File "tools.py", line 294, in raise_uncaught_error raise Error("A set cannot hold a mutable item.") __main__.Error: module 'tools.py'-- in raise_uncaught_error(): line 00291: throw_error() module '/home/spir/prog/ospyp/throw_error.py'-- in throw_error(): line 00009: build_set([[1,2,3]]) module '/home/spir/prog/ospyp/throw_error.py'-- in build_set(): line 00006: s = Set(l) module '/usr/lib/python2.5/sets.py'-- in __init__(): line 00429: self._update(iterable) module '/usr/lib/python2.5/sets.py'-- in _update(): line 00374: data[element] = value A set cannot hold a mutable item. The python traceback is the one of the second exception (mine), while the traceback read and reformatted by my custom exception is the one of the original exception (lauched by the module sets). Which is rather interesting -- even if not what I intended to do. Now, I can catch my own exception to avoid stopping a test unit run, for instance, and only print out the exception message: def raise_caught_error(): try: raise_uncaught_error() except Error,error: print error ==> module 'tools.py'-- in raise_uncaught_error(): line 00291: throw_error() module '/home/spir/prog/ospyp/throw_error.py'-- in throw_error(): line 00009: build_set([[1,2,3]]) module '/home/spir/prog/ospyp/throw_error.py'-- in build_set(): line 00006: s = Set(l) module '/usr/lib/python2.5/sets.py'-- in __init__(): line 00429: self._update(iterable) module '/usr/lib/python2.5/sets.py'-- in _update(): line 00374: data[element] = value A set cannot hold a mutable item. thank you for your help, Denis > Am Mittwoch, 14. Januar 2009 18:09:51 schrieb spir: > > Hello, > > > > I rather often use exceptions as information providers at design or debug > > time. A typical use of mine is to have a test version of methods that wrap > > standard version: > > > > def run(): > > do stuff > > that may > > raise exc > > def testRun(): > > try: > > run() > > except Error,error: > > sys.error.write(str(error)) > > > > So that I can run a bunch of (possibly failing) tests and still get all > > worthful info. Now, the drawback is that I then lose python provided > > traceback, as for any reason str(exc) does not return tracback, only the > > "message". To have the traceback I planned to catch the traceback manually. > > The aims whare: > > * be able to output the tracback prepended to the message, when useful > > * try to find a more readable (for me) format > > * filter it: e.g. print only last trace mark of each module > > If you have ideas on the best way to do this, thanks. > > > > I tried to use sys.exc_info() that returns a (type,value,traceback) tuple > > and the format_tb() function of the traceback module. *Sometimes* I get the > > traceback as expected and all is fine. But in most cases sys.exc_info() > > returns (None,None,None) like if there was absolutely no active exception. > > I cannot consistently reproduce the issue to make a clear diagnosis. > > > > Thank you, > > Denis > > ------ la vida e estranya From kent37 at tds.net Thu Jan 15 16:24:13 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 15 Jan 2009 10:24:13 -0500 Subject: [Tutor] traceback In-Reply-To: <20090114180951.6095bbb3@o> References: <20090114180951.6095bbb3@o> Message-ID: <1c2a2c590901150724k5777eee9of35b041f1fdfb795@mail.gmail.com> On Wed, Jan 14, 2009 at 12:09 PM, spir wrote: > Hello, > > I rather often use exceptions as information providers at design or debug time. A typical use > of mine is to have a test version of methods that wrap standard version: > > def run(): > do stuff > that may > raise exc > def testRun(): > try: > run() > except Error,error: > sys.error.write(str(error)) > > So that I can run a bunch of (possibly failing) tests and still get all worthful info. You might be interested in the unittest module. It lets you create and run a series of tests, some of which may fail, while reporting errors in a useful way. My introduction is here: http://personalpages.tds.net/~kent37/kk/00014.html Kent From kent37 at tds.net Thu Jan 15 16:32:27 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 15 Jan 2009 10:32:27 -0500 Subject: [Tutor] single key ordered sequence In-Reply-To: <20090115124800.6637f730@o> References: <20090115124800.6637f730@o> Message-ID: <1c2a2c590901150732x38f6b681x6a26e0f8f0014385@mail.gmail.com> On Thu, Jan 15, 2009 at 6:48 AM, spir wrote: > I have a list of tuples element, in which the first item is a kind of key. I need a target list > with only one tuple per key. But the order must be kept -- so that I cannot use a temp dictionary. > Additionally, in this case the chosen element for a repeted key is the last one occurring in > source list. > > How would you do that? In [1]: items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'),(3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')] In [2]: seen = set() In [3]: newItems = [] In [5]: for item in reversed(items): ...: if item[0] not in seen: ...: seen.add(item[0]) ...: newItems.append(item) In [6]: newItems Out[6]: [(5, 'c'), (4, 'a'), (3, 'b'), (2, 'a'), (1, 'b')] In [7]: newItems.reverse() In [8]: newItems Out[8]: [(1, 'b'), (2, 'a'), (3, 'b'), (4, 'a'), (5, 'c')] Or, with a somewhat hacky list comp: In [9]: seen = set() In [10]: [ item for item in reversed(items) if item[0] not in seen and not seen.add(item[0]) ] > Also, how to practically walk in reverse order in a list without copying it (e.g. items[::-1]), > especially if i need both indexes and items (couldn't find with enumerate()). See use of reversed() above. You can combine it with enumerate(): In [13]: list(enumerate(reversed(items))) Out[13]: [(0, (5, 'c')), (1, (5, 'b')), (2, (5, 'a')), (3, (4, 'a')), (4, (3, 'b')), (5, (3, 'a')), (6, (2, 'a')), (7, (1, 'b')), (8, (1, 'a'))] In [16]: list(reversed(list(enumerate(items)))) Out[16]: [(8, (5, 'c')), (7, (5, 'b')), (6, (5, 'a')), (5, (4, 'a')), (4, (3, 'b')), (3, (3, 'a')), (2, (2, 'a')), (1, (1, 'b')), (0, (1, 'a'))] Kent From broek at cc.umanitoba.ca Thu Jan 15 17:27:19 2009 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Thu, 15 Jan 2009 11:27:19 -0500 Subject: [Tutor] help with getting python to run from command prompt onWindows XP In-Reply-To: References: <496E3AFC.7030909@gmail.com> Message-ID: <496F63E7.4020401@cc.umanitoba.ca> Alan Gauld said unto the world at 14/01/09 07:34 PM: > > "Brian van den Broek" wrote > >> icon for Idle launching as expected. When run from IDLE, `print >> sys.executable' yields `C:\\Python26\\pythonw.exe'. >> He reports that C:\Python26 contains both python.exe and pythonw.exe. >> >> I've had him add the text `;C:\Python26' (without quotes) to the end >> of his Path environment variable via the Control Panel|System >> Properties way of editing Environment variables. I've had him reboot >> afterwards. > > Get him to type > > SET > env.txt > > at the DOS prompt that should list all environment variables into env.txt > > Get him to email that file to you and check what it says about PATH. > >> After all of that, he reports that an attempt to run python from the >> command prompt produces a complaint that `` `python' is not recognized >> as an internal or external command, operable program or batch file.'' > > What happens if he types > > C:PROMPT> C:\Python26\python.exe > > In other words uses the full path? Hi all, Thanks to all respondents for the input. Apologies for the delay in reply; there's a bit of a lag as I'm communicating with my friend by email, too. With the full path, python loads as expected. I'm awaiting the results of SET > env.txt as per Alan's suggestion above. If that doesn't clear it up for me, I shall report back. Thanks again, Brian vdB From broek at cc.umanitoba.ca Thu Jan 15 17:48:30 2009 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Thu, 15 Jan 2009 11:48:30 -0500 Subject: [Tutor] help with getting python to run from command prompt onWindows XP In-Reply-To: <496F63E7.4020401@cc.umanitoba.ca> References: <496E3AFC.7030909@gmail.com> <496F63E7.4020401@cc.umanitoba.ca> Message-ID: <496F68DE.8090403@cc.umanitoba.ca> Brian van den Broek said unto the world at 15/01/09 11:27 AM: > Alan Gauld said unto the world at 14/01/09 07:34 PM: >> >> "Brian van den Broek" wrote > With the full path, python loads as expected. I'm awaiting the results of > SET > env.txt > as per Alan's suggestion above. Never fails. Shortly after posting, I got an answer back from the friend I'm trying to help. The (recognized by me as) relevant bits of output are: Path=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files\texlive\2008\bin\win32;C:\Python26 PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH There is no subsequent Path line that might be stomping on the line shown above. I'm surprised that it is `Path' rather than `PATH'. Does that matter? I'm pretty sure that my friend didn't change that, as once he got into the `Edit System Variable' dialog, he felt uncertain and sent me a screen shot before he effected any modifications; the screen shot shows `Path'. Last, the texlive entry is from an installation of latex that I guided him through right before we installed python. Invoking latex from the command line works as expected, so I conclude that the Path is not broken. > If that doesn't clear it up for me, I shall report back. Didn't and did. Thanks and best, Brian From kent37 at tds.net Thu Jan 15 18:33:26 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 15 Jan 2009 12:33:26 -0500 Subject: [Tutor] help with getting python to run from command prompt onWindows XP In-Reply-To: <496F68DE.8090403@cc.umanitoba.ca> References: <496E3AFC.7030909@gmail.com> <496F63E7.4020401@cc.umanitoba.ca> <496F68DE.8090403@cc.umanitoba.ca> Message-ID: <1c2a2c590901150933r5e3b69acsb3864460d990513c@mail.gmail.com> On Thu, Jan 15, 2009 at 11:48 AM, Brian van den Broek wrote: > The (recognized by me as) relevant bits of output are: > Path=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program > Files\texlive\2008\bin\win32;C:\Python26 > PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH > > There is no subsequent Path line that might be stomping on the line shown > above. > > I'm surprised that it is `Path' rather than `PATH'. Does that matter? I don't think so, my PC has 'Path' also. I'm stumped... Kent From digitalxero at gmail.com Thu Jan 15 18:35:03 2009 From: digitalxero at gmail.com (Dj Gilcrease) Date: Thu, 15 Jan 2009 10:35:03 -0700 Subject: [Tutor] help with getting python to run from command prompt onWindows XP In-Reply-To: <496F68DE.8090403@cc.umanitoba.ca> References: <496E3AFC.7030909@gmail.com> <496F63E7.4020401@cc.umanitoba.ca> <496F68DE.8090403@cc.umanitoba.ca> Message-ID: if he just needs to run python scripts you just need to type the script name (preferably from the directory it is in) eg: C:\Path\To\App>app_name.py and it will run Also if you have changed the enviromental variables, you need to close the command prompt and re-open it on windows since it does not propagate to existing instances Dj Gilcrease OpenRPG Developer ~~http://www.openrpg.com On Thu, Jan 15, 2009 at 9:48 AM, Brian van den Broek wrote: > Brian van den Broek said unto the world at 15/01/09 11:27 AM: >> >> Alan Gauld said unto the world at 14/01/09 07:34 PM: >>> >>> "Brian van den Broek" wrote > > prompt and replies including Alan's suggestion to get a text file dump of > environment variables.> > >> With the full path, python loads as expected. I'm awaiting the results of >> SET > env.txt >> as per Alan's suggestion above. > > Never fails. Shortly after posting, I got an answer back from the friend I'm > trying to help. > > The (recognized by me as) relevant bits of output are: > Path=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program > Files\texlive\2008\bin\win32;C:\Python26 > PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH > > There is no subsequent Path line that might be stomping on the line shown > above. > > I'm surprised that it is `Path' rather than `PATH'. Does that matter? I'm > pretty sure that my friend didn't change that, as once he got into the `Edit > System Variable' dialog, he felt uncertain and sent me a screen shot before > he effected any modifications; the screen shot shows `Path'. > > Last, the texlive entry is from an installation of latex that I guided him > through right before we installed python. Invoking latex from the command > line works as expected, so I conclude that the Path is not broken. > >> If that doesn't clear it up for me, I shall report back. > > Didn't and did. > > Thanks and best, > > Brian > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From orsenthil at gmail.com Thu Jan 15 18:38:45 2009 From: orsenthil at gmail.com (Senthil Kumaran) Date: Thu, 15 Jan 2009 23:08:45 +0530 Subject: [Tutor] Python3.0 and Tkinter on ubuntu 8.10 HOWTO Message-ID: <20090115173845.GA7200@goofy> On Wed, Jan 14, 2009 at 03:38:20PM -0500, Vern Ceder wrote: > Since there was some interest in the question of how to get a full > Python 3.0, including Tkinter and IDLE, compiled on Ubuntu Intrepid > 8.10, I've written up what I've done and posted it at > http://learnpython.wordpress.com/2009/01/14/installing-python-30-on-ubuntu/ > Good explaination! You can also make a note about make fullinstall, which will make Python 3.0 as the default And also mention about python binary being present as python2.5,python2.6 and python3.0 when more than one version is installed. Thanks, Senthil -- Senthil Kumaran O.R. http://uthcode.sarovar.org From marc.tompkins at gmail.com Thu Jan 15 18:54:29 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 15 Jan 2009 09:54:29 -0800 Subject: [Tutor] help with getting python to run from command prompt onWindows XP In-Reply-To: References: <496E3AFC.7030909@gmail.com> <496F63E7.4020401@cc.umanitoba.ca> <496F68DE.8090403@cc.umanitoba.ca> Message-ID: <40af687b0901150954l39647ac0x6f78965e2aebcc3d@mail.gmail.com> On Thu, Jan 15, 2009 at 9:35 AM, Dj Gilcrease wrote: > if he just needs to run python scripts you just need to type the > script name (preferably from the directory it is in) > > eg: C:\Path\To\App>app_name.py > > and it will run > By default, and on most people's machines, not true. You can double-click on a .py script from the GUI, and if your file associations are set correctly then Python (or PythonW) will be invoked - but from the command line, not so much. HOWEVER: if you add ";.PY;.PYW" to the end of your PATHEXT string, then this will work. (Just tried it out on my machine and wonder why I never did before.) Unfortunately, this still requires that Windows be able to find "python.exe" or "pythonw.exe" in the system path... so it's nifty, but doesn't solve the OP's problem. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From orsenthil at gmail.com Thu Jan 15 18:56:39 2009 From: orsenthil at gmail.com (Senthil Kumaran) Date: Thu, 15 Jan 2009 23:26:39 +0530 Subject: [Tutor] single key ordered sequence Message-ID: <20090115175639.GB7200@goofy> > Also, how to practically walk in reverse order in a list without > copying it (e.g. items[::-1]), > especially if i need both indexes and items (couldn't find with > enumerate()). > Are you looking for reversed()? The way you are doing it is probably OK. But it can be simplified thus: keys = [] target = [] for item in reversed(items): if not item[0] in keys: keys.append(item[0]) target.append(item) print target If this is not what you wanted,then I have misunderstood your requirement and just based it on your code. Thanks, Senthil From marc.tompkins at gmail.com Thu Jan 15 19:07:23 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 15 Jan 2009 10:07:23 -0800 Subject: [Tutor] help with getting python to run from command prompt onWindows XP In-Reply-To: <496F68DE.8090403@cc.umanitoba.ca> References: <496E3AFC.7030909@gmail.com> <496F63E7.4020401@cc.umanitoba.ca> <496F68DE.8090403@cc.umanitoba.ca> Message-ID: <40af687b0901151007jb8349d4u5bf4d1aa84ff5527@mail.gmail.com> On Thu, Jan 15, 2009 at 8:48 AM, Brian van den Broek wrote: > > The (recognized by me as) relevant bits of output are: > Path=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program > Files\texlive\2008\bin\win32;C:\Python26 > PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH > > There is no subsequent Path line that might be stomping on the line shown > above. > New thought: could this be some sort of long-filename/short-filename weirdness? What happens if you have your friend do the following: > C:\>dir /x py* > Volume in drive C has no label. > Volume Serial Number is E400-17CA > > Directory of C:\ > > 2008-09-22 10:24 PM Python26 > 0 File(s) 0 bytes > 1 Dir(s) 9,809,756,160 bytes free > See that long empty space between "" and "Python26"? That means that there's no fake short filename associated with "Python26", which is what we expect - "Python26" is less than eight characters and has no spaces. However, funky things can happen during installation, and I have seen cases where filenames that _look_ normal STILL get fake short filenames associated with them. If you see anything between "" and "Python26" on your friend's machine (it would probably look like PYTHON~1.0, or something similar), then try putting (whatever it is) into the Path instead... -- www.fsrtechnologies.com p.s. - Full disclosure - I actually still have Python 2.5.1, so my directory is actually "Python25". Shouldn't matter, but wanted to disclose that. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Jan 15 19:20:24 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Jan 2009 18:20:24 -0000 Subject: [Tutor] eval and floating point References: <6faf39c90901150421n6374587dl4b237dc3f9bf1803@mail.gmail.com> Message-ID: "Andre Engels" wrote >> eval("float(3/2)") > > That still does not work, because the 'float' comes after the > division. 3/2 equals 1, so float(3/2) equals 1.0. To make it work, > you'll have to put the float inside the division: > > eval("float(3)/2") Ahem! Quite. That was what I actually intended to post! But having seen the other posts suggesting using future I had a rethink. I don't think either float() or the "3.0" approach will help the OP because I suspect he is trying to eval a string stored in a variable. In that case the "import future" trick is probably the only solution that will work, short of parsing the string and doing the division without using eval... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From srilyk at gmail.com Thu Jan 15 19:20:45 2009 From: srilyk at gmail.com (W W) Date: Thu, 15 Jan 2009 12:20:45 -0600 Subject: [Tutor] running & debugging in python interactive shel In-Reply-To: References: <496E86DB.20202@gmail.com> Message-ID: <333efb450901151020i2f86dc6v2a7eb4f6da050711@mail.gmail.com> On Wed, Jan 14, 2009 at 8:18 PM, Che M wrote: > > I'd like to add to this question and expand it: can anyone point me to > a good resource on debugging *generally*? > The first result on "Debugger tutorial" on google sent me to this: http://www.cs.princeton.edu/~benjasik/gdb/gdbtut.html Though it's for a specific program, it seems to have some good general purpose advice. Personally, I've never had the need for a debugger (maybe because I'm not writing complicated enough programs) - a simple "print" statement (in the right spot) tends to take care of all of my debugging needs. -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From wescpy at gmail.com Thu Jan 15 19:28:27 2009 From: wescpy at gmail.com (wesley chun) Date: Thu, 15 Jan 2009 10:28:27 -0800 Subject: [Tutor] eval and floating point In-Reply-To: References: <6faf39c90901150421n6374587dl4b237dc3f9bf1803@mail.gmail.com> Message-ID: <78b3a9580901151028meff495arbc201db004b91d15@mail.gmail.com> >>> eval("float(3/2)") >> >> That still does not work, because the 'float' comes after the >> division. 3/2 equals 1, so float(3/2) equals 1.0. To make it work, >> you'll have to put the float inside the division: >> eval("float(3)/2") correct. as long as one of the operands is a float, the division will be (or rather, the division *won't* be integer), i.e., "3./2" or "3/2.". > the "import future" trick is probably the only solution that will work, > short of parsing the string and doing the division without using eval... in addition to the import of division from __future__, which adds one extra line of code to all your source files which need this functionality, you can also use -Qnew to launch the interpreter, which defaults to the 3.x true division semantics: \$ python -Qnew Python 2.4.5 (#1, May 9 2008, 12:23:22) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 3/2 1.5 hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From alan.gauld at btinternet.com Thu Jan 15 19:28:37 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Jan 2009 18:28:37 -0000 Subject: [Tutor] tkinter canvas References: <1c2a2c590901150424k4181b8fs94b79270d1f941c2@mail.gmail.com> Message-ID: "Kent Johnson" wrote > for i in range(numboxes): > box[i]=w.create_rectangle((1+i)*40, 40, (2+i)*40, height-40, > fill="blue") > w.tag_bind(box[i], '', lambda e, i=i: enter(e, i)) > w.tag_bind(box[i], '', lambda e, i=i: leave(e, i)) I'm wrong again. I've never noticed tag_bind() before. Although on investigation it is used by Grayson in his Tkinter book... I notice it can also be used in the Text widget to catch events on specific items of text or embedded images etc. Nice. Alan G From alan.gauld at btinternet.com Thu Jan 15 19:36:29 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Jan 2009 18:36:29 -0000 Subject: [Tutor] help with getting python to run from command prompt onWindows XP References: <496E3AFC.7030909@gmail.com> <496F63E7.4020401@cc.umanitoba.ca> <496F68DE.8090403@cc.umanitoba.ca> Message-ID: "Brian van den Broek" wrote > The (recognized by me as) relevant bits of output are: > Path=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program > Files\texlive\2008\bin\win32;C:\Python26 > PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH That looks OK. Puzzling! Scraping the barrel here but he is definitely using a command prompt to type the command? ie He is not using Start->Run? The latter has a different registry based, way of determining the path. Otherwise I'm baffled! Alan G From agent.krycek at gmail.com Thu Jan 15 19:47:32 2009 From: agent.krycek at gmail.com (Alex Krycek) Date: Thu, 15 Jan 2009 11:47:32 -0700 Subject: [Tutor] Creating simple windows in XP In-Reply-To: <1c2a2c590901150433t4f02b82fkab416c105669d97c@mail.gmail.com> References: <1c2a2c590901150433t4f02b82fkab416c105669d97c@mail.gmail.com> Message-ID: Thanks for the suggestions guys. I had looked at Tkinter before and liked that it comes w/ Python. It's just that it's so complex writing anything. EasyGui is pretty simple, but I relying on standard tools. I liked how in VB, for example, to open a dialog box you could write: MsgBox("Text", vbOKOnly, "Title"). I'll probably go with EasyGui. Thanks again. On Thu, Jan 15, 2009 at 5:33 AM, Kent Johnson wrote: > On Thu, Jan 15, 2009 at 1:29 AM, Alex Krycek > wrote: > > Hello, > > > > I'd like to create very simple GUI's in XP. For the sake of simplicity, > I'm > > trying to avoid downloading and installing anything (although I am > > considering EasyGui). To see how well it works, I've tried having my > > program run a Visual Basic script ( i.e. subprocess.call(someScript.vbs, > > shell = True) ). It seemed to work ok. I was just wondering if there was > a > > better and/or easier way of doing this. > > Tkinter is the only GUI framework that comes with Python. If EasyGUI > meets your needs, why not use it? > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jervisau at gmail.com Thu Jan 15 21:44:52 2009 From: jervisau at gmail.com (Jervis Whitley) Date: Fri, 16 Jan 2009 07:44:52 +1100 Subject: [Tutor] single key ordered sequence In-Reply-To: <20090115175639.GB7200@goofy> References: <20090115175639.GB7200@goofy> Message-ID: <8e63a5ce0901151244n5689fd4amd710888721aef287@mail.gmail.com> On Fri, Jan 16, 2009 at 4:56 AM, Senthil Kumaran wrote: > > Also, how to practically walk in reverse order in a list without > > copying it (e.g. items[::-1]), > > especially if i need both indexes and items (couldn't find with > > enumerate()). > > > Are you looking for reversed()? > The way you are doing it is probably OK. > But it can be simplified thus: > > keys = [] > target = [] > > for item in reversed(items): > if not item[0] in keys: > keys.append(item[0]) > target.append(item) > > print target > > If this is not what you wanted,then I have misunderstood your > requirement and just based it on your code. > > Thanks, > Senthil > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > how about this: items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'), (3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')] mydict = dict(items) items = [item for item in mydict.iteritems()] testing shows: C:\WINDOWS\system32\cmd.exe /c python test_time.py **ORIGINAL** s = """ items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'), (3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')] keys = [] for index in range(len(items)-1,-1,-1): key = items[index][0] if key in keys: items[index] = None else: keys.append(key) items = [item for item in items if item is not None] """ timeit.Timer(stmt=s).timit() 5.40928835422 **Test1** s = """ items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'), (3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')] keys = [] for item in reversed(items): key = item[0] if key in keys: items.remove(item) else: keys.append(key) #items = [item for item in items if item is not None] """ timeit.Timer(stmt=s).timit() 5.02896436267 **Test2** s= """ items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'), (3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')] keys = dict(items) items = [item for item in keys.iteritems()] """ timeit.Timer(stmt=s).timit() 3.38715506199 Hit any key to close this window... -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu Jan 15 23:15:12 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 15 Jan 2009 17:15:12 -0500 Subject: [Tutor] single key ordered sequence In-Reply-To: <8e63a5ce0901151244n5689fd4amd710888721aef287@mail.gmail.com> References: <20090115175639.GB7200@goofy> <8e63a5ce0901151244n5689fd4amd710888721aef287@mail.gmail.com> Message-ID: <1c2a2c590901151415l15b59885ud45b1d69df349f2d@mail.gmail.com> On Thu, Jan 15, 2009 at 3:44 PM, Jervis Whitley wrote: > how about this: > items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'), > (3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')] > mydict = dict(items) > items = [item for item in mydict.iteritems()] That only coincidentally preserves order; the order of items in a dictionary is, for practical purposes, unpredictable. BTW [item for item in mydict.iteritems()] can be written as just mydict.items(). Kent From denis.spir at free.fr Thu Jan 15 23:29:48 2009 From: denis.spir at free.fr (spir) Date: Thu, 15 Jan 2009 23:29:48 +0100 Subject: [Tutor] traceback again: __traceback__ arg for exceptions in py3.0 Message-ID: <20090115232948.67b3ebfd@o> I just discovered the following: PEP 3134: Exception objects now store their traceback as the __traceback__ attribute. This means that an exception object now contains all the information pertaining to an exception, and there are fewer reasons to use sys.exc_info() (though the latter is not removed). in http://docs.python.org/dev/3.0/whatsnew/3.0.html denis ------ la vida e estranya From kent37 at tds.net Thu Jan 15 23:33:41 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 15 Jan 2009 17:33:41 -0500 Subject: [Tutor] indented grammar parsing In-Reply-To: <20090111191153.16a0b805@o> References: <20090111191153.16a0b805@o> Message-ID: <1c2a2c590901151433w6936d236v79826d636048a850@mail.gmail.com> On Sun, Jan 11, 2009 at 1:11 PM, spir wrote: > Hello, > > this is a rather specific question about parsing an indented grammar. > I have a working implementation (presented below) that may be worth a critic review -- if you like > it. > > First issue is: is there a way to express an indented formatfing using a common grammar > language such as BNF (or regex)? If yes, how to do that? If not, what kind of formal grammar is > actually such a format? Is there any standard way to express it? > > I guess from this text that python parsers have a pre-parse phase that generate the so-called > INDENT and DEDENT tokens -- which are then used during actual parsing. It's pretty common for parsers to be implemented in two phases, lexical scanning and actual parsing. The lexical scanner recognizes patterns in the source file and outputs a sequence of tokens. The parser analyzes the tokens, not the actual source text. So for the Python lexical scanner to emit INDENT and DEDENT tokens doesn't seem that strange to me. Kent From ksarikhani at gmail.com Thu Jan 15 23:38:21 2009 From: ksarikhani at gmail.com (Kayvan Sarikhani) Date: Thu, 15 Jan 2009 17:38:21 -0500 Subject: [Tutor] Opsware Global Shell Scripting In-Reply-To: References: Message-ID: Hello...thanks to several individuals, I've been able to get a little farther in this Opsware global shell script: #!/usr/bin/python import os outfile = open('test.txt','w') for servername in os.listdir('/opsw/Server/@'): print '---', servername print >> outfile, '---', servername rosh = 'rosh -n %s -l \$LOGNAME \ date' % (servername) os.system(rosh) outfile.close() This does most of what I need, but I've run into two issues. 1) After it uses the rosh command to remotely access a managed system, it executes the "date" command...but I need to be able to direct the date output to the outfile. I imagine it's probably going to be similar to how it directs output of the servernames, but still not quite sure how this fits in the scheme of this command. 2) Some connection attempts to systems just hang...not really sure why (yet), but I'd like to be able to specify some kind of timeout so that it executes the rosh command, and if it doesn't connect in 10 seconds, breaks the connection, and moves on to the next server in the list. I've read that there is some kind of a built-in timeout function, but I'm quite stumped on this one. If anyone has any suggestions or pointers, I'd really appreciate it. Thanks very much! K -------------- next part -------------- An HTML attachment was scrubbed... URL: From jervisau at gmail.com Thu Jan 15 23:36:05 2009 From: jervisau at gmail.com (Jervis Whitley) Date: Fri, 16 Jan 2009 09:36:05 +1100 Subject: [Tutor] single key ordered sequence In-Reply-To: <1c2a2c590901151415l15b59885ud45b1d69df349f2d@mail.gmail.com> References: <20090115175639.GB7200@goofy> <8e63a5ce0901151244n5689fd4amd710888721aef287@mail.gmail.com> <1c2a2c590901151415l15b59885ud45b1d69df349f2d@mail.gmail.com> Message-ID: <8e63a5ce0901151436y1ed97353s4c8511de03b8a02a@mail.gmail.com> On Fri, Jan 16, 2009 at 9:15 AM, Kent Johnson wrote: > On Thu, Jan 15, 2009 at 3:44 PM, Jervis Whitley > wrote: > > how about this: > > items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'), > > (3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')] > > mydict = dict(items) > > items = [item for item in mydict.iteritems()] > > That only coincidentally preserves order; the order of items in a > dictionary is, for practical purposes, unpredictable. > > BTW [item for item in mydict.iteritems()] can be written as just > mydict.items(). > > Kent I realise that what you have said is true, however can you show me a case where > items = dict(items).items() will not preserve order? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From pine508 at hotmail.com Thu Jan 15 23:56:50 2009 From: pine508 at hotmail.com (Che M) Date: Thu, 15 Jan 2009 17:56:50 -0500 Subject: [Tutor] running & debugging in python interactive shel In-Reply-To: <333efb450901151020i2f86dc6v2a7eb4f6da050711@mail.gmail.com> References: <496E86DB.20202@gmail.com> <333efb450901151020i2f86dc6v2a7eb4f6da050711@mail.gmail.com> Message-ID: Date: Thu, 15 Jan 2009 12:20:45 -0600 From: srilyk at gmail.com To: pine508 at hotmail.com Subject: Re: [Tutor] running & debugging in python interactive shel CC: tutor at python.org On Wed, Jan 14, 2009 at 8:18 PM, Che M wrote: >> I'd like to add to this question and expand it: can anyone point me to >> a good resource on debugging *generally*? > The first result on "Debugger tutorial" on google sent me to this: > http://www.cs.princeton.edu/~benjasik/gdb/gdbtut.html > Though it's for a specific program, it seems to have some good general purpose advice. > Personally, I've never had the need for a debugger (maybe because I'm not writing complicated > enough programs) - a simple "print" statement (in the right spot) tends to take care of all of my > debugging needs. That page didn't strike me as very helpful for my case, but thanks anyway. I'll Google for it, too, but just wondered if any of the tutors here had any recommendations. I just checked Alan Gauld's tutorial and I see it doesn't have a debugger section (completely understandably, as this is sort of advanced). I also use print statements a fair bit. I've just heard that using a debugger is a very useful thing and I thought maybe someone would have some tips here or knew of a good Python-relevant tutorial about it. Thanks, Che -Wayne _________________________________________________________________ Windows Live?: Keep your life in sync. http://windowslive.com/explore?ocid=TXT_TAGLM_WL_t1_allup_explore_012009 From broek at cc.umanitoba.ca Fri Jan 16 00:05:53 2009 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Thu, 15 Jan 2009 18:05:53 -0500 Subject: [Tutor] help with getting python to run from command prompt onWindows XP In-Reply-To: <1c2a2c590901150933r5e3b69acsb3864460d990513c@mail.gmail.com> References: <496E3AFC.7030909@gmail.com> <496F63E7.4020401@cc.umanitoba.ca> <496F68DE.8090403@cc.umanitoba.ca> <1c2a2c590901150933r5e3b69acsb3864460d990513c@mail.gmail.com> Message-ID: <496FC151.3030005@cc.umanitoba.ca> Kent Johnson said unto the world at 15/01/09 12:33 PM: > On Thu, Jan 15, 2009 at 11:48 AM, Brian van den Broek > wrote: >> The (recognized by me as) relevant bits of output are: >> Path=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program >> Files\texlive\2008\bin\win32;C:\Python26 >> PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH >> >> There is no subsequent Path line that might be stomping on the line shown >> above. >> >> I'm surprised that it is `Path' rather than `PATH'. Does that matter? > > I don't think so, my PC has 'Path' also. I'm stumped... > > Kent Hi all, Thanks for the further replies. As consensus seems to be there's nothing obvious to explain the problem, it's either going to be that my (relatively unsophisticated about computers) friend and I had a miscommunication over email or there is something at play that I won't be able to discern remotely. I'll have him verify all steps again and then call `gremlins'. Thanks for the help, Brian vdB From bgailer at gmail.com Fri Jan 16 00:39:07 2009 From: bgailer at gmail.com (bob gailer) Date: Thu, 15 Jan 2009 18:39:07 -0500 Subject: [Tutor] single key ordered sequence In-Reply-To: <8e63a5ce0901151436y1ed97353s4c8511de03b8a02a@mail.gmail.com> References: <20090115175639.GB7200@goofy> <8e63a5ce0901151244n5689fd4amd710888721aef287@mail.gmail.com> <1c2a2c590901151415l15b59885ud45b1d69df349f2d@mail.gmail.com> <8e63a5ce0901151436y1ed97353s4c8511de03b8a02a@mail.gmail.com> Message-ID: <496FC91B.9040400@gmail.com> Jervis Whitley wrote: > > > On Fri, Jan 16, 2009 at 9:15 AM, Kent Johnson > wrote: > > On Thu, Jan 15, 2009 at 3:44 PM, Jervis Whitley > > wrote: > > how about this: > > items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'), > > (3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')] > > mydict = dict(items) > > items = [item for item in mydict.iteritems()] > > That only coincidentally preserves order; the order of items in a > dictionary is, for practical purposes, unpredictable. > > BTW [item for item in mydict.iteritems()] can be written as just > mydict.items(). > > Kent > > I realise that what you have said is true, however > can you show me a case where > > > items = dict(items).items() > > will not preserve order? Thanks. > On my computer: >>> dict((('z', 1), ('y', 2))).items() [('y', 2), ('z', 1)] -- Bob Gailer Chapel Hill NC 919-636-4239 From alan.gauld at btinternet.com Fri Jan 16 00:45:01 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Jan 2009 23:45:01 -0000 Subject: [Tutor] Creating simple windows in XP References: <1c2a2c590901150433t4f02b82fkab416c105669d97c@mail.gmail.com> Message-ID: "Alex Krycek" wrote > EasyGui is pretty simple, but I relying on standard tools. I liked > how in > VB, for example, to open a dialog box you could write: > > MsgBox("Text", vbOKOnly, "Title"). > You mean like doing import tkMessageBox tkMessageBox.showinfo("Window Text", "A short message") in Tkinter? :-) OR res = tkMessageBox.askokcancel("Which?", "Ready to stop?") print res At that level Tkinter is pretty easy too. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Fri Jan 16 00:50:56 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Jan 2009 23:50:56 -0000 Subject: [Tutor] running & debugging in python interactive shel References: <496E86DB.20202@gmail.com> <333efb450901151020i2f86dc6v2a7eb4f6da050711@mail.gmail.com> Message-ID: "Che M" wrote > tutors here had any recommendations. I just checked Alan Gauld's > tutorial and I see it doesn't have a debugger section (completely You need to get a copy of the paper book, it has a chapter on debugging, starting with print statements and going through to the Python debugger and finally the IDLE debugger - but that is only available in the book... Alan G From jervisau at gmail.com Fri Jan 16 00:52:52 2009 From: jervisau at gmail.com (Jervis Whitley) Date: Fri, 16 Jan 2009 10:52:52 +1100 Subject: [Tutor] single key ordered sequence In-Reply-To: <496FC91B.9040400@gmail.com> References: <20090115175639.GB7200@goofy> <8e63a5ce0901151244n5689fd4amd710888721aef287@mail.gmail.com> <1c2a2c590901151415l15b59885ud45b1d69df349f2d@mail.gmail.com> <8e63a5ce0901151436y1ed97353s4c8511de03b8a02a@mail.gmail.com> <496FC91B.9040400@gmail.com> Message-ID: <8e63a5ce0901151552ne20cb3djf6080c6a2c0aeb6@mail.gmail.com> On Fri, Jan 16, 2009 at 10:39 AM, bob gailer wrote: > Jervis Whitley wrote: > >> >> >> On Fri, Jan 16, 2009 at 9:15 AM, Kent Johnson > kent37 at tds.net>> wrote: >> >> On Thu, Jan 15, 2009 at 3:44 PM, Jervis Whitley >> > wrote: >> > how about this: >> > items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'), >> > (3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')] >> > mydict = dict(items) >> > items = [item for item in mydict.iteritems()] >> >> That only coincidentally preserves order; the order of items in a >> dictionary is, for practical purposes, unpredictable. >> >> BTW [item for item in mydict.iteritems()] can be written as just >> mydict.items(). >> >> Kent >> >> I realise that what you have said is true, however can you show me a case >> where >> > items = dict(items).items() >> >> will not preserve order? Thanks. >> >> > On my computer: > > >>> dict((('z', 1), ('y', 2))).items() > [('y', 2), ('z', 1)] > > -- > Bob Gailer > Chapel Hill NC > 919-636-4239 > Same on mine, thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Jan 16 00:53:00 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Jan 2009 23:53:00 -0000 Subject: [Tutor] help with getting python to run from command prompt onWindows XP References: <496E3AFC.7030909@gmail.com> <496F63E7.4020401@cc.umanitoba.ca><496F68DE.8090403@cc.umanitoba.ca><1c2a2c590901150933r5e3b69acsb3864460d990513c@mail.gmail.com> <496FC151.3030005@cc.umanitoba.ca> Message-ID: "Brian van den Broek" wrote > I'll have him verify all steps again and then call `gremlins'. One last thing to try is to get him to send a screen shot with the error message showing. That will prove that he is using the right type of console, typing the right command and reporting the right error! Beyond that I think we are beaten... Alan G From s4027340 at student.uq.edu.au Fri Jan 16 02:00:30 2009 From: s4027340 at student.uq.edu.au (Mr Gerard Kelly) Date: Fri, 16 Jan 2009 11:00:30 +1000 Subject: [Tutor] tkinter canvas Message-ID: <505129e3.29e35051@uq.edu.au> wow, that's excellent, thanks so much. I haven't got a clue how lambda functions work, but they seem pretty useful, so I'll try to figure them out. ----- Original Message ----- From: Kent Johnson Date: Thursday, January 15, 2009 10:24 pm Subject: Re: [Tutor] tkinter canvas > On Thu, Jan 15, 2009 at 12:41 AM, Mr Gerard Kelly > wrote: > > > I want to be able to bind these boxes to an event - so that I can > either> click on them, or hold the mouse cursor over them, and have > them change > > color. > > Here is a version of your program that binds the Enter and Leave > events to each box and changes the box color when the mouse is over > it: > > ######################### > > from Tkinter import * > > master = Tk() > > numboxes=6 > > width=40*(numboxes+2) > height=200 > w = Canvas(master, width=width, height=height) > w.pack() > > size=width/(numboxes+2) > > box=[0]*numboxes > > def enter(e, i): > e.widget.itemconfigure(box[i], fill='red') > > def leave(e, i): > e.widget.itemconfigure(box[i], fill='blue') > > for i in range(numboxes): > box[i]=w.create_rectangle((1+i)*40, 40, (2+i)*40, height-40, > fill="blue") w.tag_bind(box[i], '', lambda e, i=i: > enter(e, i)) > w.tag_bind(box[i], '', lambda e, i=i: leave(e, i)) > > mainloop() > > ####################### > > The 'i=i' in the lambda is needed due to the (surprising) way that > variables are bound to closures; without it, every event would be > bound to the same value of i. Some explanation here: > http://code.activestate.com/recipes/502271/ > > Kent > From jervisau at gmail.com Fri Jan 16 02:09:43 2009 From: jervisau at gmail.com (Jervis Whitley) Date: Fri, 16 Jan 2009 12:09:43 +1100 Subject: [Tutor] running & debugging in python interactive she In-Reply-To: References: <496E86DB.20202@gmail.com> <333efb450901151020i2f86dc6v2a7eb4f6da050711@mail.gmail.com> Message-ID: <8e63a5ce0901151709y36391e36gb02a1cb89b9ec835@mail.gmail.com> On Fri, Jan 16, 2009 at 9:56 AM, Che M wrote: > > > > >> I'd like to add to this question and expand it: can anyone point me to > >> a good resource on debugging *generally*? > > The first result on "Debugger tutorial" on google sent me to this: > > > http://www.cs.princeton.edu/~benjasik/gdb/gdbtut.html > > > Though it's for a specific program, it seems to have some good general > purpose advice. > > Personally, I've never had the need for a debugger (maybe because I'm not > writing complicated > > enough programs) - a simple "print" statement (in the right spot) tends > to take care of all of my > > debugging needs. > > That page didn't strike me as very helpful for my case, but thanks > anyway. I'll Google for it, too, but just wondered if any of the > tutors here had any recommendations. I just checked Alan Gauld's > tutorial and I see it doesn't have a debugger section (completely > understandably, as this is sort of advanced). > > I also use print statements a fair bit. I've just heard that using > a debugger is a very useful thing and I thought maybe someone would > have some tips here or knew of a good Python-relevant tutorial about it. > > Thanks, > Che > > > -Wayne > > I did a search for 'python pdb tutorial' and found this resource: http://www.ferg.org/papers/debugging_in_python.html pdb is the python debugger, this tutorial will give you more than enough to get started. Cheers, -------------- next part -------------- An HTML attachment was scrubbed... URL: From dorseye at gmail.com Fri Jan 16 02:57:09 2009 From: dorseye at gmail.com (Eric Dorsey) Date: Thu, 15 Jan 2009 18:57:09 -0700 Subject: [Tutor] 2 & 4 or more spaces per indentation level.. Message-ID: Dear Pythonistas: Working in IDLE on Windows Vista, I have one program that I set to have 2 character spacing (due to the levels of if's and while's going on -- later my brother called this a bit of a code smell, ie. logic shouldn't go that deep, it should be broken out into separate functions instead. Thoughts on that are welcome to, do any of you feel logic should only go so many layers deep?), and my editor defaults to 4 (Which I believe is the standard according to PEP 8) I copied some code from the 2 spacing program to another I'm writing currently which has the default 4, and it got things kind of screwy with spacing. I believe I've got it fixed now by manually tabbing/spacing, etc., but I was wondering, if this happened on a much bigger scale, or you were say, pasting code in from some example where they used a different spacing than you, is there a simple/good/smart way to get it all back to the 4 spacing default? Or if for example I wanted to convert my 2 spacing program to the conventional 4? - Eric -------------- next part -------------- An HTML attachment was scrubbed... URL: From ballerz4ishi at sbcglobal.net Fri Jan 16 04:41:04 2009 From: ballerz4ishi at sbcglobal.net (Ishan Puri) Date: Thu, 15 Jan 2009 19:41:04 -0800 (PST) Subject: [Tutor] Corpora Message-ID: <892765.78280.qm@web83301.mail.sp1.yahoo.com> Hi, I was wondering if anyone could tell me where I can get corpora containing IMs, or blogs or any internet communication? This is kind of urgent. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From orsenthil at gmail.com Fri Jan 16 04:41:06 2009 From: orsenthil at gmail.com (Senthil Kumaran) Date: Fri, 16 Jan 2009 09:11:06 +0530 Subject: [Tutor] 2 & 4 or more spaces per indentation level.. In-Reply-To: References: Message-ID: <20090116034106.GA9987@goofy> On Thu, Jan 15, 2009 at 06:57:09PM -0700, Eric Dorsey wrote: > Working in IDLE on Windows Vista, I have one program that I set to have > 2 character spacing (due to the levels of if's and while's going on -- > later my brother called this a bit of a code smell, ie. logic shouldn't > go that deep, it should be broken out into separate functions instead. Your brother is right. Logic should not go deep and moreover the screen width not enough even with 2 space indentation gives a not-so-good picture too. > Thoughts on that are welcome to, do any of you feel logic should only > go so many layers deep?), and my editor defaults to 4 (Which I believe > is the standard according to PEP 8) Thats the way to approach. Follow PEP8. > they used a different spacing than you, is there a simple/good/smart > way to get it all back to the 4 spacing default? Or if for example I Rule #0 is Never mix tabs and spaces. Rule #1 is use a standard spacing through out the code. And when copying from a certain space-setting indentation to another, the modular script will still work fine. You can use some global find/replace mechanism to do suit your setting. For eg. I remember doing :%s/\ \ /\ \ \ \ /g OR you can also run your code through pyindent or python code beautifier (Google for it, you might find one). But after using the beautifier under these situations, just rely on your eyes to do a quick check if the logic has not gone awry ( which rarely does, but still I would believe myself more than the tool). -- Senthil http://uthocode.sarovar.org From john at fouhy.net Fri Jan 16 04:56:33 2009 From: john at fouhy.net (John Fouhy) Date: Fri, 16 Jan 2009 16:56:33 +1300 Subject: [Tutor] Corpora In-Reply-To: <892765.78280.qm@web83301.mail.sp1.yahoo.com> References: <892765.78280.qm@web83301.mail.sp1.yahoo.com> Message-ID: <5e58f2e40901151956y352945c1u94242ab4c89838b9@mail.gmail.com> 2009/1/16 Ishan Puri : > Hi, > I was wondering if anyone could tell me where I can get corpora > containing IMs, or blogs or any internet communication? This is kind of > urgent. Have you tried the enron email dataset? http://www.cs.cmu.edu/~enron/ (google may turn up other links) -- John. From orsenthil at gmail.com Fri Jan 16 04:57:10 2009 From: orsenthil at gmail.com (Senthil Kumaran) Date: Fri, 16 Jan 2009 09:27:10 +0530 Subject: [Tutor] Corpora In-Reply-To: <892765.78280.qm@web83301.mail.sp1.yahoo.com> References: <892765.78280.qm@web83301.mail.sp1.yahoo.com> Message-ID: <7c42eba10901151957o42865912ld7823cbb479a5a59@mail.gmail.com> On Fri, Jan 16, 2009 at 9:11 AM, Ishan Puri wrote: > Hi, > I was wondering if anyone could tell me where I can get corpora > containing IMs, or blogs or any internet communication? This is kind of www.google.com And for IM's specifically, you can look at "Alice Bot" Project, the corpus will be in structured format and you might end up using python to parse it ( and your question becomes relevant to this list :) ) -- Senthil From alan.gauld at btinternet.com Fri Jan 16 10:05:09 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 16 Jan 2009 09:05:09 -0000 Subject: [Tutor] 2 & 4 or more spaces per indentation level.. References: Message-ID: "Eric Dorsey" wrote > Working in IDLE on Windows Vista, I have one program that I set to > have 2 > character spacing (due to the levels of if's and while's going on -- > later > my brother called this a bit of a code smell, ie. logic shouldn't go > that > deep, it should be broken out into separate functions instead. > Thoughts on > that are welcome to, do any of you feel logic should only go so many > layers > deep?), Deeply nested logic tends to be hard to debug and hard to terst thoroughly so yes, this is considered a bad smell. Refactoring the inner parts of a loop into a function is often a good way to deal with this but it may have a performamnce impact if its a critical bit of code so its not a cure all. Usually its possioble to reduce nesting by using a different logic flow (De Morgans rules often help here) or by using higher level structures like list comprehensions instead of loops. In fact functional programming techniques in general can help minimise nesting of code - this is one of the claimed advantages of functional languages, that they lead to less deeply nested programs... > I copied some code from the 2 spacing program to another I'm writing > currently which has the default 4, and it got things kind of screwy > with > spacing. This can happen if you don't have the code in functions. Its easy to copy a function but copying arbitrary lines out of a function is much more risky. > but I was wondering, if this happened on a much bigger scale, or you > were > say, pasting code in from some example where they used a different > spacing > than you, is there a simple/good/smart way to get it all back to the > 4 > spacing default? There are many tools around that can do this kind of thing - indent, tab nanny, untabify, format etc... Pick your own favourite. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From denis.spir at free.fr Fri Jan 16 12:54:28 2009 From: denis.spir at free.fr (spir) Date: Fri, 16 Jan 2009 12:54:28 +0100 Subject: [Tutor] 2 & 4 or more spaces per indentation level.. In-Reply-To: <20090116034106.GA9987@goofy> References: <20090116034106.GA9987@goofy> Message-ID: <20090116125428.45225420@o> Le Fri, 16 Jan 2009 09:11:06 +0530, Senthil Kumaran a ?crit : > > > they used a different spacing than you, is there a simple/good/smart > > way to get it all back to the 4 spacing default? Or if for example I > > Rule #0 is Never mix tabs and spaces. > Rule #1 is use a standard spacing through out the code. > > And when copying from a certain space-setting indentation to another, > the modular script will still work fine. You can use some global > find/replace mechanism to do suit your setting. > For eg. I remember doing :%s/\ \ /\ \ \ \ /g > The simplest method I guess is to first copy the code into a new file/doc/editor tab. Change there to your personal indent width using whatever tool your editor provides, or by global search/replace. Then only paste into your code. denis ------ la vida e estranya From vginer at gmail.com Fri Jan 16 13:51:03 2009 From: vginer at gmail.com (Vicent) Date: Fri, 16 Jan 2009 13:51:03 +0100 Subject: [Tutor] "Pointer" to a function? Storing a function as an object property? Passing arguments by value/by reference? Message-ID: <50ed08f40901160451h17222bbbhed6338213a41daf7@mail.gmail.com> I am posting this question to two Python forums: Tutor and Python(x,y). In the case of Tutor [1], I think it's the right place to ask questions for a newbie like me. In the case of Python(x,y) Discussion Group [2], I am posting also because I think I am addressing a specific group of Python users that probably previously dealed with the same problems I do now. Anyway, let me know if it's a good idea to keep on doing this in the future. This question is about how to define classes or objects (or data structures) I need to use, and how to do it in an efficient way. I want to define an object or data structure called "Problem". That "problem" has to contain, somehow, a property or element called "function" which, in fact, I would like it to be a function, or a "pointer" to a function. For example, if "prob" is a "Problem" object, I would like to be able to do something like this: # call the function in prob, and store the result in "x" : x = prob.function( arguments/variables required by the function ) Does it makes any sense? Which would it be the right (meaning efficient but still object-oriented-programming-compliant) way to do it? I mean, if I store "a whole function" within each "Problem" object (assuming it can be done in Python), each Problem object would be consuming lot of memory (wouldn't it?). Maybe it would be better just to store a kind of "pointer" to the function within the "problem" object, so the object would be "lighter". The function would be then defined outside the object, as usual. Can you give me some hint about this? By the way, I have another related question. In C you can pass arguments to a function by value or by reference. Is there any equivalence in Python to that approach? How is the usual way to pass function arguments in Python? I guess I'll discover many of this things by my own when "playing arround" with Python, but some orientation will be welcomed. [1] http://mail.python.org/mailman/listinfo/tutor [2] http://groups.google.es/group/pythonxy Thank you very much in advance. -- Vicent -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Fri Jan 16 14:05:15 2009 From: andreengels at gmail.com (Andre Engels) Date: Fri, 16 Jan 2009 14:05:15 +0100 Subject: [Tutor] "Pointer" to a function? Storing a function as an object property? Passing arguments by value/by reference? In-Reply-To: <50ed08f40901160451h17222bbbhed6338213a41daf7@mail.gmail.com> References: <50ed08f40901160451h17222bbbhed6338213a41daf7@mail.gmail.com> Message-ID: <6faf39c90901160505w10664117o582526c50b95fd2d@mail.gmail.com> On Fri, Jan 16, 2009 at 1:51 PM, Vicent wrote: > I am posting this question to two Python forums: Tutor and Python(x,y). > > In the case of Tutor [1], I think it's the right place to ask questions for > a newbie like me. > > In the case of Python(x,y) Discussion Group [2], I am posting also because I > think I am addressing a specific group of Python users that probably > previously dealed with the same problems I do now. Anyway, let me know if > it's a good idea to keep on doing this in the future. > > This question is about how to define classes or objects (or data structures) > I need to use, and how to do it in an efficient way. > > I want to define an object or data structure called "Problem". > > That "problem" has to contain, somehow, a property or element called > "function" which, in fact, I would like it to be a function, or a "pointer" > to a function. > > For example, if "prob" is a "Problem" object, I would like to be able to > do something like this: > > > # call the function in prob, and store the result in "x" : > > x = prob.function( arguments/variables required by the function ) > > > Does it makes any sense? Which would it be the right (meaning efficient but > still object-oriented-programming-compliant) way to do it? > > I mean, if I store "a whole function" within each "Problem" object (assuming > it can be done in Python), each Problem object would be consuming lot of > memory (wouldn't it?). Maybe it would be better just to store a kind of > "pointer" to the function within the "problem" object, so the object would > be "lighter". The function would be then defined outside the object, as > usual. > > Can you give me some hint about this? In fact, this can be done in Python very easily, see the following interactive session: >>> class test(object): pass >>> test1 = test() >>> test2 = test() >>> def double(x): return x+x >>> def square(x): return x*x >>> test1.f = double >>> test2.f = square >>> test1.f(5) 10 >>> test2.f(5) 25 >>> -- Andr? Engels, andreengels at gmail.com From kent37 at tds.net Fri Jan 16 14:57:38 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 16 Jan 2009 08:57:38 -0500 Subject: [Tutor] "Pointer" to a function? Storing a function as an object property? Passing arguments by value/by reference? In-Reply-To: <50ed08f40901160451h17222bbbhed6338213a41daf7@mail.gmail.com> References: <50ed08f40901160451h17222bbbhed6338213a41daf7@mail.gmail.com> Message-ID: <1c2a2c590901160557k1f02416ew35705dbe531295b9@mail.gmail.com> On Fri, Jan 16, 2009 at 7:51 AM, Vicent wrote: > I want to define an object or data structure called "Problem". > > That "problem" has to contain, somehow, a property or element called > "function" which, in fact, I would like it to be a function, or a "pointer" > to a function. > > For example, if "prob" is a "Problem" object, I would like to be able to > do something like this: > > > # call the function in prob, and store the result in "x" : > > x = prob.function( arguments/variables required by the function ) As Andr? showed, this is trivially easy in Python. To expand on his exampl...functions are "first-class objects" in Python. That means that a function is an object that can be used in the same way as other values, i.e. assigned to variables or attributes, passed as function parameters, etc. The introduction of this essay has a bit more about this: http://personalpages.tds.net/~kent37/kk/00001.html > Does it makes any sense? Sure. > I mean, if I store "a whole function" within each "Problem" object (assuming > it can be done in Python), each Problem object would be consuming lot of > memory (wouldn't it?). Maybe it would be better just to store a kind of > "pointer" to the function within the "problem" object, so the object would > be "lighter". The function would be then defined outside the object, as > usual. All Python values are references, so you are essentially storing a pointer to the function object within the problem. Python assignment does not copy. This is a fundamental concept of Python that often confuses newbies, it is worth taking some time to understand it correctly. My explanation is here: http://personalpages.tds.net/~kent37/kk/00012.html > By the way, I have another related question. In C you can pass arguments to > a function by value or by reference. Is there any equivalence in Python to > that approach? How is the usual way to pass function arguments in Python? This question is the source of endless heat and little light on comp.lang.python, for (IMO) two reasons: - the word 'reference' means two things in this context - 'pass by reference' as a way of parameter passing and 'reference' as a name for a pointer. - the (IMO) correct answer is 'neither'. Python passes object references by value. If you think of it as passing a pointer by value you will pretty much have the right idea. See the second link above for more. Kent From greg at thewhittiers.com Fri Jan 16 14:56:37 2009 From: greg at thewhittiers.com (greg whittier) Date: Fri, 16 Jan 2009 08:56:37 -0500 Subject: [Tutor] "Pointer" to a function? Storing a function as an object property? Passing arguments by value/by reference? In-Reply-To: <50ed08f40901160451h17222bbbhed6338213a41daf7@mail.gmail.com> References: <50ed08f40901160451h17222bbbhed6338213a41daf7@mail.gmail.com> Message-ID: On Fri, Jan 16, 2009 at 7:51 AM, Vicent wrote: > > That "problem" has to contain, somehow, a property or element called "function" which, in fact, I would like it to be a function, or a "pointer" to a function. In python, the name of a function is just a pointer to it. Try this >>> def foo(): print "Hi!" >>> class Problem: def __init__(self,fun): self.fun = fun >>> p1 = Problem(foo) >>> p2 = Problem(foo) >>> foo >>> p1.fun >>> p2.fun >>> p1.fun == p2.fun True >>> From vginer at gmail.com Fri Jan 16 16:28:34 2009 From: vginer at gmail.com (Vicent) Date: Fri, 16 Jan 2009 16:28:34 +0100 Subject: [Tutor] "Pointer" to a function? Storing a function as an object property? Passing arguments by value/by reference? In-Reply-To: References: <50ed08f40901160451h17222bbbhed6338213a41daf7@mail.gmail.com> Message-ID: <50ed08f40901160728x125e3927gf00203fd4332e4fd@mail.gmail.com> On Fri, Jan 16, 2009 at 14:56, greg whittier wrote: > > In python, the name of a function is just a pointer to it. Try this > > >>> def foo(): > print "Hi!" > > > >>> class Problem: > def __init__(self,fun): > self.fun = fun > > > >>> p1 = Problem(foo) > >>> p2 = Problem(foo) > >>> foo > > >>> p1.fun > > >>> p2.fun > > >>> p1.fun == p2.fun > True > >>> > Wow!!! I thought that the question was simple but I was afraid that the answer was going to be too complex. But I see that it actually works like I thought it should!!! It's extremely simple and intuitive, IMHO. Thank you to all for your precise and clear answers. I've learned a lot, and specially appreciate the links that Kent provided. I hope I can contribute to this forum in the future. -- Vicent -------------- next part -------------- An HTML attachment was scrubbed... URL: From david at abbottdavid.com Fri Jan 16 17:35:13 2009 From: david at abbottdavid.com (David) Date: Fri, 16 Jan 2009 11:35:13 -0500 Subject: [Tutor] Simple program with menu to view videos Message-ID: <4970B741.6010704@abbottdavid.com> Hi, I just received the dvd Python Fundamentals by Wesley J. Chun and it was packaged by the distributor for use on Window and Mac but I use Linux so I pulled the videos of of the dvd. There are 10 lessons with a total of 58 individual videos. Most lessons are 6-8 videos long. So I did as Alan has suggested and came up with a plan of attack. What my basic program does is plays the first video and then the next in that lesson and when finished them all goes back to the menu. I am asking for some tips on how I can make this program with less code and using some classes, if that is the best way to proceed. I have a lot of code that is just copied from one function to the next. I am new to python and enjoy these little projects because I can see them in action. Here is my starting point; http://dwabbott.com/code/index6.html thanks -david -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From sierra_mtnview at sbcglobal.net Fri Jan 16 17:40:26 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 16 Jan 2009 08:40:26 -0800 Subject: [Tutor] Translating FORTRAN (77?) to Python? Message-ID: <4970B87A.7000005@sbcglobal.net> An HTML attachment was scrubbed... URL: From denis.spir at free.fr Fri Jan 16 18:32:19 2009 From: denis.spir at free.fr (spir) Date: Fri, 16 Jan 2009 18:32:19 +0100 Subject: [Tutor] @property? Message-ID: <20090116183219.57329501@o> Hello, would someone point me to some clear doc about properties: purpose, use, underlying model... [Could not find myself, probably because the word "property itself has far too wide meaning.] Thank you. denis ------ la vida e estranya From cfuller084 at thinkingplanet.net Fri Jan 16 18:19:09 2009 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Fri, 16 Jan 2009 11:19:09 -0600 Subject: [Tutor] Translating FORTRAN (77?) to Python? In-Reply-To: <4970B87A.7000005@sbcglobal.net> References: <4970B87A.7000005@sbcglobal.net> Message-ID: <200901161119.09724.cfuller084@thinkingplanet.net> On Friday 16 January 2009 10:40, Wayne Watson wrote: > I may have a need down the line to convert a large number of lines of > FORTRAN code to Python. Is there a good translator available to do this? In > the past, I've found some for translating Pascal to C, and possibly others. There is a Fotran to C converter, and you might have some luck interfacing that with SWIG or just following the tutorials in the Python docs. http://www.netlib.org/f2c/ http://docs.python.org/extending/ Cheers From greg at thewhittiers.com Fri Jan 16 19:10:27 2009 From: greg at thewhittiers.com (greg whittier) Date: Fri, 16 Jan 2009 13:10:27 -0500 Subject: [Tutor] Translating FORTRAN (77?) to Python? In-Reply-To: <4970B87A.7000005@sbcglobal.net> References: <4970B87A.7000005@sbcglobal.net> Message-ID: There's an absolutely incredible project call f2py http://cens.ioc.ee/projects/f2py2e/ that I've used before. It doesn't translate the code, but wraps it (which is actually better) and lets you import your library as a module. It even generates docstrings so you can see how to call the functions. On Fri, Jan 16, 2009 at 11:40 AM, Wayne Watson wrote: > I may have a need down the line to convert a large number of lines of > FORTRAN code to Python. Is there a good translator available to do this? In > the past, I've found some for translating Pascal to C, and possibly others. > -- > > Wayne Watson (Watson Adventures, Prop., Nevada City, CA) > > (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time) > > "The creation of the world did not occur at the > beginning of time; it occurs every day." -- M. Proust > > Web Page: > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From srilyk at gmail.com Fri Jan 16 19:10:40 2009 From: srilyk at gmail.com (W W) Date: Fri, 16 Jan 2009 12:10:40 -0600 Subject: [Tutor] Creating simple windows in XP In-Reply-To: References: <1c2a2c590901150433t4f02b82fkab416c105669d97c@mail.gmail.com> Message-ID: <333efb450901161010k2931d493j673399d949d6d557@mail.gmail.com> On Thu, Jan 15, 2009 at 5:45 PM, Alan Gauld wrote: > You mean like doing > > import tkMessageBox > tkMessageBox.showinfo("Window Text", "A short message") > > in Tkinter? :-) > > OR > > res = tkMessageBox.askokcancel("Which?", "Ready to stop?") > print res > > At that level Tkinter is pretty easy too. After trying that and getting the mildly annoying root window to pop up I did a quick search and found how to hide that window. from Tkinter import Tk root = Tk() root.withdraw() tkMessageBox.showinfo("Window", "Root window is gone!") If you need it back, root.deiconfiy() will show the window again. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Fri Jan 16 19:13:21 2009 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 16 Jan 2009 10:13:21 -0800 Subject: [Tutor] @property? In-Reply-To: <20090116183219.57329501@o> References: <20090116183219.57329501@o> Message-ID: <20090116181321.GA65871@dragon.alchemy.com> On Fri, Jan 16, 2009 at 06:32:19PM +0100, spir wrote: > Hello, > > would someone point me to some clear doc about properties: purpose, use, underlying model... > [Could not find myself, probably because the word "property itself has far too wide meaning.] I'm a little confused here because of the "@" in the subject. Do you mean Python syntax using the "@" in front of a name like: @protected def spam(eggs): ... Those are called "decorators". Try searching for those, or we can help if that's what you're looking for. -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From denis.spir at free.fr Fri Jan 16 19:23:22 2009 From: denis.spir at free.fr (spir) Date: Fri, 16 Jan 2009 19:23:22 +0100 Subject: [Tutor] Simple program with menu to view videos In-Reply-To: <4970B741.6010704@abbottdavid.com> References: <4970B741.6010704@abbottdavid.com> Message-ID: <20090116192322.6df025ee@o> Le Fri, 16 Jan 2009 11:35:13 -0500, David a ?crit : > Hi, > I just received the dvd Python Fundamentals by Wesley J. Chun and it was > packaged by the distributor for use on Window and Mac but I use Linux so > I pulled the videos of of the dvd. There are 10 lessons with a total of > 58 individual videos. Most lessons are 6-8 videos long. So I did as Alan > has suggested and came up with a plan of attack. What my basic program > does is plays the first video and then the next in that lesson and when > finished them all goes back to the menu. I am asking for some tips on > how I can make this program with less code and using some classes, if > that is the best way to proceed. I have a lot of code that is just > copied from one function to the next. I am new to python and enjoy these > little projects because I can see them in action. Here is my starting point; > http://dwabbott.com/code/index6.html > thanks > -david Just had a look at your code. As you say: "a lot of code that is just copied from one function to the next". The only reason for that is your functions have no argument (parameter): def lesson3b(): player = "/usr/bin/mplayer" fname = "/home/david/Desktop/core_video/data/python_0302.flv" subprocess.call([player, fname]) lesson3c() From this instance of a specific lesson player function, you can simply define a generic one: def play_lesson(lesson_id): # does not belong here: player = "/usr/bin/mplayer" fname = lesson_file_name(lesson_id) # how to get the file name? subprocess.call([player, fname]) # does not belong here: lesson3c() Note that "player" is a constant, so that it does not belong to the function. At best, it may be an optional argument which could later be overriden (by e.g. a command line argument -- if ever you chage the player). Also, the lesson3c() call is part of an overall scheduling logic that should be controled from an external loop or menu -- this depends on how you intend to use the application. Finally, note that the lesson file names are pretty regular: There are built out a single prefix, a "series" number, then a lesson letter. Provided you do not change this logic, you can build the filenames easily. The prefix can be written as an optional arg, like the player. Also, I would distinguish "series" from "lesson" (this may be helpful at the schedular level). An alternative may be a lesson file lookup in a dictionary of (lesson_id:lesson_file_name) pairs, but there is no need for that here. So that the core lesson playing function may look like that: def play_lesson(series_id, lesson_id, player = "/usr/bin/mplayer", prefix="/home/david/Desktop/core_video/data/python_"): # convert lesson lowercass letter id to a ordinal: # (a,b,...z <--> 97,98,...122) lesson_id = ord(lesson_id) - 96 # I use below a string formatting expression # but the file name may be constructed "manually" fname = "%s%02d%02d" %(prefix, series_id, lesson_id) subprocess.call([player, fname]) Now, you need a master control function, from which the user can possibly choose which lesson to watch, that will accordingly call the lesson player func. As said, this mainly depends on how you expect it as a user. Note that the logic you first coded is a kind of "masked" recursivity: play1a play1b play1c .... playnx playny This would be implemented in the above version by an additional explicit recursive call: def play_lesson(series_id, lesson_id, player = "/usr/bin/mplayer", prefix="/home/david/Desktop/core_video/data/python_"): ....... subprocess.call([player, fname]) play_lesson(next_lesson(series_id, lesson_id)) (provided the next_lesson func exists) This is very probably *not* the user model of an adaptative lesson player tool ;-) For a question of taste or programming style, I would personly rather create a "lesson" type (class) that holds and handles all that stuff: identification, file_name, play(), next()... But it would probably be neither clearer, nore simpler. You could do it afterwards as an introduction to objects (the list will help you). Denis ------ la vida e estranya From wescpy at gmail.com Fri Jan 16 19:30:28 2009 From: wescpy at gmail.com (wesley chun) Date: Fri, 16 Jan 2009 10:30:28 -0800 Subject: [Tutor] "Pointer" to a function? Storing a function as an object property? Passing arguments by value/by reference? In-Reply-To: <1c2a2c590901160557k1f02416ew35705dbe531295b9@mail.gmail.com> References: <50ed08f40901160451h17222bbbhed6338213a41daf7@mail.gmail.com> <1c2a2c590901160557k1f02416ew35705dbe531295b9@mail.gmail.com> Message-ID: <78b3a9580901161030y53d0ef2apc95962f96b7d3623@mail.gmail.com> > All Python values are references, so you are essentially storing a > pointer to the function object within the problem. Python assignment > does not copy. This is a fundamental concept of Python that often > confuses newbies, it is worth taking some time to understand it > correctly. My explanation is here: > http://personalpages.tds.net/~kent37/kk/00012.html inside kent's post is an(other) article by fredrik lundh that may be difficult to see during reading so i want to post it so you don't miss it: http://effbot.org/zone/call-by-object.htm in my training courses, when people ask if Python is "call-by-reference" or "call-by-value," i tell them it's neither... *and* both, then proceed to show them what i mean. this topic is definitely a place where beginners trip up, and it is also where you begin your long road to maturity as a Python programmer. remember, Python places an strong emphasis on objects, and in this particular case, what happens depends on whether an object allows for modification (mutability). hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From kent37 at tds.net Fri Jan 16 19:31:48 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 16 Jan 2009 13:31:48 -0500 Subject: [Tutor] @property? In-Reply-To: <20090116183219.57329501@o> References: <20090116183219.57329501@o> Message-ID: <1c2a2c590901161031v75f4ae45webd54968dd0b48@mail.gmail.com> On Fri, Jan 16, 2009 at 12:32 PM, spir wrote: > Hello, > > would someone point me to some clear doc about properties: purpose, use, underlying model... Properties: http://personalpages.tds.net/~kent37/kk/00008.html Decorators (the @ syntax): http://personalpages.tds.net/~kent37/kk/00001.html Kent From sierra_mtnview at sbcglobal.net Fri Jan 16 20:02:59 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 16 Jan 2009 11:02:59 -0800 Subject: [Tutor] Translating FORTRAN (77?) to Python? In-Reply-To: References: <4970B87A.7000005@sbcglobal.net> Message-ID: <4970D9E3.2030709@sbcglobal.net> An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Fri Jan 16 20:19:58 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Fri, 16 Jan 2009 20:19:58 +0100 Subject: [Tutor] Translating FORTRAN (77?) to Python? In-Reply-To: <4970D9E3.2030709@sbcglobal.net> References: <4970B87A.7000005@sbcglobal.net> <4970D9E3.2030709@sbcglobal.net> Message-ID: On Fri, Jan 16, 2009 at 20:02, Wayne Watson wrote: > That is interesting. I'll pursue it. Thanks. Of course, at the moment, I > have no F77 compiler, so I can't even execute or use the code. Is there a > freebie F77 compiler out there? GCC supportd it http://gcc.gnu.org/. Greets Sander From jsmith at medplus.com Fri Jan 16 20:10:48 2009 From: jsmith at medplus.com (Smith, Jeff) Date: Fri, 16 Jan 2009 14:10:48 -0500 Subject: [Tutor] Translating FORTRAN (77?) to Python? In-Reply-To: <4970D9E3.2030709@sbcglobal.net> References: <4970B87A.7000005@sbcglobal.net> <4970D9E3.2030709@sbcglobal.net> Message-ID: There was an add-on to the GNU C compiler for FORTRAN77 at one time (g77). I don't know if it is still available to how well it works though. Jeff ________________________________ From: tutor-bounces+jsmith=medplus.com at python.org [mailto:tutor-bounces+jsmith=medplus.com at python.org] On Behalf Of Wayne Watson Sent: Friday, January 16, 2009 2:03 PM To: greg whittier Cc: tutor at python.org Subject: Re: [Tutor] Translating FORTRAN (77?) to Python? That is interesting. I'll pursue it. Thanks. Of course, at the moment, I have no F77 compiler, so I can't even execute or use the code. Is there a freebie F77 compiler out there? greg whittier wrote: There's an absolutely incredible project call f2py http://cens.ioc.ee/projects/f2py2e/ that I've used before. It doesn't translate the code, but wraps it (which is actually better) and lets you import your library as a module. It even generates docstrings so you can see how to call the functions. On Fri, Jan 16, 2009 at 11:40 AM, Wayne Watson wrote: I may have a need down the line to convert a large number of lines of FORTRAN code to Python. Is there a good translator available to do this? In the past, I've found some for translating Pascal to C, and possibly others. -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time) "The creation of the world did not occur at the beginning of time; it occurs every day." -- M. Proust Web Page: _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time) "The creation of the world did not occur at the beginning of time; it occurs every day." -- M. Proust Web Page: Confidentiality Notice: The information contained in this electronic transmission is confidential and may be legally privileged. It is intended only for the addressee(s) named above. If you are not an intended recipient, be aware that any disclosure, copying, distribution or use of the information contained in this transmission is prohibited and may be unlawful. If you have received this transmission in error, please notify us by telephone (513) 229-5500 or by email (postmaster at MedPlus.com). After replying, please erase it from your computer system. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Jan 16 19:29:09 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 16 Jan 2009 13:29:09 -0500 Subject: [Tutor] Simple program with menu to view videos In-Reply-To: <4970B741.6010704@abbottdavid.com> References: <4970B741.6010704@abbottdavid.com> Message-ID: <1c2a2c590901161029k698ecb79j502cc91c2324c36c@mail.gmail.com> On Fri, Jan 16, 2009 at 11:35 AM, David wrote: > I am asking for some tips on how I can make > this program with less code and using some classes, if that is the best way > to proceed. I have a lot of code that is just copied from one function to > the next. When you are copy/pasting code, think about how you can make a function that abstracts the copied bits. For example you could have this function: def play(filename): player = "/usr/bin/mplayer" fname = "/home/david/Desktop/core_video/data/" + filename subprocess.call([player, fname]) Then for example you would have def lesson10f(): play("python_1006.flv") menu() So that is a start. Now look at what you are doing with the individual sub-lessons. You really just want a way to play a series of lessons. This can be done with a loop: def lesson8(): files = ['python_0800a.flv', 'python_0801.flv', , 'python_0806.flv'] playall(files) def playall(files): for name in files: play(name) Since the lesson names follow a regular pattern you might even be able to generate the names automatically from the lesson number. Finally, put a loop in your menu function rather than having the lessons call back to the menu. Kent From sierra_mtnview at sbcglobal.net Fri Jan 16 21:06:45 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 16 Jan 2009 12:06:45 -0800 Subject: [Tutor] Translating FORTRAN (77?) to Python? In-Reply-To: References: <4970B87A.7000005@sbcglobal.net> <4970D9E3.2030709@sbcglobal.net> Message-ID: <4970E8D5.2070301@sbcglobal.net> An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Fri Jan 16 21:41:39 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Fri, 16 Jan 2009 21:41:39 +0100 Subject: [Tutor] Translating FORTRAN (77?) to Python? In-Reply-To: <4970E8D5.2070301@sbcglobal.net> References: <4970B87A.7000005@sbcglobal.net> <4970D9E3.2030709@sbcglobal.net> <4970E8D5.2070301@sbcglobal.net> Message-ID: On Fri, Jan 16, 2009 at 21:06, Wayne Watson wrote: > Anything under Win? Yes, minigw http://www.mingw.org/. Greets Sander From sierra_mtnview at sbcglobal.net Fri Jan 16 22:20:10 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 16 Jan 2009 13:20:10 -0800 Subject: [Tutor] Translating FORTRAN (77?) to Python? In-Reply-To: References: <4970B87A.7000005@sbcglobal.net> <4970D9E3.2030709@sbcglobal.net> <4970E8D5.2070301@sbcglobal.net> Message-ID: <4970FA0A.2030100@sbcglobal.net> An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Sat Jan 17 00:01:26 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Sat, 17 Jan 2009 00:01:26 +0100 Subject: [Tutor] Translating FORTRAN (77?) to Python? In-Reply-To: <4970FA0A.2030100@sbcglobal.net> References: <4970B87A.7000005@sbcglobal.net> <4970D9E3.2030709@sbcglobal.net> <4970E8D5.2070301@sbcglobal.net> <4970FA0A.2030100@sbcglobal.net> Message-ID: On Fri, Jan 16, 2009 at 22:20, Wayne Watson wrote: > Will that do me any good if I implement my application under Win Python? Your question was for a fotran compiler to compile the source code. The fotran program is your reference point to compare the results to. Greets Sander From jeremiah.jester at panasonic.aero Fri Jan 16 23:56:42 2009 From: jeremiah.jester at panasonic.aero (Jeremiah Jester) Date: Fri, 16 Jan 2009 14:56:42 -0800 Subject: [Tutor] curl and python Message-ID: <1232146602.10436.8.camel@M13425> I'm trying to get curl to traverse a remote http directory get all page names and do some processing on these file with python. For starters, i need to get the directory listing in an array from the domain. Any ideas on how to do this? Thanks, JJ Disclaimer: The information contained in this transmission, including any attachments, may contain confidential information of Panasonic Avionics Corporation. This transmission is intended only for the use of the addressee(s) listed above. Unauthorized review, dissemination or other use of the information contained in this transmission is strictly prohibited. If you have received this transmission in error or have reason to believe you are not authorized to receive it, please notify the sender by return email and promptly delete the transmission. From alan.gauld at btinternet.com Sat Jan 17 02:40:02 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 17 Jan 2009 01:40:02 -0000 Subject: [Tutor] [python(x, y)] "Pointer" to a function? Storing a function as an object property? Passing arguments by value/by reference? References: <50ed08f40901160451h17222bbbhed6338213a41daf7@mail.gmail.com> Message-ID: "Vicent" wrote > That "problem" has to contain, somehow, a property or element called > "function" which, in fact, I would like it to be a function, or a > "pointer" > to a function. I won't repeat what others have said about passing function objects into an object and storing them as attributes. However I will point out an even more fundamental approach to your problem and pick up on one of your comments... > # call the function in prob, and store the result in "x" : > > x = prob.function( arguments/variables required by the function ) This is normal syntax for accessing the methods of an object. Thus: class Problem: def function(self, args): # your function code here return result p = Problem() x = p.function() So if you know what function will be used for each problem then you can define it as part of the class definition as a normal method. Or you can pass a reference to a predefined function into the class constructor: class Problem: def __init__(self, aFunc): self.function = aFunc def f(): return 42 def g(): return 66 p1 = Problem(f) p2 = Problem(g) x = p1.function() # call f() y = p2.function() # call g() This is IMHO slightly more elegant than assigning the function to an attribute of the object after construction. The down side of this style is that these functions will not have any access to attributes inside your class via self, as methods would. > Does it makes any sense? Which would it be the right (meaning > efficient but > still object-oriented-programming-compliant) way to do it? Its all potentially object oriented, depending upon what you want to do. > I mean, if I store "a whole function" within each "Problem" object > (assuming > it can be done in Python), each Problem object would be consuming > lot of > memory (wouldn't it?). Methods are defined in classes (which are also objects in their own right in Python) and objects hold references to the class. So each instance only has a reference to the class which is used to access the predefined methods. The functions that you pass as parameters as just direct references to those function objects. > Maybe it would be better just to store a kind of > "pointer" to the function within the "problem" object, Thats what happens. > By the way, I have another related question. In C you can pass > arguments to > a function by value or by reference. Is there any equivalence in > Python to > that approach? How is the usual way to pass function arguments in > Python? Basically by reference but as Wes said there are some wrinkles whoch mean it can be less than intuitive for a beginner! -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sat Jan 17 02:46:30 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 17 Jan 2009 01:46:30 -0000 Subject: [Tutor] Translating FORTRAN (77?) to Python? References: <4970B87A.7000005@sbcglobal.net><4970D9E3.2030709@sbcglobal.net> Message-ID: "Smith, Jeff" wrote > There was an add-on to the GNU C compiler for FORTRAN77 at one time > (g77). I don't know if it is still available to how well it works > though. Caveat: Fortran is one of the few mainstream languages that I have never read or written so I have no personal experience. But... At work we had a Fortran project which used the g77 GNU compiler and the FORTRAN team seemed to think it was OK. They were porting code from a VAX to a Sun Unix box. I believe the GNU g77 translator is available for Windows too. Alan G. From pine508 at hotmail.com Sat Jan 17 06:20:34 2009 From: pine508 at hotmail.com (Che M) Date: Sat, 17 Jan 2009 00:20:34 -0500 Subject: [Tutor] referring to subfolders Message-ID: I have been using absolute paths in my programs, but want to get out of the habit as I try to run them on other computers. I was surprised to find that this type of reference didn't work: path = '/subfolder/myfile.py' But instead I did it this way and it works: import os.path self.currentdir = os.curdir self.mysubfolder = os.path.join(self.currentdir, "subfolder") path = self.mysubfolder + '/myfile.py' Is this really the only way to do it,and so I have to import os.path each time I have a case where I refer to a subdirectory? It seems like something quick/built-in like the first way should work, or maybe I am misunderstanding something? Thanks. _________________________________________________________________ Windows Live?: Keep your life in sync. http://windowslive.com/explore?ocid=TXT_TAGLM_WL_t1_allup_explore_012009 From steve at alchemy.com Sat Jan 17 06:26:52 2009 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 16 Jan 2009 21:26:52 -0800 Subject: [Tutor] referring to subfolders In-Reply-To: References: Message-ID: <49716C1C.6030503@alchemy.com> Che M wrote: > I have been using absolute paths in my programs, but > want to get out of the habit as I try to run them on > other computers. I was surprised to find that this > type of reference didn't work: > > path = '/subfolder/myfile.py' Pathnames are relative by default. So: 'myfile.py' would be the file myfile.py in the current directory. 'subfolder/myfile.py' would be myfile.py inside subfolder, which is below the current directory. It's the initial / character which makes it absolute, and start from the root directory. From pine508 at hotmail.com Sat Jan 17 06:36:01 2009 From: pine508 at hotmail.com (Che M) Date: Sat, 17 Jan 2009 00:36:01 -0500 Subject: [Tutor] referring to subfolders In-Reply-To: <49716C1C.6030503@alchemy.com> References: <49716C1C.6030503@alchemy.com> Message-ID: ---------------------------------------- > Date: Fri, 16 Jan 2009 21:26:52 -0800 > From: steve at alchemy.com > To: pine508 at hotmail.com > CC: tutor at python.org > Subject: Re: [Tutor] referring to subfolders > > Che M wrote: >> I have been using absolute paths in my programs, but >> want to get out of the habit as I try to run them on >> other computers. I was surprised to find that this >> type of reference didn't work: >> >> path = '/subfolder/myfile.py' > > Pathnames are relative by default. So: > 'myfile.py' > would be the file myfile.py in the current directory. > 'subfolder/myfile.py' > would be myfile.py inside subfolder, which is below the current directory. > > It's the initial / character which makes it absolute, and start from the > root directory. Thanks--much simpler! _________________________________________________________________ Windows Live?: Keep your life in sync. http://windowslive.com/howitworks?ocid=TXT_TAGLM_WL_t1_allup_howitworks_012009 From kent37 at tds.net Sat Jan 17 06:11:01 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 17 Jan 2009 00:11:01 -0500 Subject: [Tutor] curl and python In-Reply-To: <1232146602.10436.8.camel@M13425> References: <1232146602.10436.8.camel@M13425> Message-ID: <1c2a2c590901162111q55a248f4vccd0b4b34591cb4e@mail.gmail.com> On Fri, Jan 16, 2009 at 5:56 PM, Jeremiah Jester wrote: > I'm trying to get curl to traverse a remote http directory get all page > names and do some processing on these file with python. > > For starters, i need to get the directory listing in an array from the > domain. Any ideas on how to do this? urllib2 and BeautifulSoup: http://personalpages.tds.net/~kent37/kk/00010.html http://personalpages.tds.net/~kent37/kk/00009.html Kent From kent37 at tds.net Sat Jan 17 14:03:46 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 17 Jan 2009 08:03:46 -0500 Subject: [Tutor] referring to subfolders In-Reply-To: References: Message-ID: <1c2a2c590901170503r7446c70brce0d59cad9cae847@mail.gmail.com> On Sat, Jan 17, 2009 at 12:20 AM, Che M wrote: > import os.path > self.currentdir = os.curdir > self.mysubfolder = os.path.join(self.currentdir, "subfolder") > path = self.mysubfolder + '/myfile.py' > > Is this really the only way to do it,and so I have to import > os.path each time I have a case where I refer to a subdirectory? The advantage of os.path.join() (if you use it for all joins) is that it is portable, it will use the appropriate path separator for the platform it is running on. These days that is not such a big deal, perhaps, as Mac OSX, Windows and Linux all accept / as a path separator. Kent From bgailer at gmail.com Sat Jan 17 17:35:47 2009 From: bgailer at gmail.com (bob gailer) Date: Sat, 17 Jan 2009 11:35:47 -0500 Subject: [Tutor] Translating FORTRAN (77?) to Python? In-Reply-To: <4970B87A.7000005@sbcglobal.net> References: <4970B87A.7000005@sbcglobal.net> Message-ID: <497208E3.8040003@gmail.com> Wayne Watson wrote: > I may have a need down the line to convert a large number of lines of > FORTRAN code to Python. Is there a good translator available to do this? I guess from the responses and Google Search that no such translator exists. It is possible but not trivial to write one. I probably could do that but would need some motivation. From sierra_mtnview at sbcglobal.net Sat Jan 17 23:06:57 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 17 Jan 2009 14:06:57 -0800 Subject: [Tutor] Translating FORTRAN (77?) to Python? In-Reply-To: References: <4970B87A.7000005@sbcglobal.net> <4970D9E3.2030709@sbcglobal.net> <4970E8D5.2070301@sbcglobal.net> <4970FA0A.2030100@sbcglobal.net> Message-ID: <49725681.7080602@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Sun Jan 18 03:28:34 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 17 Jan 2009 18:28:34 -0800 Subject: [Tutor] Translating FORTRAN (77?) to Python? In-Reply-To: <497208E3.8040003@gmail.com> References: <4970B87A.7000005@sbcglobal.net> <497208E3.8040003@gmail.com> Message-ID: <497293D2.40801@sbcglobal.net> An HTML attachment was scrubbed... URL: From echolynx at gmail.com Sun Jan 18 04:04:38 2009 From: echolynx at gmail.com (Ian Egland) Date: Sat, 17 Jan 2009 22:04:38 -0500 Subject: [Tutor] Best Python3000 Tutorial for Beginner Message-ID: Hello all, I just joined this mailing list. I am a beginner to programming in general and would really appreciate a tutorial for Python3000 that at least covers the basics. I have tried reading the manual, but I think it was written for more experienced programmers wishing to switch to python rather than a beginner looking for where to start. Most of the other tutorials I have found were for earlier versions of Python, and because Python 3.0 was released on my birthday, I decided I was meant to learn that release. ;-) Anyway, any help would be appreciated. I will do my best to return the favor. -Ian -------------- next part -------------- An HTML attachment was scrubbed... URL: From orsenthil at gmail.com Sun Jan 18 04:14:40 2009 From: orsenthil at gmail.com (Senthil Kumaran) Date: Sun, 18 Jan 2009 08:44:40 +0530 Subject: [Tutor] Best Python3000 Tutorial for Beginner In-Reply-To: References: Message-ID: <7c42eba10901171914o6e85e360ka9b0b5d79fd22a77@mail.gmail.com> On Sun, Jan 18, 2009 at 8:34 AM, Ian Egland wrote: > Hello all, I just joined this mailing list. > > I am a beginner to programming in general and would really appreciate a > tutorial for Python3000 that at least covers the basics. I have tried Hello Ian, That is a nice reason to get started with a language. However, you have to remember that Python 3.0 is not a new language at all. It is just a backwards impatible release of the original almighty pyhon, which just tends to increase its strength and clean its design further. I am not at all surprised that you did not find any beginner Python 3.0 tutorial. It might be coming out soon, but the curretly people migrating to Python 3.0 are ones who already know python 2k well. So, for your purposes I would suggest the following. 1) Get Beginner Python tutorial. (See Alan's tutorial in this mailing list and also google for A Byte of Python) 2) Read and understand the language well. Get comfortable upto a point where you can differentiate between string, unicode and bytes. I should warn you that it might take months' time. and now you can read this very beginner friendly introduction to Python 3k. http://www.comp.leeds.ac.uk/nde/papers/teachpy3.html Thanks, Senthil From echolynx at gmail.com Sun Jan 18 04:21:34 2009 From: echolynx at gmail.com (Ian Egland) Date: Sat, 17 Jan 2009 22:21:34 -0500 Subject: [Tutor] Help with elif Message-ID: Wow, that was a quick response! Thanks all! I have looked at a couple tutorials and whipped this up. However, attempting to run it in IDLE results in a syntax error leaving my elif highlighted in red. What's wrong? I've looked at the code and can't find any syntax errors- though I've just started. print("[Temperature Converter, First Edition]") print("Created on January 17th, 2009 by Ian Egland") temp1 = int(input("Please enter a temperature: ")) scale = input("Convert to (F)ahrenheit or (C)elcius?") if scale == "F": temp2 = (9/5)*temp1+32 print(temp1, "C =", temp2, "F" elif scale == "C": # Error appears here. temp2 = (5/9)*(temp1-32) print(temp1, "F =", temp2, "C" else: print("Sorry, you must enter either an F or a C. Case-sensitive. Please try again." In regards to learning python, I've found that after I get somewhat-familiar with a language, I want a programming problem to solve with what I've learned. While learning Java, http://www.javabat.com has been my best friend. (That is, as close to a best friend as programming website can be.) Is there something like this for Java? Is one in the works? -Ian -------------- next part -------------- An HTML attachment was scrubbed... URL: From echolynx at gmail.com Sun Jan 18 04:22:58 2009 From: echolynx at gmail.com (Ian Egland) Date: Sat, 17 Jan 2009 22:22:58 -0500 Subject: [Tutor] Fixed Message-ID: Found it- wasn't closing the ()'s in the print()'s. Thanks anyway, sorry for filling your inbox. -Ian -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Sun Jan 18 04:44:25 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 17 Jan 2009 22:44:25 -0500 Subject: [Tutor] Help with elif In-Reply-To: References: Message-ID: <1c2a2c590901171944j31949717t943ce3656c8cfea7@mail.gmail.com> On Sat, Jan 17, 2009 at 10:21 PM, Ian Egland wrote: > I have looked at a couple tutorials and whipped this up. However, attempting > to run it in IDLE results in a syntax error leaving my elif highlighted in > red. What's wrong? I've looked at the code and can't find any syntax errors- > though I've just started. > > print("[Temperature Converter, First Edition]") > print("Created on January 17th, 2009 by Ian Egland") > temp1 = int(input("Please enter a temperature: ")) > scale = input("Convert to (F)ahrenheit or (C)elcius?") > if scale == "F": > temp2 = (9/5)*temp1+32 > print(temp1, "C =", temp2, "F" Missing parenthesis in the above line. > elif scale == "C": # Error appears here. Syntax errors often appear on the line *following* the line with the actual error. Kent From brian.mathis at gmail.com Sun Jan 18 06:24:05 2009 From: brian.mathis at gmail.com (Brian Mathis) Date: Sun, 18 Jan 2009 00:24:05 -0500 Subject: [Tutor] Best Python3000 Tutorial for Beginner In-Reply-To: References: Message-ID: <183c528b0901172124g16552494q1df8fa99bf91ca53@mail.gmail.com> In addition to what was already mentioned, I found "Think Python" useful. It is aimed at both learning programming in general, and it teaches in python specifically. However, it's written for python 2. http://www.greenteapress.com/thinkpython/thinkpython.html On Sat, Jan 17, 2009 at 10:04 PM, Ian Egland wrote: > Hello all, I just joined this mailing list. > > I am a beginner to programming in general and would really appreciate a > tutorial for Python3000 that at least covers the basics. I have tried > reading the manual, but I think it was written for more experienced > programmers wishing to switch to python rather than a beginner looking for > where to start. Most of the other tutorials I have found were for earlier > versions of Python, and because Python 3.0 was released on my birthday, I > decided I was meant to learn that release. ;-) > > Anyway, any help would be appreciated. I will do my best to return the > favor. > > -Ian > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From alan.gauld at btinternet.com Sun Jan 18 10:04:52 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 18 Jan 2009 09:04:52 -0000 Subject: [Tutor] Best Python3000 Tutorial for Beginner References: Message-ID: "Ian Egland" wrote > I am a beginner to programming in general and would really > appreciate a > tutorial for Python3000 that at least covers the basics..... > where to start. Most of the other tutorials I have found were for > earlier > versions of Python, and because Python 3.0 was released on my > birthday, I > decided I was meant to learn that release. ;-) I have finally managed to get a new site for my tutorial and am intending to upgrade it to Python 3 over the next few months. (I have to learn Python 3 myself as I'm doing it!!) >From previous experience it will take me about 1 week per topic so 6 months in total to upgrade the whole tutor. If you are interested in being a guinea pig for the topics I can let you have early visibility. But it will take me much longer to write than you will want to spend reading! HTH -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk From alan.gauld at btinternet.com Sun Jan 18 10:09:06 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 18 Jan 2009 09:09:06 -0000 Subject: [Tutor] Help with elif References: Message-ID: "Ian Egland" wrote > learned. While learning Java, http://www.javabat.com has been my > best > friend. (That is, as close to a best friend as programming website > can be.) > Is there something like this for Java? Is one in the works? If you already know Java, even a little bit then my tutorial will be too basic for you. I'd try the Byte of Python website/book. Although the official tutorial should be understandable too... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From jammy007_pp at yahoo.com Sun Jan 18 11:18:33 2009 From: jammy007_pp at yahoo.com (jammy007 pp) Date: Sun, 18 Jan 2009 02:18:33 -0800 (PST) Subject: [Tutor] Tutor Digest, Vol 59, Issue 90 In-Reply-To: Message-ID: <73001.44088.qm@web63301.mail.re1.yahoo.com> hi everyone? , i was trying to make a simple tic tac toe game using ascii characters . i read the source code from micheal dawson's book but didnt understand it much . if some one could? explain it to me with examples it would be great . thanks jammy -------------- next part -------------- An HTML attachment was scrubbed... URL: From vceder at canterburyschool.org Sun Jan 18 13:30:39 2009 From: vceder at canterburyschool.org (Vern Ceder) Date: Sun, 18 Jan 2009 07:30:39 -0500 Subject: [Tutor] Best Python3000 Tutorial for Beginner In-Reply-To: References: Message-ID: <497320EF.9030703@canterburyschool.org> Swaroop's Byte of Python has both 2.x and 3.x versions: http://www.swaroopch.com/notes/Python_en:Table_of_Contents Cheers, Vern Ceder Ian Egland wrote: > Hello all, I just joined this mailing list. > > I am a beginner to programming in general and would really appreciate a > tutorial for Python3000 that at least covers the basics. I have tried > reading the manual, but I think it was written for more experienced > programmers wishing to switch to python rather than a beginner looking > for where to start. Most of the other tutorials I have found were for > earlier versions of Python, and because Python 3.0 was released on my > birthday, I decided I was meant to learn that release. ;-) > > Anyway, any help would be appreciated. I will do my best to return the > favor. > > -Ian > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Sun Jan 18 13:56:57 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 18 Jan 2009 07:56:57 -0500 Subject: [Tutor] Help with elif In-Reply-To: References: Message-ID: <1c2a2c590901180456x2babb1d4i7c40a1c3ddb7b1c2@mail.gmail.com> On Sat, Jan 17, 2009 at 10:21 PM, Ian Egland wrote: > In regards to learning python, I've found that after I get somewhat-familiar > with a language, I want a programming problem to solve with what I've > learned. While learning Java, http://www.javabat.com has been my best > friend. (That is, as close to a best friend as programming website can be.) > Is there something like this for Java? Is one in the works? I don't know of anything quite like JavaBat. I think you will find that experimenting with Python is much easier than with Java. It is very simple to try out Python in the interactive interpreter, in IDLE or in an editor. Many programmers' editors can be configured to run Python programs directly from the editor. You might possibly like to try Crunchy, which puts an interactive session right into a tutorial in your web browser: http://showmedo.com/videos/video?name=1430020&fromSeriesID=143#TB_inline?&width=776&height=618&inlineId=videoPlayer Some puzzle and problem sites are listed here: http://personalpages.tds.net/~kent37/stories/00021.html#e21puzzles-and-problems Kent From kent37 at tds.net Sun Jan 18 14:08:20 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 18 Jan 2009 08:08:20 -0500 Subject: [Tutor] Tutor Digest, Vol 59, Issue 90 In-Reply-To: <73001.44088.qm@web63301.mail.re1.yahoo.com> References: <73001.44088.qm@web63301.mail.re1.yahoo.com> Message-ID: <1c2a2c590901180508w24f72b45vcc50b81c2d7e9a97@mail.gmail.com> On Sun, Jan 18, 2009 at 5:18 AM, jammy007 pp wrote: > hi everyone , > i was trying to make a simple tic tac toe game using ascii characters . > i read the source code from micheal dawson's book but didnt understand it > much . > > if some one could explain it to me with examples it would be great . Not everyone here has Dawson's book. A more specific question would help us help you. What is the first thing in the program that you don't understand? Kent From kent37 at tds.net Sun Jan 18 14:13:26 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 18 Jan 2009 08:13:26 -0500 Subject: [Tutor] Best Python3000 Tutorial for Beginner In-Reply-To: <497320EF.9030703@canterburyschool.org> References: <497320EF.9030703@canterburyschool.org> Message-ID: <1c2a2c590901180513n654657f5kcf724bf5b6cc6ad2@mail.gmail.com> On Sun, Jan 18, 2009 at 7:30 AM, Vern Ceder wrote: > > Swaroop's Byte of Python has both 2.x and 3.x versions: > > http://www.swaroopch.com/notes/Python_en:Table_of_Contents This page gives direct access to both versions: http://www.swaroopch.com/notes/Python Kent From alan.gauld at btinternet.com Sun Jan 18 15:40:24 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 18 Jan 2009 14:40:24 -0000 Subject: [Tutor] Help with elif References: Message-ID: "Alan Gauld" wrote > If you already know Java, even a little bit then my tutorial will be > too basic for you. > > I'd try the Byte of Python website/book. Actually I meant the dive into python website/book. Not that there's anything wrong with "Byte of" either, but "Dive In" seems more appropriate if you already program in Java... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From david at abbottdavid.com Sun Jan 18 16:37:50 2009 From: david at abbottdavid.com (David) Date: Sun, 18 Jan 2009 10:37:50 -0500 Subject: [Tutor] calculator will not multiply Message-ID: <49734CCE.3030808@abbottdavid.com> Everything else works + - / but not * why? thanks -david #!/usr/bin/python from __future__ import division import sys def add(x, y): return x + y def sub(x, y): return x - y def dev(x, y): return x / y def mul(x, y): return x * y def compute(arg1, arg2, arg3): if sys.argv[2] == "+": total = add(int(sys.argv[1]), int(sys.argv[3])) print total elif sys.argv[2] == "-": total = sub(int(sys.argv[1]), int(sys.argv[3])) print total elif sys.argv[2] == "/": total = dev(int(sys.argv[1]), int(sys.argv[3])) print total elif sys.argv[2] == "*": total = mul(int(sys.argv[1]), int(sys.argv[3])) print total else: print "oops" compute(sys.argv[1], sys.argv[2], sys.argv[3]) -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From andreengels at gmail.com Sun Jan 18 16:49:09 2009 From: andreengels at gmail.com (Andre Engels) Date: Sun, 18 Jan 2009 16:49:09 +0100 Subject: [Tutor] calculator will not multiply In-Reply-To: <49734CCE.3030808@abbottdavid.com> References: <49734CCE.3030808@abbottdavid.com> Message-ID: <6faf39c90901180749x5aa114ddh3968c669a5300911@mail.gmail.com> On Sun, Jan 18, 2009 at 4:37 PM, David wrote: > Everything else works + - / but not * > why? > thanks > -david It works for me. However, I do have another issue with your code: > def compute(arg1, arg2, arg3): > if sys.argv[2] == "+": > total = add(int(sys.argv[1]), int(sys.argv[3])) > print total > elif sys.argv[2] == "-": > total = sub(int(sys.argv[1]), int(sys.argv[3])) > print total > elif sys.argv[2] == "/": > total = dev(int(sys.argv[1]), int(sys.argv[3])) > print total > elif sys.argv[2] == "*": > total = mul(int(sys.argv[1]), int(sys.argv[3])) > print total > else: > print "oops" You define this as a function of arg1, arg2 and arg3, but inside the function you use the 'outer value' of sys.argv[1], sys.argv[2] and sys.argv[3]. It is very much advisable to use local rather than global variables inside functions. That way: * you can re-use the function elsewhere in the program, or even in a different program * you can develop the function and the main program semi-independently. For example, suppose you want to make this part of a larger program, and change the call "myprogram.py 2 + 3" to "myprogram.py calculate 2 + 3". In your case, you would have to change all the sys.argv inside the function. If instead you define the function as: def compute(arg1, arg2, arg3): if sys.arg2 == "+": total = add(int(sys.arg1), int(sys.arg3)) print total elif sys.arg2 == "-": total = sub(int(sys.arg1), int(sys.arg3)) print total elif sys.arg2 == "/": total = dev(int(sys.arg1), int(sys.arg3)) print total elif sys.arg2 == "*": total = mul(int(sys.arg1), int(sys.arg3)) print total else: print "oops" this can be implemented without changing the function at all, you just need to change compute(sys.argv[1], sys.argv[2], sys.argv[3]) to if sys.argv[1].equals("compute"): compute(sys.argv[2], sys.argv[3], sys.argv[4]) -- Andr? Engels, andreengels at gmail.com From andreengels at gmail.com Sun Jan 18 16:51:04 2009 From: andreengels at gmail.com (Andre Engels) Date: Sun, 18 Jan 2009 16:51:04 +0100 Subject: [Tutor] calculator will not multiply In-Reply-To: <6faf39c90901180749x5aa114ddh3968c669a5300911@mail.gmail.com> References: <49734CCE.3030808@abbottdavid.com> <6faf39c90901180749x5aa114ddh3968c669a5300911@mail.gmail.com> Message-ID: <6faf39c90901180751p3818f65k7a977077da24fc86@mail.gmail.com> There's an editing error in my previous message. The corrected function should not be: def compute(arg1, arg2, arg3): if sys.arg2 == "+": total = add(int(sys.arg1), int(sys.arg3)) print total elif sys.arg2 == "-": total = sub(int(sys.arg1), int(sys.arg3)) print total elif sys.arg2 == "/": total = dev(int(sys.arg1), int(sys.arg3)) print total elif sys.arg2 == "*": total = mul(int(sys.arg1), int(sys.arg3)) print total else: print "oops" but: def compute(arg1, arg2, arg3): if arg2 == "+": total = add(int(sys.arg1), int(sys.arg3)) print total elif arg2 == "-": total = sub(int(sys.arg1), int(sys.arg3)) print total elif arg2 == "/": total = dev(int(sys.arg1), int(sys.arg3)) print total elif arg2 == "*": total = mul(int(sys.arg1), int(sys.arg3)) print total else: print "oops" -- Andr? Engels, andreengels at gmail.com From jadrifter at gmail.com Sun Jan 18 16:55:30 2009 From: jadrifter at gmail.com (jadrifter) Date: Sun, 18 Jan 2009 07:55:30 -0800 Subject: [Tutor] calculator will not multiply In-Reply-To: <49734CCE.3030808@abbottdavid.com> References: <49734CCE.3030808@abbottdavid.com> Message-ID: <1232294130.6118.4.camel@ltop> On Sun, 2009-01-18 at 10:37 -0500, David wrote: > Everything else works + - / but not * > why? > thanks > -david > > > #!/usr/bin/python > from __future__ import division > import sys > > > def add(x, y): > return x + y > def sub(x, y): > return x - y > def dev(x, y): > return x / y > def mul(x, y): > return x * y > def compute(arg1, arg2, arg3): > if sys.argv[2] == "+": > total = add(int(sys.argv[1]), int(sys.argv[3])) > print total > elif sys.argv[2] == "-": > total = sub(int(sys.argv[1]), int(sys.argv[3])) > print total > elif sys.argv[2] == "/": > total = dev(int(sys.argv[1]), int(sys.argv[3])) > print total > elif sys.argv[2] == "*": > total = mul(int(sys.argv[1]), int(sys.argv[3])) > print total > else: > print "oops" > > compute(sys.argv[1], sys.argv[2], sys.argv[3]) > > It worked fine for me. Don't forget to put quotes around the * sign or the shell will substitute. so: ./calc.py 2 '*' 9 or: ./calc.py 2 "*" 9 or: ./calc.py 2 \* 9 but not: ./calc.py 2 * 9 John Purser From david at abbottdavid.com Sun Jan 18 17:10:50 2009 From: david at abbottdavid.com (David) Date: Sun, 18 Jan 2009 11:10:50 -0500 Subject: [Tutor] calculator will not multiply In-Reply-To: <1232294130.6118.4.camel@ltop> References: <49734CCE.3030808@abbottdavid.com> <1232294130.6118.4.camel@ltop> Message-ID: <4973548A.3090607@abbottdavid.com> jadrifter wrote: > It worked fine for me. Don't forget to put quotes around the * sign or > the shell will substitute. > > so: > ./calc.py 2 '*' 9 > or: > ./calc.py 2 "*" 9 > or: > ./calc.py 2 \* 9 > but not: > ./calc.py 2 * 9 > > John Purser > > > Thanks Kent and jadrifter, that explains that! Also thanks for the tips Angre :) -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From kent37 at tds.net Sun Jan 18 16:58:33 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 18 Jan 2009 10:58:33 -0500 Subject: [Tutor] calculator will not multiply In-Reply-To: <49734CCE.3030808@abbottdavid.com> References: <49734CCE.3030808@abbottdavid.com> Message-ID: <1c2a2c590901180758m212c3a31wfded74e9f3e30e64@mail.gmail.com> On Sun, Jan 18, 2009 at 10:37 AM, David wrote: > Everything else works + - / but not * > why? > compute(sys.argv[1], sys.argv[2], sys.argv[3]) Because * is a special character to your shell. Probably your shell is expanding the * to a list of files. Try printing sys.argv from within your program, or quoting the * on the command line. Kent From marc.tompkins at gmail.com Sun Jan 18 19:45:13 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sun, 18 Jan 2009 10:45:13 -0800 Subject: [Tutor] calculator will not multiply In-Reply-To: <49734CCE.3030808@abbottdavid.com> References: <49734CCE.3030808@abbottdavid.com> Message-ID: <40af687b0901181045h64e8d799qbe4529000b811854@mail.gmail.com> On Sun, Jan 18, 2009 at 7:37 AM, David wrote: > Everything else works + - / but not * > why? > thanks > -david > > > #!/usr/bin/python > from __future__ import division > import sys > > > def add(x, y): > return x + y > def sub(x, y): > return x - y > def dev(x, y): > return x / y > def mul(x, y): > return x * y > def compute(arg1, arg2, arg3): > if sys.argv[2] == "+": > total = add(int(sys.argv[1]), int(sys.argv[3])) > print total > elif sys.argv[2] == "-": > total = sub(int(sys.argv[1]), int(sys.argv[3])) > print total > elif sys.argv[2] == "/": > total = dev(int(sys.argv[1]), int(sys.argv[3])) > print total > elif sys.argv[2] == "*": > total = mul(int(sys.argv[1]), int(sys.argv[3])) > print total > else: > print "oops" > > compute(sys.argv[1], sys.argv[2], sys.argv[3]) > > It works for me under Windows XP, so I suspect that the hints you've received about * being expanded by your shell are correct. However, I had an idea - rather than requiring your user to put quotes around the "*", why not do this: elif sys.argv[2] in ["*","x","X"]: total = mul(int(sys.argv[1]), int(sys.argv[3])) print total This could be a problem if you wanted to develop your calculator into a full-fledged scientific calculator, but otherwise... -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From david at abbottdavid.com Sun Jan 18 22:26:27 2009 From: david at abbottdavid.com (David) Date: Sun, 18 Jan 2009 16:26:27 -0500 Subject: [Tutor] calculator will not multiply In-Reply-To: <40af687b0901181045h64e8d799qbe4529000b811854@mail.gmail.com> References: <49734CCE.3030808@abbottdavid.com> <40af687b0901181045h64e8d799qbe4529000b811854@mail.gmail.com> Message-ID: <49739E83.5050608@abbottdavid.com> Marc Tompkins wrote: > It works for me under Windows XP, so I suspect that the hints you've > received about * being expanded by your shell are correct. However, I > had an idea - rather than requiring your user to put quotes around the > "*", why not do this: > > elif sys.argv[2] in ["*","x","X"]: > total = mul(int(sys.argv[1]), int(sys.argv[3])) > print total Thank you :) > > This could be a problem if you wanted to develop your calculator into a > full-fledged scientific calculator, but otherwise... I may need just a little more practice, not because of a lack of effort, but there seems to be a small problem with retention :( > > > -- > www.fsrtechnologies.com 500 server error > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From echolynx at gmail.com Mon Jan 19 02:15:50 2009 From: echolynx at gmail.com (Ian Egland) Date: Sun, 18 Jan 2009 20:15:50 -0500 Subject: [Tutor] Convert String to Int Message-ID: 'Allo All. I know that, should you want to get an int from the user, you use int(input("Question!")). However, what if the user wasn't that savvy and didn't realize he/she HAD to enter a number? Program crash. Is there a way that I can get the input as a string, check and see if it's convertible to an integer, convert it if it is and ask them to try again if it's not? Thanks in advance. Ian -------------- next part -------------- An HTML attachment was scrubbed... URL: From sridhar.ratna at gmail.com Mon Jan 19 02:32:33 2009 From: sridhar.ratna at gmail.com (Sridhar Ratnakumar) Date: Sun, 18 Jan 2009 17:32:33 -0800 Subject: [Tutor] Convert String to Int In-Reply-To: References: Message-ID: <7c73a13a0901181732n4e143052wc5cb6ffbe791cfec@mail.gmail.com> On Sun, Jan 18, 2009 at 5:15 PM, Ian Egland wrote: > I know that, should you want to get an int from the user, you use > int(input("Question!")). However, what if the user wasn't that savvy and > didn't realize he/she HAD to enter a number? Program crash. Is there a way > that I can get the input as a string, check and see if it's convertible to > an integer, convert it if it is and ask them to try again if it's not? while True: try: a = int(raw_input()) break except ValueError: print "Try again" print 'You entered:', a From marc.tompkins at gmail.com Mon Jan 19 02:35:52 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sun, 18 Jan 2009 17:35:52 -0800 Subject: [Tutor] Convert String to Int In-Reply-To: References: Message-ID: <40af687b0901181735j58d1c1adq5c654efeed9b6ab1@mail.gmail.com> On Sun, Jan 18, 2009 at 5:15 PM, Ian Egland wrote: > I know that, should you want to get an int from the user, you use > int(input("Question!")). However, what if the user wasn't that savvy and > didn't realize he/she HAD to enter a number? Program crash. Is there a way > that I can get the input as a string, check and see if it's convertible to > an integer, convert it if it is and ask them to try again if it's not? > > You have two options: to test the input ahead of time, or to catch the crash. Believe it or not, number two is usually the preferred method (there's a programming axiom "It's better to ask forgiveness than permission") In Python, you put the operations that have a potential for disaster inside a try/except block, like so: try: > int(input("Question!")) > do whatever... > except: > ask again... > do the next thing > When Python "crashes", an Exception is generated, which carries all sorts of useful information about just what went wrong. It's good form to try to guess what the error might be before catching it (how many times have you been frustrated by some commercial program that says "Out of memory" {or some other catch-all} any time ANYTHING bad happens? It's because the programmer assumed that the only errors that would ever come up would be memory-related. Don't be that guy.) For example, do a test run like so: > >>> int('hello') > Traceback (most recent call last): > File "", line 1, in > ValueError: invalid literal for int() with base 10: 'hello' > Now you know that invalid input would result in a ValueError, so change my above code to: > try: > int(input("Question!")) > do whatever... > except ValueError: > ask again... > do the next thing > Someone else will no doubt already have posted how to test your input ahead of time - I thought I'd chime in with the other method... -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From echolynx at gmail.com Mon Jan 19 02:43:54 2009 From: echolynx at gmail.com (Ian Egland) Date: Sun, 18 Jan 2009 20:43:54 -0500 Subject: [Tutor] Convert String to Int In-Reply-To: <40af687b0901181735j58d1c1adq5c654efeed9b6ab1@mail.gmail.com> References: <40af687b0901181735j58d1c1adq5c654efeed9b6ab1@mail.gmail.com> Message-ID: Actually, nobody told me how to catch it before it occurs, though this "after error" stuff is new to me. Could you send an example of how to catch it beforehand? Just for the record? Thanks. Ian On Sun, Jan 18, 2009 at 8:35 PM, Marc Tompkins wrote: > On Sun, Jan 18, 2009 at 5:15 PM, Ian Egland wrote: > >> I know that, should you want to get an int from the user, you use >> int(input("Question!")). However, what if the user wasn't that savvy and >> didn't realize he/she HAD to enter a number? Program crash. Is there a way >> that I can get the input as a string, check and see if it's convertible to >> an integer, convert it if it is and ask them to try again if it's not? >> >> > You have two options: to test the input ahead of time, or to catch the > crash. Believe it or not, number two is usually the preferred method > (there's a programming axiom "It's better to ask forgiveness than > permission") In Python, you put the operations that have a potential for > disaster inside a try/except block, like so: > > try: >> int(input("Question!")) >> do whatever... >> except: >> ask again... >> do the next thing >> > > When Python "crashes", an Exception is generated, which carries all sorts > of useful information about just what went wrong. It's good form to try to > guess what the error might be before catching it (how many times have you > been frustrated by some commercial program that says "Out of memory" {or > some other catch-all} any time ANYTHING bad happens? It's because the > programmer assumed that the only errors that would ever come up would be > memory-related. Don't be that guy.) For example, do a test run like so: > >> >>> int('hello') >> Traceback (most recent call last): >> File "", line 1, in >> ValueError: invalid literal for int() with base 10: 'hello' >> > > Now you know that invalid input would result in a ValueError, so change my > above code to: > >> try: >> int(input("Question!")) >> do whatever... >> except ValueError: >> ask again... >> do the next thing >> > > Someone else will no doubt already have posted how to test your input ahead > of time - I thought I'd chime in with the other method... > > > -- > www.fsrtechnologies.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Mon Jan 19 03:59:04 2009 From: bgailer at gmail.com (bob gailer) Date: Sun, 18 Jan 2009 21:59:04 -0500 Subject: [Tutor] Convert String to Int In-Reply-To: References: Message-ID: <4973EC78.3080408@gmail.com> Ian Egland wrote: > 'Allo All. > > I know that, should you want to get an int from the user, you use > int(input("Question!")). However, what if the user wasn't that savvy > and didn't realize he/she HAD to enter a number? Program crash. Is > there a way that I can get the input as a string, check and see if > it's convertible to an integer, convert it if it is and ask them to > try again if it's not? a = raw_input("Enter an integer:") if a.isdigit(): # process input else: # complain -- Bob Gailer Chapel Hill NC 919-636-4239 From ajarncolin at gmail.com Mon Jan 19 07:28:44 2009 From: ajarncolin at gmail.com (col speed) Date: Mon, 19 Jan 2009 13:28:44 +0700 Subject: [Tutor] cube root Message-ID: <6a1b26420901182228v760bdaddweccbfed9b2495b12@mail.gmail.com> Hi there, just a quick one. Is there a way to obtain cube roots in python? I have been trying: math.pow(n,1.0/3) This works with some, but with 64, for example I get: >>> pow(64,1.0/3) 3.9999999999999996 However: >>> 4**3 64 Any ideas? Thanks Colin -------------- next part -------------- An HTML attachment was scrubbed... URL: From lupin at orcon.net.nz Mon Jan 19 07:41:34 2009 From: lupin at orcon.net.nz (Brett Wilkins) Date: Mon, 19 Jan 2009 19:41:34 +1300 Subject: [Tutor] cube root In-Reply-To: <6a1b26420901182228v760bdaddweccbfed9b2495b12@mail.gmail.com> References: <6a1b26420901182228v760bdaddweccbfed9b2495b12@mail.gmail.com> Message-ID: <4974209E.104@orcon.net.nz> Hey Colin, What you're running into here is the limited accuracy of floating point values... You'll likely find this happens a lot in python.. CPython, at least. (I know, as I do) I'm not sure, as I've never used it... but perhaps Numeric/Numpy handle this kinda stuff better (for accuracy's sake) Cheers, --Brett col speed wrote: > Hi there, just a quick one. > Is there a way to obtain cube roots in python? > I have been trying: > math.pow(n,1.0/3) > This works with some, but with 64, for example I get: > >>> pow(64,1.0/3) > 3.9999999999999996 > However: > >>> 4**3 > 64 > Any ideas? > Thanks > Colin > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From orsenthil at gmail.com Mon Jan 19 08:43:19 2009 From: orsenthil at gmail.com (Senthil Kumaran) Date: Mon, 19 Jan 2009 13:13:19 +0530 Subject: [Tutor] cube root In-Reply-To: <4974209E.104@orcon.net.nz> References: <6a1b26420901182228v760bdaddweccbfed9b2495b12@mail.gmail.com> <4974209E.104@orcon.net.nz> Message-ID: <7c42eba10901182343s3f7ac759tcc4c09a118f7f7aa@mail.gmail.com> On Mon, Jan 19, 2009 at 12:11 PM, Brett Wilkins wrote: > Hey Colin, > What you're running into here is the limited accuracy of floating point > values... Here the Python Documentation mentioning about the inherent limitations in dealing with floating point numbers: http://docs.python.org/tutorial/floatingpoint.html -- Senthil From denis.spir at free.fr Mon Jan 19 09:43:50 2009 From: denis.spir at free.fr (spir) Date: Mon, 19 Jan 2009 09:43:50 +0100 Subject: [Tutor] Convert String to Int In-Reply-To: <4973EC78.3080408@gmail.com> References: <4973EC78.3080408@gmail.com> Message-ID: <20090119094350.048af1b7@o> Le Sun, 18 Jan 2009 21:59:04 -0500, bob gailer a ?crit : > Ian Egland wrote: > > 'Allo All. > > > > I know that, should you want to get an int from the user, you use > > int(input("Question!")). However, what if the user wasn't that savvy > > and didn't realize he/she HAD to enter a number? Program crash. Is > > there a way that I can get the input as a string, check and see if > > it's convertible to an integer, convert it if it is and ask them to > > try again if it's not? > > a = raw_input("Enter an integer:") > if a.isdigit(): > # process input > else: > # complain > Actually, you probably run python 3.0, as you first wrote: int(input("Question!")) Before py3.0, input() would have processed & converted automatically the user input text (type string) into a number, if possible. So that int() would be useless. Try: >>> type(input()) 1 If you get this output, you have py<3.0 installed. But this behaviour was not the best (both for stability and security reasons) so that it was recommanded to use raw_input() instead, that keeps the input as raw string and lets the programmer process it carefully according to actual needs. With python 3, only raw_input() remains, but it has been renamed to "input()", so that only the correct feature is available. denis ------ la vida e estranya From alan.gauld at btinternet.com Mon Jan 19 10:00:13 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 19 Jan 2009 09:00:13 -0000 Subject: [Tutor] cube root References: <6a1b26420901182228v760bdaddweccbfed9b2495b12@mail.gmail.com> <4974209E.104@orcon.net.nz> Message-ID: "Brett Wilkins" wrote > What you're running into here is the limited accuracy of floating > point > values... You'll likely find this happens a lot in python.. CPython, > at least. In fact it happens with virtually every programming language available. The problem traces back to the way that computers represent floating point numbers in hardware. The integrated circuits cannot hold infinitely long numbers so they need to use a condensed representation and that inherently introduces small inaccuracies. (Think of 1/3 in decimal - an infinite series of 1.3333..., the same is true in binary, some numbers just cannot be represented accurately) In the specific case being discussed you can disguise the problem quite easily by displaying the result with a smaller number of decimal places using round() or string formatting: >>> 64**(1.0/3) 3.9999999999999996 >>> print 64**(1.0/3) 4.0 >>> round(64**(1.0/3)) 4.0 >>> "%5.3f" % 64**(1.0/3) '4.000' >>> When you need to compare floating point numbers you also need to be careful since: >>> 4.0 == 64**(1.0/3) ## is false! You need to introduce an error range, typically: >>> e = 0.00000001 >>> 4.0-e < 64**(1.0/3) < 4.0+e # is true You can also use the decimal module for exact decimal arithmetic but it introduces some other complications. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Mon Jan 19 10:05:49 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 19 Jan 2009 09:05:49 -0000 Subject: [Tutor] Convert String to Int References: Message-ID: "Ian Egland" wrote > I know that, should you want to get an int from the user, you use > int(input("Question!")). However, what if the user wasn't that savvy > and > didn't realize he/she HAD to enter a number? It's considered good UI design to phrase the prompt in such a way as to help the user know what to input: Thus: >>> x = int(input("Date(1-31): ")) or >>> s = int(input("Sex(m=1,f=2): ")) And then you have trhe responsibility to catch the error just in case... This is all part of "industrial standard" programming. You have to make your programs foolproof, while bearing in mind that nature keeps buiding bigger and better fools! -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Mon Jan 19 10:12:43 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 19 Jan 2009 09:12:43 -0000 Subject: [Tutor] Convert String to Int References: <40af687b0901181735j58d1c1adq5c654efeed9b6ab1@mail.gmail.com> Message-ID: "Ian Egland" wrote > Actually, nobody told me how to catch it before it occurs x = input('x = ') if type(x) == int: # check its an integer x = int(x) # ok, so convert to a number else: print ("Please enter a number") But that leads to much more complex and inefficient code so we prefer try: x = int(input(...)) except: print ('Please enter a number') PS. Assuming you are using Python v3. If you are using an earlier version its better(safer) to use raw_input() rather than input() which is potentially dangerous. In v3 old style input has been removed and raw_input replaced with a new safe input() HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Mon Jan 19 10:14:39 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 19 Jan 2009 09:14:39 -0000 Subject: [Tutor] Convert String to Int References: <4973EC78.3080408@gmail.com> Message-ID: "bob gailer" wrote > a = raw_input("Enter an integer:") > if a.isdigit(): > # process input Oops, yes. My posting on this is wrong because you can't compare to int untl after you convert the value. isdigit() is the correct check. Apologies - too early in the morning... Alan G From jammy007_pp at yahoo.com Mon Jan 19 10:18:41 2009 From: jammy007_pp at yahoo.com (jammy007 pp) Date: Mon, 19 Jan 2009 01:18:41 -0800 (PST) Subject: [Tutor] help on making python tictactoe Message-ID: <502624.34781.qm@web63305.mail.re1.yahoo.com> guys , i need immediate help on creating a simple tictactoe game . i read micheal dawson's book but didnt quiet get it . please help . thanks . jammy -------------- next part -------------- An HTML attachment was scrubbed... URL: From vginer at gmail.com Mon Jan 19 11:28:54 2009 From: vginer at gmail.com (Vicent) Date: Mon, 19 Jan 2009 11:28:54 +0100 Subject: [Tutor] cube root In-Reply-To: <4974209E.104@orcon.net.nz> References: <6a1b26420901182228v760bdaddweccbfed9b2495b12@mail.gmail.com> <4974209E.104@orcon.net.nz> Message-ID: <50ed08f40901190228h1a2858c1g1061068d16515560@mail.gmail.com> On Mon, Jan 19, 2009 at 07:41, Brett Wilkins wrote: > > What you're running into here is the limited accuracy of floating point > values... > You'll likely find this happens a lot in python.. CPython, at least. (I > know, as I do) > I'm not sure, as I've never used it... but perhaps Numeric/Numpy handle > this kinda stuff better (for accuracy's sake) > > Maybe this issue can be overcome by using symbolic notation when possible (maybe by using SymPy)? Has anyone any experience with this? -- Vicent -------------- next part -------------- An HTML attachment was scrubbed... URL: From ptmcg at austin.rr.com Mon Jan 19 11:29:03 2009 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 19 Jan 2009 04:29:03 -0600 Subject: [Tutor] cube root In-Reply-To: References: Message-ID: Wow! Everybody jumped on the "floating point inaccuracy" topic, I'm surprised no one tried to find out what the OP was trying to do with his cube root solver in the first place. Of course, the first-cut approach to solving the cube root is to raise to the 1/3 power, but this is not the only possible approach. Assuming that the OP wanted to try to find cube roots for integers, or raise an exception if the given number is not a perfect cube, I came up with this: def cube_root(n): "A modified Newton's Method solver for integral cube roots." if int(n) != n: raise ValueError("must provide an integer") if n in (-1,0,1): return n offset = (1,-1)[n > 0] x = n/2 seen = set() steps = 0 while 1: y = x**3 if y == n: #~ print "Found %d ^ 1/3 = %d in %d steps" % (n,x,steps) return x dydx = 3.0*x*x x += int((n-y)/dydx)+offset x = x or 1 if x in seen: raise ValueError("%d is not a perfect cube" % n) seen.add(x) steps += 1 This will correctly give 4 for 64, 5 for 125, etc., not 3.99999999999. Then I went googling for "python cube root", and found this curious solution: def root3rd(x): y, y1 = None, 2 while y!=y1: y = y1 y3 = y**3 d = (2*y3+x) y1 = (y*(y3+2*x)+d//2)//d return y This only works for perfect cubes, but could be made more robust with this test just before returning y: if y*y*y != x: raise ValueError("%d is not a perfect cube" % x) I was intrigued at this solution - timing it versus mine showed it to be 5x faster. I tried to see some sort of Newton's method implementation, but instead its more of a binary search. This was confirmed by adding this line inside the while loop: print y,y1 And to solve for the cube root of 1860867 (123**3), I get this output: None 2 2 4 4 8 8 16 16 32 32 62 62 105 105 123 with the value 123 returned as the answer. Note that the guess (variable y1) is initially doubled and redoubled, until the solution is neared. I tried initializing y1 to a different guess, the original number, and got this: None 1860867 1860867 930434 930434 465217 465217 232609 232609 116305 116305 58153 58153 29077 29077 14539 14539 7270 7270 3635 3635 1818 1818 909 909 456 456 235 235 141 141 123 Now the guess is halved each time until nearing the solution, then again converging to the solution 123. This algorithm is also robust in that it can do more than just cube roots. By changing this line: y3 = y**3 to: y3 = y**4 We get a 4th root solver! Unfortunately, this breaks down at the 5th root, as I found solutions would not converge. At this point, I lost interest in the general applicability of this algorithm, but it is still an interesting approach - does anyone know the theoretical basis for it? I guess I was just disappointed that taking cube roots of so small a number as 64 quickly got us into floating-point roundoff errors, and if the OP is doing something like looking for perfect cubes, then there are alternatives to the one-size-fits-almost-all logarithmic implementation of the '**' operator. -- Paul From lupin at orcon.net.nz Mon Jan 19 12:11:22 2009 From: lupin at orcon.net.nz (Brett Wilkins) Date: Tue, 20 Jan 2009 00:11:22 +1300 (NZDT) Subject: [Tutor] cube root Message-ID: <16251.131.203.105.1.1232363482.squirrel@mail.orcon.net.nz> The only language I've run into so far (I haven't used many, mind) that doesn't have this issue is Scheme :) (Just learning it at the moment.) Cheers, --Brett P.S. Forgive me if this email doesn't sort properly, sending through webmail, as I don't have a relaying SMTP available to me currently. Alan Gauld wrote: > > "Brett Wilkins" wrote > >> What you're running into here is the limited accuracy of floating point >> values... You'll likely find this happens a lot in python.. CPython, >> at least. > > In fact it happens with virtually every programming language available. > The problem traces back to the way that computers represent floating > point numbers in hardware. The integrated circuits cannot hold infinitely > long numbers so they need to use a condensed representation and > that inherently introduces small inaccuracies. (Think of 1/3 in > decimal - an infinite series of 1.3333..., the same is true in binary, > some numbers just cannot be represented accurately) > > In the specific case being discussed you can disguise the problem > quite easily by displaying the result with a smaller number of decimal > places using round() or string formatting: > >>>> 64**(1.0/3) > 3.9999999999999996 >>>> print 64**(1.0/3) > 4.0 >>>> round(64**(1.0/3)) > 4.0 >>>> "%5.3f" % 64**(1.0/3) > '4.000' >>>> > > When you need to compare floating point numbers you also > need to be careful since: > >>>> 4.0 == 64**(1.0/3) ## is false! > > You need to introduce an error range, typically: > >>>> e = 0.00000001 >>>> 4.0-e < 64**(1.0/3) < 4.0+e # is true > > You can also use the decimal module for exact decimal > arithmetic but it introduces some other complications. > > HTH, > > From kent37 at tds.net Mon Jan 19 12:58:11 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 19 Jan 2009 06:58:11 -0500 Subject: [Tutor] cube root In-Reply-To: <16251.131.203.105.1.1232363482.squirrel@mail.orcon.net.nz> References: <16251.131.203.105.1.1232363482.squirrel@mail.orcon.net.nz> Message-ID: <1c2a2c590901190358v5f20a2f2k70606162c301b9e4@mail.gmail.com> On Mon, Jan 19, 2009 at 6:11 AM, Brett Wilkins wrote: > The only language I've run into so far (I haven't used many, mind) that > doesn't have this issue is Scheme :) It doesn't have an issue with cube roots or with floating point inaccuracies in general? If the latter, I would like to know how they do that... Kent From denis.spir at free.fr Mon Jan 19 13:13:53 2009 From: denis.spir at free.fr (spir) Date: Mon, 19 Jan 2009 13:13:53 +0100 Subject: [Tutor] cube root In-Reply-To: References: <6a1b26420901182228v760bdaddweccbfed9b2495b12@mail.gmail.com> <4974209E.104@orcon.net.nz> Message-ID: <20090119131353.4c5d6b2a@o> Do you know any common algorithm to convert decimal (in the sense of fractional) decimals (in the sense of base 10 numbers) into binaries? 123.456 --> 1111011.bbb... and/or 123456 * 10**(-3) --> bbb... * 2**(-bbb...) How do python/C achieve that? denis ------ la vida e estranya From andreengels at gmail.com Mon Jan 19 13:15:25 2009 From: andreengels at gmail.com (Andre Engels) Date: Mon, 19 Jan 2009 13:15:25 +0100 Subject: [Tutor] cube root In-Reply-To: <16251.131.203.105.1.1232363482.squirrel@mail.orcon.net.nz> References: <16251.131.203.105.1.1232363482.squirrel@mail.orcon.net.nz> Message-ID: <6faf39c90901190415o5fc08255w2649df5b85520c74@mail.gmail.com> On Mon, Jan 19, 2009 at 12:11 PM, Brett Wilkins wrote: > The only language I've run into so far (I haven't used many, mind) that > doesn't have this issue is Scheme :) > (Just learning it at the moment.) It doesn't? That would surprise me. The only one that I know to do this kind of thing correctly is Matlab. -- Andr? Engels, andreengels at gmail.com From lupin at orcon.net.nz Mon Jan 19 13:20:48 2009 From: lupin at orcon.net.nz (Brett Wilkins) Date: Tue, 20 Jan 2009 01:20:48 +1300 (NZDT) Subject: [Tutor] cube root Message-ID: <18363.131.203.105.1.1232367648.squirrel@mail.orcon.net.nz> Hmm, Well I thought it was both, but the latter seems untrue (now that I test a bit more) (expt 64 (/ 1 3)) gives the value 4, but turning any of those into floating point numbers seems to give me the infamous 3.999999999999996 thing all over again. I was originally thinking that scheme would handle exponents as floating point numbers, the way that C does (ie 2e20 is a fp number...), and I tested 2e20+1-2e20, which stumps most languages (python just gives 0.0, gcc 4.0.1 gives the same). Oh well, sorry to get your hopes up! Btw, I'm using MIT/GNU scheme, in case that makes a difference. Cheers --Brett Kent Johnson wrote: > On Mon, Jan 19, 2009 at 6:11 AM, Brett Wilkins wrote: >> The only language I've run into so far (I haven't used many, mind) that >> doesn't have this issue is Scheme :) > > It doesn't have an issue with cube roots or with floating point > inaccuracies in general? If the latter, I would like to know how they > do that... > > Kent From andreengels at gmail.com Mon Jan 19 13:22:59 2009 From: andreengels at gmail.com (Andre Engels) Date: Mon, 19 Jan 2009 13:22:59 +0100 Subject: [Tutor] cube root In-Reply-To: <20090119131353.4c5d6b2a@o> References: <6a1b26420901182228v760bdaddweccbfed9b2495b12@mail.gmail.com> <4974209E.104@orcon.net.nz> <20090119131353.4c5d6b2a@o> Message-ID: <6faf39c90901190422g77265d0ewc673fcbde46fc532@mail.gmail.com> On Mon, Jan 19, 2009 at 1:13 PM, spir wrote: > Do you know any common algorithm to convert decimal (in the sense of fractional) decimals (in the sense of base 10 numbers) into binaries? > > 123.456 --> 1111011.bbb... > and/or > 123456 * 10**(-3) --> bbb... * 2**(-bbb...) > > How do python/C achieve that? There's probably more efficient methods, but a simple method to convert a decimal fraction to a binary would be the following (untested): def tobinary(n,precision=12) # n is a number between 0 and 1 that should be converted, precision is the number of binary digits to use. assert 0.0 <= n < 1.0 outcome = "0." compare = 0.5 for i in xrange(precision): if n > compare: outcome += "1" n -= compare if n == 0.0: break else: outcome += "0" compare /= 2 return outcome -- Andr? Engels, andreengels at gmail.com From denis.spir at free.fr Mon Jan 19 13:26:15 2009 From: denis.spir at free.fr (spir) Date: Mon, 19 Jan 2009 13:26:15 +0100 Subject: [Tutor] help on making python tictactoe In-Reply-To: <502624.34781.qm@web63305.mail.re1.yahoo.com> References: <502624.34781.qm@web63305.mail.re1.yahoo.com> Message-ID: <20090119132615.7cb8025f@o> Le Mon, 19 Jan 2009 01:18:41 -0800 (PST), jammy007 pp a ?crit : > guys , i need immediate help on creating a simple tictactoe game . > > i read micheal dawson's book but didnt quiet get it . > > please help . > > thanks . > > jammy > > > > try googling: "software developpment company python xxx" (name of your city here) --------------^ More seriously: This is a list for (mutual) help. You would have better results providing concrete information on what precise issue you "didnt quiet get" than demanding "immediate help". (I guess.) denis ------ la vida e estranya From ksterling at mindspring.com Mon Jan 19 14:46:21 2009 From: ksterling at mindspring.com (Ken Oliver) Date: Mon, 19 Jan 2009 08:46:21 -0500 (EST) Subject: [Tutor] cube root Message-ID: <23945681.1232372781650.JavaMail.root@mswamui-billy.atl.sa.earthlink.net> -----Original Message----- >From: Andre Engels >Sent: Jan 19, 2009 7:22 AM >To: spir >Cc: tutor at python.org >Subject: Re: [Tutor] cube root > >On Mon, Jan 19, 2009 at 1:13 PM, spir wrote: >> Do you know any common algorithm to convert decimal (in the sense of fractional) decimals (in the sense of base 10 numbers) into binaries? >> >> 123.456 --> 1111011.bbb... >> and/or >> 123456 * 10**(-3) --> bbb... * 2**(-bbb...) >> >> How do python/C achieve that? > >There's probably more efficient methods, but a simple method to >convert a decimal fraction to a binary would be the following >(untested): > >def tobinary(n,precision=12) > # n is a number between 0 and 1 that should be converted, >precision is the number of binary digits to use. > assert 0.0 <= n < 1.0 > outcome = "0." > compare = 0.5 > for i in xrange(precision): > if n > compare: > outcome += "1" > n -= compare > if n == 0.0: break > else: > outcome += "0" > compare /= 2 > return outcome > >-- >Andr? Engels, andreengels at gmail.com I hope my memory serves. To convert decimal fraction into binary fraction, do the following repeatedly to the decimal until desired accuracy is achieved. Multiply by 2, if result is less than 1, next digit is 0 else next digit is 1 and you drop the whole number part of the result. Continue... .456 * 2 = .912 (first digit is 0) .912 * 2 = 1.824 (next digit is 1) .824 * 2 = 1.648 (next digit is 1) .648 * 2 = 1.296 (next digit is 1) .296 * 2 = .592 (next digit is 0) 0.456 ~ 0.01110 From irimia.suleapa at unknownsoftware.ro Mon Jan 19 15:11:44 2009 From: irimia.suleapa at unknownsoftware.ro (Irimia, Suleapa) Date: Mon, 19 Jan 2009 16:11:44 +0200 Subject: [Tutor] Ip address Message-ID: <49748A20.50604@unknownsoftware.ro> Hello list, I am new to python and i have a question. I managed to build a client which connect to an website and grab things from there. I run this client on a linux box, which have multiple ip address. What do i want is to run 3 clients and each one to use different ip address to access that website. Anyone can point me to some documentation about how this can be done? Thanks and advance, From bhaaluu at gmail.com Mon Jan 19 15:55:55 2009 From: bhaaluu at gmail.com (bhaaluu) Date: Mon, 19 Jan 2009 09:55:55 -0500 Subject: [Tutor] help on making python tictactoe In-Reply-To: <502624.34781.qm@web63305.mail.re1.yahoo.com> References: <502624.34781.qm@web63305.mail.re1.yahoo.com> Message-ID: On Mon, Jan 19, 2009 at 4:18 AM, jammy007 pp wrote: > guys , i need immediate help on creating a simple tictactoe game . > > i read micheal dawson's book but didnt quiet get it . > > please help . > > thanks . > > jammy Python Programming for the Absolute Beginner 2E by Michael Dawson has the BEST explanation there is of programming a Tic-Tac-Toe game! It is explained in Chapter 6 Functions The Tic-Tac-Toe Game. If you've read and done the Challenges in Chapters 1-5, then the 'new' concept on Chapter 6 is how to program with functions. Otherwise, the Tic-Tac-Toe game is covered step-by-step. 1. Read Chapter 6. 2. Go back and highlight the important new concepts. 3. Key the Tic-Tac-Toe program into your computer. (It is better to key it in than copy/paste it from the CD) 4. Get the game running on your computer. You'll find typos. This is part of learning Python. You need to make mistakes. Finding and correcting your mistakes is an important part of learning how to program a computer.. 5. Make a hard-copy print-out of the source code for the game you just got running.. 6. Play computer by reading and following the program flow in the printout. Underline, highlight, and write notes in the margins of the printout as you 'play computer'. 7. Do the Challenges for Chapter 6. Challenge No. 4 is to plug the hole in the strategy of the game in the book. To do that, you'll need to modify the game in the book. If you've followed the above instructions, you should have no problems. 8. If you still have problems, post _your_ problem source code to this list with an explanation of what your problem is. Happy Programming! -- b h a a l u u at g m a i l dot c o m Kid on Bus: What are you gonna do today, Napoleon? Napoleon Dynamite: Whatever I feel like I wanna do. Gosh! From srilyk at gmail.com Mon Jan 19 16:27:07 2009 From: srilyk at gmail.com (W W) Date: Mon, 19 Jan 2009 09:27:07 -0600 Subject: [Tutor] Ip address In-Reply-To: <49748A20.50604@unknownsoftware.ro> References: <49748A20.50604@unknownsoftware.ro> Message-ID: <333efb450901190727s261437dbi3cdb8fe55e85b8bb@mail.gmail.com> On Mon, Jan 19, 2009 at 8:11 AM, Irimia, Suleapa < irimia.suleapa at unknownsoftware.ro> wrote: > Hello list, > > I am new to python and i have a question. I managed to build a client which > connect to an website and grab things from there. I run this client on a > linux box, which have multiple ip address. What do i want is to run 3 > clients and each one to use different ip address to access that website. > Anyone can point me to some documentation about how this can be done? > I'm not 100% sure if I understand what you're saying, so let me clarify: You have one linux box, with 3 instances of your program running, and you want the server to see these as three unique IPs? I'm not aware of any way to do this without proxy servers or IP spoofing. HTH, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From brian.mathis at gmail.com Mon Jan 19 17:15:57 2009 From: brian.mathis at gmail.com (Brian Mathis) Date: Mon, 19 Jan 2009 11:15:57 -0500 Subject: [Tutor] help on making python tictactoe In-Reply-To: <502624.34781.qm@web63305.mail.re1.yahoo.com> References: <502624.34781.qm@web63305.mail.re1.yahoo.com> Message-ID: <183c528b0901190815oa11eb63rb7a902e4f92af077@mail.gmail.com> On Mon, Jan 19, 2009 at 4:18 AM, jammy007 pp wrote: > guys , i need immediate help on creating a simple tictactoe game . > > i read micheal dawson's book but didnt quiet get it . > > please help . > > thanks . > > jammy The purpose of homework is that you figure it out for yourself and learn something. From eike.welk at gmx.net Mon Jan 19 18:57:35 2009 From: eike.welk at gmx.net (Eike Welk) Date: Mon, 19 Jan 2009 18:57:35 +0100 Subject: [Tutor] Non-blocking non-interactive graphics display In-Reply-To: <4a289b480901142200k3e376eaeg39de1ed8de1e239c@mail.gmail.com> References: <4a289b480901142200k3e376eaeg39de1ed8de1e239c@mail.gmail.com> Message-ID: <200901191857.36613.eike.welk@gmx.net> You should look at IPython it is a frontend for the Python interpreter that runs the eventloop of Matplotlib in a separate thread. http://ipython.scipy.org/moin/ http://matplotlib.sourceforge.net/ Matplotlib and Ipython might be in your Python distribution from Enthougt. A session with Ipython looks like this: ---------------------------------------------------- eike at lixie:~> ipython --pylab Welcome to pylab, a matplotlib-based Python environment. For more information, type 'help(pylab)'. In [1]:plot([1,2,4,8]) Out[1]:[] In [2]:#A window with a graph has appeared. One can pan and zoom this graph. In [3]:1+2+3 Out[3]:6 In [4]: ----------------------------------------------------- In the Matplotlib newsgroup you would have to ask how to draw graphical primitives (lines). HTH, Eike. From steve at alchemy.com Mon Jan 19 19:05:22 2009 From: steve at alchemy.com (Steve Willoughby) Date: Mon, 19 Jan 2009 10:05:22 -0800 Subject: [Tutor] Question about pygame/tkinter interaction In-Reply-To: <200901191857.36613.eike.welk@gmx.net> References: <4a289b480901142200k3e376eaeg39de1ed8de1e239c@mail.gmail.com> <200901191857.36613.eike.welk@gmx.net> Message-ID: <20090119180522.GA66977@dragon.alchemy.com> I have a game I'm porting to Python which is currently written using TCL/Tk. Now it would be fairly easy to make it work in Python with Tkinter, of course, since the way the GUI would be organized and implemented would be essentially the same. However, I'd also like to implement some fancier (but minor) animated effects and embed video and audio clips. So I was thinking that pygame (or pymedia) would be reasonable choices, but I've never used either of those before. Is it reasonable to expect that I could use Tkinter for everything else, but use pygame/pymedia to handle things like creating a video playback window on the screen, or is pygame going to want to run the whole GUI event loop and screen updates in competition with Tkinter? Any general nudges in the right direction would be appreciated. Thanks, steve -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From wescpy at gmail.com Mon Jan 19 19:36:07 2009 From: wescpy at gmail.com (wesley chun) Date: Mon, 19 Jan 2009 10:36:07 -0800 Subject: [Tutor] Convert String to Int In-Reply-To: References: <40af687b0901181735j58d1c1adq5c654efeed9b6ab1@mail.gmail.com> Message-ID: <78b3a9580901191036l4ed1912ele606b6e47535e858@mail.gmail.com> > if type(x) == int: # check its an integer i also understand that it's "isinstance(x, int)" should be used instead of the above or "if type(x) is int" but i'm running a blank as to why at this exact moment... perhaps it's an all-C function? however, all of these comparisons are only good if 'x' represents the object of desire. if it's output from raw_input() [in 2.x] or input() [in 3.x], it won't do any good because 'x' would still be a str. so before converting to an int, i would go with the isdigit() method, perhaps x.strip().isdigit() because you don't want to be messed up by a user who may have inadvertently typed one or more spaces before or after the number. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From srilyk at gmail.com Mon Jan 19 19:45:29 2009 From: srilyk at gmail.com (W W) Date: Mon, 19 Jan 2009 12:45:29 -0600 Subject: [Tutor] Question about pygame/tkinter interaction In-Reply-To: <20090119180522.GA66977@dragon.alchemy.com> References: <4a289b480901142200k3e376eaeg39de1ed8de1e239c@mail.gmail.com> <200901191857.36613.eike.welk@gmx.net> <20090119180522.GA66977@dragon.alchemy.com> Message-ID: <333efb450901191045j234d0cch621032eed00c4f0a@mail.gmail.com> On Mon, Jan 19, 2009 at 12:05 PM, Steve Willoughby wrote: > Is it reasonable to expect that I could use Tkinter for > everything else, but use pygame/pymedia to handle things like > creating a video playback window on the screen, or is pygame > going to want to run the whole GUI event loop and screen updates > in competition with Tkinter? > > Any general nudges in the right direction would be appreciated. > Thanks, > steve > As far as I know it would be a fairly reasonable expectation - you would simply hide the Tkinter screen when you show the pygame/pymedia window. However, I'm not nearly as versed on any of the above as a lot of folks here, so they may be able to confirm/contradict my advice. But with my limited knowledge, that's probably how I'd do it (unless you have a burning desire to learn pygame). HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From eike.welk at gmx.net Mon Jan 19 21:16:20 2009 From: eike.welk at gmx.net (Eike Welk) Date: Mon, 19 Jan 2009 21:16:20 +0100 Subject: [Tutor] Question about pygame/tkinter interaction In-Reply-To: <20090119180522.GA66977@dragon.alchemy.com> References: <4a289b480901142200k3e376eaeg39de1ed8de1e239c@mail.gmail.com> <200901191857.36613.eike.welk@gmx.net> <20090119180522.GA66977@dragon.alchemy.com> Message-ID: <200901192116.21021.eike.welk@gmx.net> You could use Qt and PyQt (bindings) for your application. QT is a library for buttons and similar things; it can show images, play video and play sound. They should both be part of every big Linux distribution. They are also available for Windows and Mac OS. http://doc.trolltech.com/4.4/index.html http://www.riverbankcomputing.co.uk/news List of tutorials: http://www.diotavelli.net/PyQtWiki/Tutorials Kind regards, Eike. From kent37 at tds.net Mon Jan 19 21:11:16 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 19 Jan 2009 15:11:16 -0500 Subject: [Tutor] Convert String to Int In-Reply-To: <78b3a9580901191036l4ed1912ele606b6e47535e858@mail.gmail.com> References: <40af687b0901181735j58d1c1adq5c654efeed9b6ab1@mail.gmail.com> <78b3a9580901191036l4ed1912ele606b6e47535e858@mail.gmail.com> Message-ID: <1c2a2c590901191211xc993913q4ab164ac470e80b@mail.gmail.com> On Mon, Jan 19, 2009 at 1:36 PM, wesley chun wrote: >> if type(x) == int: # check its an integer > > > i also understand that it's "isinstance(x, int)" should be used > instead of the above or "if type(x) is int" but i'm running a blank as > to why at this exact moment... perhaps it's an all-C function? If x is an instance of a subclass of Y, 'type(x) == Y" and "type(x) is Y" will fail; isinstance(x, Y) will succeed. Generally it's preferable to allow subclasses so isinstance() is preferred. Kent From kent37 at tds.net Mon Jan 19 23:30:01 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 19 Jan 2009 17:30:01 -0500 Subject: [Tutor] Question about pygame/tkinter interaction In-Reply-To: <20090119180522.GA66977@dragon.alchemy.com> References: <4a289b480901142200k3e376eaeg39de1ed8de1e239c@mail.gmail.com> <200901191857.36613.eike.welk@gmx.net> <20090119180522.GA66977@dragon.alchemy.com> Message-ID: <1c2a2c590901191430o561da1a6o952229c05c4afd6f@mail.gmail.com> On Mon, Jan 19, 2009 at 1:05 PM, Steve Willoughby wrote: > Is it reasonable to expect that I could use Tkinter for > everything else, but use pygame/pymedia to handle things like > creating a video playback window on the screen, or is pygame > going to want to run the whole GUI event loop and screen updates > in competition with Tkinter? My guess is that pygame and Tkinter are both going to want to control the event loop. Googling 'pygame tkinter' gives both hints that it might be possible and hints of trouble... Kent From benjamin.serrato at gmail.com Mon Jan 19 23:36:54 2009 From: benjamin.serrato at gmail.com (Benjamin Serrato) Date: Mon, 19 Jan 2009 16:36:54 -0600 Subject: [Tutor] Tutor Digest, Vol 59, Issue 90 In-Reply-To: References: Message-ID: I would like to add that 'A Byte of Python has been updated for python3.0 print statements are corrected and Swaroop looks to be still working on it. It's a wiki now, so the text can be edited if you find a better explanation and would like to add to it. I like Swaroop's style though. B Serrato > Hello all, I just joined this mailing list. > > I am a beginner to programming in general and would really appreciate a > > tutorial for Python3000 that at least covers the basics. I have tried > > reading the manual, but I think it was written for more experienced > > programmers wishing to switch to python rather than a beginner looking for > > where to start. Most of the other tutorials I have found were for earlier > > versions of Python, and because Python 3.0 was released on my birthday, I > > decided I was meant to learn that release. ;-) > > Anyway, any help would be appreciated. I will do my best to return the > > favor. > > -Ian > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lidereshumanistas at gmail.com Mon Jan 19 23:40:37 2009 From: lidereshumanistas at gmail.com (Lideres Humanistas) Date: Mon, 19 Jan 2009 19:40:37 -0300 Subject: [Tutor] Python in the World March For Peace and Nonviolence Message-ID: Designers Python: We may use the Global March for Peace and Nonviolence to position the Python language and free software in the world. And joined the World March Richard Sallman. http://marchamundial.org/en/participation-participation-forms/listados-de-adhesiones/some-of-our-participants/163-richard-stallman Emilio Castro. -- Inter?s Cehum.cl: Desarrollar el conocimiento por encima de los pre-dialogales aceptados o impuestos al pensamiento como verdades consideradas intencionalmente como absolutas e inamovibles. Sitios Web de inter?s humanizador: http://humanistasenaccion.org http://www.cehum.cl http://groups.google.es/group/punta-de-vacas-2010 http://groups.google.es/group/revolucion-industrial-humanista http://groups.google.es/group/revolucion-educacional-humanista http://groups.google.es/group/revolucion-salud-humanista http://groups.google.es/group/revolucion-deportiva-humanista http://groups.google.es/group/desarme-nuclear-universal http://flickr.com/photos/humanizador/ http://flickr.com/photos/humanizate/ http://humanizador.blogspot.com/ http://www.youtube.com/humanizador http://www.panoramio.com/user/650187 http://www.florcitamotuda.tk http://www.yonopago.cl http://www.silo.net http://www.silo.ws http://www.parquemanantiales.org http://www.parquepuntadevacas.org -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Tue Jan 20 00:04:33 2009 From: srilyk at gmail.com (W W) Date: Mon, 19 Jan 2009 17:04:33 -0600 Subject: [Tutor] 2.5 vs 3k? Message-ID: <333efb450901191504p3be78737xff89463226e1c701@mail.gmail.com> So, I'm curious about this whole python 3k thing. Is python migrating to 3k only? Will 2.x no longer be "officially" supported? If so/not, what are some of the arguments for migrating to 3k? What makes it "better" than the python we all know and love? Thanks for the info/comments, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Jan 20 00:36:33 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 19 Jan 2009 23:36:33 -0000 Subject: [Tutor] 2.5 vs 3k? References: <333efb450901191504p3be78737xff89463226e1c701@mail.gmail.com> Message-ID: "W W" wrote > So, I'm curious about this whole python 3k thing. Is python > migrating to 3k > only? Will 2.x no longer be "officially" supported? If you look at what happened with other major language changes (Perl 4->5 for example) there is likely to be a lot of support for 2.X Python for several years. This will likely be driven by necessity, there is an awful lot of code out there that won't be upgraded to 3 for a long time. But new features will likely start to only appear in 3. And 2.X releases will be focused on bug fixes etc. > If so/not, what are some of the arguments for migrating to 3k? What > makes it > "better" than the python we all know and love? There is a web page somewhere on the web site that gives a list of the new features/improvements. None of them are totally compelling for me but I am starting to look into it now. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/l From john at fouhy.net Tue Jan 20 00:38:11 2009 From: john at fouhy.net (John Fouhy) Date: Tue, 20 Jan 2009 12:38:11 +1300 Subject: [Tutor] 2.5 vs 3k? In-Reply-To: <333efb450901191504p3be78737xff89463226e1c701@mail.gmail.com> References: <333efb450901191504p3be78737xff89463226e1c701@mail.gmail.com> Message-ID: <5e58f2e40901191538v43cc49d6j283bb441f4c602f9@mail.gmail.com> 2009/1/20 W W : > So, I'm curious about this whole python 3k thing. Is python migrating to 3k > only? Will 2.x no longer be "officially" supported? Python might be transitioning to 3.0, but the full migration will take years. Python 2.6 is not going away -- in fact, I see on python.org that new versions of python 2.5 and 2.4 have just been released -- and python 2.7 will come out in time. > If so/not, what are some of the arguments for migrating to 3k? What makes it > "better" than the python we all know and love? You can see the short list of what's new/different here: http://docs.python.org/3.0/whatsnew/3.0.html If any of that appeals to you, then go for it :-) An argument for _not_ migrating (yet) is that most 3rd party libraries are still python 2.x. I expect they'll start to change, though, and you might need to migrate eventually if you want access to new stuff. -- John. From steve at alchemy.com Tue Jan 20 00:46:27 2009 From: steve at alchemy.com (Steve Willoughby) Date: Mon, 19 Jan 2009 15:46:27 -0800 Subject: [Tutor] Question about pygame/tkinter interaction In-Reply-To: <1c2a2c590901191430o561da1a6o952229c05c4afd6f@mail.gmail.com> References: <4a289b480901142200k3e376eaeg39de1ed8de1e239c@mail.gmail.com> <200901191857.36613.eike.welk@gmx.net> <20090119180522.GA66977@dragon.alchemy.com> <1c2a2c590901191430o561da1a6o952229c05c4afd6f@mail.gmail.com> Message-ID: <20090119234627.GA91182@dragon.alchemy.com> On Mon, Jan 19, 2009 at 05:30:01PM -0500, Kent Johnson wrote: > My guess is that pygame and Tkinter are both going to want to control > the event loop. Googling 'pygame tkinter' gives both hints that it > might be possible and hints of trouble... Yeah, I was thinking that, but since what I saw up until the point I asked the list was that for pygame you seem to write your own event loop, like while True: handle_event_myself(pygame.event.get()) whereas Tkinter wants you to just hand it control and let your program flow disappear into that black box entirely, until it pokes callbacks at you, I thought... "Well, maybe..." -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From ajarncolin at gmail.com Tue Jan 20 01:56:39 2009 From: ajarncolin at gmail.com (col speed) Date: Tue, 20 Jan 2009 07:56:39 +0700 Subject: [Tutor] cube root In-Reply-To: <50ed08f40901190228h1a2858c1g1061068d16515560@mail.gmail.com> References: <6a1b26420901182228v760bdaddweccbfed9b2495b12@mail.gmail.com> <4974209E.104@orcon.net.nz> <50ed08f40901190228h1a2858c1g1061068d16515560@mail.gmail.com> Message-ID: <6a1b26420901191656t205e4271n15490bf962d44ec4@mail.gmail.com> Wow! I seem to have caused a great deal of comments! I actually am looking to see if a number is a "perfect cube". I will try out all the suggestions. Thanks a lot. Colin P.S. I have a small programme that changes decimal to binary (I don't know if it can be changed to work with fractions or not), maybe it will help. def dec2bin(dec): bin = '' while dec > 0: bin = str(dec & 1) + bin dec >>= 1 return bin 2009/1/19 Vicent > > > > > On Mon, Jan 19, 2009 at 07:41, Brett Wilkins wrote: > >> >> What you're running into here is the limited accuracy of floating point >> values... >> You'll likely find this happens a lot in python.. CPython, at least. (I >> know, as I do) >> I'm not sure, as I've never used it... but perhaps Numeric/Numpy handle >> this kinda stuff better (for accuracy's sake) >> >> > Maybe this issue can be overcome by using symbolic notation when possible > (maybe by using SymPy)? Has anyone any experience with this? > > -- > Vicent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cfuller084 at thinkingplanet.net Tue Jan 20 02:07:38 2009 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Mon, 19 Jan 2009 19:07:38 -0600 Subject: [Tutor] cube root In-Reply-To: <6a1b26420901191656t205e4271n15490bf962d44ec4@mail.gmail.com> References: <6a1b26420901182228v760bdaddweccbfed9b2495b12@mail.gmail.com> <50ed08f40901190228h1a2858c1g1061068d16515560@mail.gmail.com> <6a1b26420901191656t205e4271n15490bf962d44ec4@mail.gmail.com> Message-ID: <200901191907.38608.cfuller084@thinkingplanet.net> On Monday 19 January 2009 18:56, col speed wrote: > Wow! I seem to have caused a great deal of comments! > I actually am looking to see if a number is a "perfect cube". I will try > out all the suggestions. > Thanks a lot. > Colin The reliable way to do this is to store a list of cubes. If the number you want to check is not in your list, then compute more cubes until you exceed that number. Unless you are dealing with absurdly huge numbers, this won't be very onerous on computing time. Cheers From emadnawfal at gmail.com Tue Jan 20 03:18:45 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Mon, 19 Jan 2009 21:18:45 -0500 Subject: [Tutor] Finding the shortest word in a list of words Message-ID: <652641e90901191818i43253d11p25db401076b13e81@mail.gmail.com> Hello tutors, I need to find the shortest / longest word(s) in a sequence of words. I've done this and it works, but I'm wondering whether this is a good way: >>> words = "man woman children he".split() >>> words ['man', 'woman', 'children', 'he'] >>> lens = [len(word) for word in words] >>> lens [3, 5, 8, 2] >>> for word in words: ... if len(word) == min(lens): print word ... he >>> -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From john at fouhy.net Tue Jan 20 03:31:41 2009 From: john at fouhy.net (John Fouhy) Date: Tue, 20 Jan 2009 15:31:41 +1300 Subject: [Tutor] Finding the shortest word in a list of words In-Reply-To: <652641e90901191818i43253d11p25db401076b13e81@mail.gmail.com> References: <652641e90901191818i43253d11p25db401076b13e81@mail.gmail.com> Message-ID: <5e58f2e40901191831n45ab7d07h558244efeb52dd99@mail.gmail.com> 2009/1/20 Emad Nawfal (???? ????) : > Hello tutors, > I need to find the shortest / longest word(s) in a sequence of words. I've > done this and it works, but I'm wondering whether this is a good way: >>>> words = "man woman children he".split() >>>> words > ['man', 'woman', 'children', 'he'] >>>> lens = [len(word) for word in words] >>>> lens > [3, 5, 8, 2] >>>> for word in words: > ... if len(word) == min(lens): print word > ... > he Hi Emad, You can use the decorate-sort-undecorate idiom to make this technique a bit nicer. "decorate" means "add information to the things in the list": >>> words_and_lengths = [(len(w), w) for w in words] >>> words_and_lengths [(3, 'man'), (5, 'woman'), (8, 'children'), (2, 'he')] Now I can sort it and get the shortest element easily: >>> words_and_lengths.sort() >>> words_and_lengths[0] (2, 'he') Or I can undecorate: >>> words2 = [w[1] for w in words_and_lengths] >>> words2 ['he', 'man', 'woman', 'children'] Python 2.5+ provides another way of doing this, using the key= argument to sort(): >>> words ['man', 'woman', 'children', 'he'] >>> words.sort(key=len) >>> words ['he', 'man', 'woman', 'children'] This essentially does the decorate-sort-undecorate in one step, where len is the function we used to do the decoration. Of course, this is not necessarily the best answer for your particular problem. The problem with sorting is that you have to look at some elements more than once. For short lists, it's not a problem, but it can slow you down on bigger lists. You could also find the shortest element by going through the list, remembering the shortest element you've seen so far. This will be quicker if you only want to find the single shortest. -- John. From emadnawfal at gmail.com Tue Jan 20 03:47:44 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Mon, 19 Jan 2009 21:47:44 -0500 Subject: [Tutor] Finding the shortest word in a list of words In-Reply-To: <5e58f2e40901191831n45ab7d07h558244efeb52dd99@mail.gmail.com> References: <652641e90901191818i43253d11p25db401076b13e81@mail.gmail.com> <5e58f2e40901191831n45ab7d07h558244efeb52dd99@mail.gmail.com> Message-ID: <652641e90901191847m40c1853ibac006364519ad54@mail.gmail.com> 2009/1/19 John Fouhy > 2009/1/20 Emad Nawfal (???? ????) : > > Hello tutors, > > I need to find the shortest / longest word(s) in a sequence of words. > I've > > done this and it works, but I'm wondering whether this is a good way: > >>>> words = "man woman children he".split() > >>>> words > > ['man', 'woman', 'children', 'he'] > >>>> lens = [len(word) for word in words] > >>>> lens > > [3, 5, 8, 2] > >>>> for word in words: > > ... if len(word) == min(lens): print word > > ... > > he > > Hi Emad, > > You can use the decorate-sort-undecorate idiom to make this technique > a bit nicer. > > "decorate" means "add information to the things in the list": > > >>> words_and_lengths = [(len(w), w) for w in words] > >>> words_and_lengths > [(3, 'man'), (5, 'woman'), (8, 'children'), (2, 'he')] > > Now I can sort it and get the shortest element easily: > > >>> words_and_lengths.sort() > >>> words_and_lengths[0] > (2, 'he') > > Or I can undecorate: > > >>> words2 = [w[1] for w in words_and_lengths] > >>> words2 > ['he', 'man', 'woman', 'children'] > > Python 2.5+ provides another way of doing this, using the key= > argument to sort(): > > >>> words > ['man', 'woman', 'children', 'he'] > >>> words.sort(key=len) > >>> words > ['he', 'man', 'woman', 'children'] > > This essentially does the decorate-sort-undecorate in one step, where > len is the function we used to do the decoration. > > Of course, this is not necessarily the best answer for your particular > problem. The problem with sorting is that you have to look at some > elements more than once. For short lists, it's not a problem, but it > can slow you down on bigger lists. You could also find the shortest > element by going through the list, remembering the shortest element > you've seen so far. This will be quicker if you only want to find the > single shortest. > > -- > John. > Thanks John for this. Although the decorate-sort-undecorate idiom looks so natural to me now, I don't think I would have found it on my own. I have that deja vu effect towards it. Thanks again. -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Tue Jan 20 04:13:32 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 19 Jan 2009 19:13:32 -0800 Subject: [Tutor] Finding the shortest word in a list of words In-Reply-To: <5e58f2e40901191831n45ab7d07h558244efeb52dd99@mail.gmail.com> References: <652641e90901191818i43253d11p25db401076b13e81@mail.gmail.com> <5e58f2e40901191831n45ab7d07h558244efeb52dd99@mail.gmail.com> Message-ID: <40af687b0901191913s6f566835h8e518cec7c47d734@mail.gmail.com> 2009/1/19 John Fouhy > 2009/1/20 Emad Nawfal (???? ????) : > Of course, this is not necessarily the best answer for your particular > problem. The problem with sorting is that you have to look at some > elements more than once. For short lists, it's not a problem, but it > can slow you down on bigger lists. You could also find the shortest > element by going through the list, remembering the shortest element > you've seen so far. This will be quicker if you only want to find the > single shortest. > Here's the first thing that came to mind: > from sys import maxint > > def MinMax(Sentence=""): > minLen = maxint > maxLen = 0 > > for word in Sentence.split(): > if len(word) > maxLen: > maxWord = word > maxLen = len(word) > if len(word) < minLen: > minWord = word > minLen = len(word) > return minLen, minWord, maxLen, maxWord > > > print MinMax("No victim has ever been more repressed and alienated than the > truth") > Using sys.maxint to prime minLen is overkill, of course - "antidisestablishmentarianism" is only 28 letters long, after all - but it should be larger than any word you can expect to see. This doesn't catch ties, though... could do that like so: for word in Sentence.split(): > if len(word) == minLen: > minWord.append(word) > if len(word) == maxLen: > maxWord.append(word) > if len(word) > maxLen: > maxWord = [word] > maxLen = len(word) > if len(word) < minLen: > minWord = [word] > minLen = len(word) > > -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From wormwood_3 at yahoo.com Tue Jan 20 04:47:54 2009 From: wormwood_3 at yahoo.com (wormwood_3) Date: Mon, 19 Jan 2009 19:47:54 -0800 (PST) Subject: [Tutor] Ip address References: <49748A20.50604@unknownsoftware.ro> <333efb450901190727s261437dbi3cdb8fe55e85b8bb@mail.gmail.com> Message-ID: <386909.88079.qm@web110802.mail.gq1.yahoo.com> Hello, This is definitely possible. It's more a matter of system and OS configuration than Python though, so you might want to check out some Linux forums ( http://www.linuxforums.org/ ) for additional help. In short, I think the simplest would be: Have 3 separate network interfaces in your physical box, have your router provide one of the three addresses to each. Then you could configure the client to only connect through its associated interface/IP. If this sort of setup wouldn't work, please tell us more about your configuration between your client and your network. -Sam _______________________ Samuel Huckins Homepage - http://samuelhuckins.com Tech blog - http://dancingpenguinsoflight.com/ Photos - http://www.flickr.com/photos/samuelhuckins/ AIM - samushack | Gtalk - samushack | Skype - shuckins ________________________________ From: W W To: irimia.suleapa at unknownsoftware.ro Cc: tutor at python.org Sent: Monday, January 19, 2009 10:27:07 AM Subject: Re: [Tutor] Ip address On Mon, Jan 19, 2009 at 8:11 AM, Irimia, Suleapa wrote: Hello list, I am new to python and i have a question. I managed to build a client which connect to an website and grab things from there. I run this client on a linux box, which have multiple ip address. What do i want is to run 3 clients and each one to use different ip address to access that website. Anyone can point me to some documentation about how this can be done? I'm not 100% sure if I understand what you're saying, so let me clarify: You have one linux box, with 3 instances of your program running, and you want the server to see these as three unique IPs? I'm not aware of any way to do this without proxy servers or IP spoofing. HTH, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From cfuller084 at thinkingplanet.net Tue Jan 20 05:16:01 2009 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Mon, 19 Jan 2009 22:16:01 -0600 Subject: [Tutor] Question about pygame/tkinter interaction In-Reply-To: <20090119180522.GA66977@dragon.alchemy.com> References: <4a289b480901142200k3e376eaeg39de1ed8de1e239c@mail.gmail.com> <200901191857.36613.eike.welk@gmx.net> <20090119180522.GA66977@dragon.alchemy.com> Message-ID: <200901192216.01190.cfuller084@thinkingplanet.net> On Monday 19 January 2009 12:05, Steve Willoughby wrote: > I have a game I'm porting to Python which is currently written > using TCL/Tk. Now it would be fairly easy to make it work in > Python with Tkinter, of course, since the way the GUI would be > organized and implemented would be essentially the same. > > However, I'd also like to implement some fancier (but minor) > animated effects and embed video and audio clips. So I was > thinking that pygame (or pymedia) would be reasonable choices, > but I've never used either of those before. > > Is it reasonable to expect that I could use Tkinter for > everything else, but use pygame/pymedia to handle things like > creating a video playback window on the screen, or is pygame > going to want to run the whole GUI event loop and screen updates > in competition with Tkinter? > > Any general nudges in the right direction would be appreciated. > Thanks, > steve I have successfully run dual GUI managers at once (Tkinter and wxPython) by suspending the mainloop of one and starting the other. You might be able to setup a timeout in one GUI to service pending events in the other if this approach would be difficult. GUIs tend to want to be in the main thread. Certainly any GUI functions called from other threads must be via locks. You could try experimenting with having a thread for each GUI, but I would expect problems. Another solution would be to have two separate Python instances with some form of interprocess communications. This doesn't have to be all that difficult, if you are careful with the design. You can use pickle to convert complex objects into strings, for instance. Cheers From jammy007_pp at yahoo.com Tue Jan 20 06:37:43 2009 From: jammy007_pp at yahoo.com (jammy007 pp) Date: Mon, 19 Jan 2009 21:37:43 -0800 (PST) Subject: [Tutor] thanks Message-ID: <274188.91264.qm@web63308.mail.re1.yahoo.com> thanks a lot for responding to my emails , the suggestions that i got from the members were pretty good , i like the suggestion that bhaalu gave me . feeling motivated now . will read the chapter again . god bless us all . -------------- next part -------------- An HTML attachment was scrubbed... URL: From norman at khine.net Tue Jan 20 10:49:55 2009 From: norman at khine.net (Norman Khine) Date: Tue, 20 Jan 2009 10:49:55 +0100 Subject: [Tutor] creating a sound file from a string Message-ID: <49759E43.2020902@khine.net> hello, i have a string that is generated that contains letters and numbers. i also have a folder which contains the following: sounds/ upper-a.wav upper-b.wav .. lower-a.wav lower-b.wav ... sign-?.wav sign-|.wav .. number-0.wav number-1.wav .. does anyone know of a python module which would create a single sound file based on the randomly generated string? i have looked at the python wave module, but if i am not wrong this works with one file at the time. any advise much appreciated. many thanks norman From manoj_kumar2512 at rediffmail.com Tue Jan 20 12:10:14 2009 From: manoj_kumar2512 at rediffmail.com (Manoj kumar) Date: 20 Jan 2009 11:10:14 -0000 Subject: [Tutor] MySqldb problem Message-ID: <20090120111014.59680.qmail@f5mail-237-208.rediffmail.com> ? hi all, i am a newbie to python programming. i just know basics of the language. i came across MySqldb. i able to manipulate database with MySqldb but i wasn't able to add files in database through the lib MySqldb. any help will be welcomed gracefully. thanks. MANOJ SHEOKAND (+919728523528) "some day there won't be a song in ur heart, sing anyway" -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Jan 20 12:45:58 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 20 Jan 2009 06:45:58 -0500 Subject: [Tutor] Finding the shortest word in a list of words In-Reply-To: <652641e90901191847m40c1853ibac006364519ad54@mail.gmail.com> References: <652641e90901191818i43253d11p25db401076b13e81@mail.gmail.com> <5e58f2e40901191831n45ab7d07h558244efeb52dd99@mail.gmail.com> <652641e90901191847m40c1853ibac006364519ad54@mail.gmail.com> Message-ID: <1c2a2c590901200345y2e7ef466s42be9975328363a1@mail.gmail.com> On Mon, Jan 19, 2009 at 9:47 PM, Emad Nawfal (???? ????) wrote: > Thanks John for this. Although the decorate-sort-undecorate idiom looks so > natural to me now, I don't think I would have found it on my own. I have > that deja vu effect towards it. decorate-sort-undecorate is pretty much obsolete since the key= parameter was added to sort() in Python 2.4. Since Python 2.5 you can also use key= with min() and max() so your problem can be solved very simply and tersely: In [1]: words = "man woman children he".split() In [2]: min(words, key=len) Out[2]: 'he' Kent From lie.1296 at gmail.com Tue Jan 20 12:48:19 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 20 Jan 2009 11:48:19 +0000 (UTC) Subject: [Tutor] Question about pygame/tkinter interaction References: <4a289b480901142200k3e376eaeg39de1ed8de1e239c@mail.gmail.com> <200901191857.36613.eike.welk@gmx.net> <20090119180522.GA66977@dragon.alchemy.com> <1c2a2c590901191430o561da1a6o952229c05c4afd6f@mail.gmail.com> <20090119234627.GA91182@dragon.alchemy.com> Message-ID: On Mon, 19 Jan 2009 15:46:27 -0800, Steve Willoughby wrote: > On Mon, Jan 19, 2009 at 05:30:01PM -0500, Kent Johnson wrote: >> My guess is that pygame and Tkinter are both going to want to control >> the event loop. Googling 'pygame tkinter' gives both hints that it >> might be possible and hints of trouble... > > Yeah, I was thinking that, but since what I saw up until the point I > asked the list was that for pygame you seem to write your own event > loop, like > > while True: > handle_event_myself(pygame.event.get()) > > whereas Tkinter wants you to just hand it control and let your program > flow disappear into that black box entirely, until it pokes callbacks at > you, I thought... "Well, maybe..." I guess it shouldn't be too difficult if what you're intending is to have one window controlled by Tkinter and the other by pygame, it's just a matter of having Tkinter calling pygame's event handler once in a while (so instead of while True: handle_pygame_event() insert an event that makes Tkinter calls handle_pygame_event() every once in a while. ) What I don't know is whether it is possible to "embed" a pygame- controlled frame into Tkinter-controlled window. From kent37 at tds.net Tue Jan 20 13:03:55 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 20 Jan 2009 07:03:55 -0500 Subject: [Tutor] creating a sound file from a string In-Reply-To: <49759E43.2020902@khine.net> References: <49759E43.2020902@khine.net> Message-ID: <1c2a2c590901200403k3a4008d2la504ed9746d0fdcb@mail.gmail.com> On Tue, Jan 20, 2009 at 4:49 AM, Norman Khine wrote: > does anyone know of a python module which would create a single sound file > based on the randomly generated string? > > i have looked at the python wave module, but if i am not wrong this works > with one file at the time. I think you can do this with the wave module. The code would be something like this: open output file and set number of channels, etc for each letter of input: open wave file for the letter read frames from letter file write frames to output file close output file Kent From emadnawfal at gmail.com Tue Jan 20 13:13:10 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Tue, 20 Jan 2009 07:13:10 -0500 Subject: [Tutor] Finding the shortest word in a list of words In-Reply-To: <1c2a2c590901200345y2e7ef466s42be9975328363a1@mail.gmail.com> References: <652641e90901191818i43253d11p25db401076b13e81@mail.gmail.com> <5e58f2e40901191831n45ab7d07h558244efeb52dd99@mail.gmail.com> <652641e90901191847m40c1853ibac006364519ad54@mail.gmail.com> <1c2a2c590901200345y2e7ef466s42be9975328363a1@mail.gmail.com> Message-ID: <652641e90901200413x64f662bdsb91f04b2ee574ee9@mail.gmail.com> 2009/1/20 Kent Johnson > On Mon, Jan 19, 2009 at 9:47 PM, Emad Nawfal (???? ????) > wrote: > > > Thanks John for this. Although the decorate-sort-undecorate idiom looks > so > > natural to me now, I don't think I would have found it on my own. I have > > that deja vu effect towards it. > > decorate-sort-undecorate is pretty much obsolete since the key= > parameter was added to sort() in Python 2.4. Since Python 2.5 you can > also use key= with min() and max() so your problem can be solved very > simply and tersely: > > In [1]: words = "man woman children he".split() > > In [2]: min(words, key=len) > Out[2]: 'he' > > Kent > Thank you all for the beautiful solutions. When you say that something is obsolete, what does this mean? Is that just because there is a simpler way, or are there other technical considerations? -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From norman at khine.net Tue Jan 20 13:25:05 2009 From: norman at khine.net (Norman Khine) Date: Tue, 20 Jan 2009 13:25:05 +0100 Subject: [Tutor] creating a sound file from a string In-Reply-To: <1c2a2c590901200403k3a4008d2la504ed9746d0fdcb@mail.gmail.com> References: <49759E43.2020902@khine.net> <1c2a2c590901200403k3a4008d2la504ed9746d0fdcb@mail.gmail.com> Message-ID: <4975C2A1.70403@khine.net> Thanks I am looking at this now. From unix I could run sox so that \$ sox uppercase-a.wav uppercase-b.wav ab.wav this produces a merged uppercase-a.wav uppercase-b.wav perhaps this is a better way, but requires having to execute an external programme. any thoughts? cheers norman Kent Johnson wrote: > On Tue, Jan 20, 2009 at 4:49 AM, Norman Khine wrote: >> does anyone know of a python module which would create a single sound file >> based on the randomly generated string? >> >> i have looked at the python wave module, but if i am not wrong this works >> with one file at the time. > > I think you can do this with the wave module. The code would be > something like this: > > open output file and set number of channels, etc > for each letter of input: > open wave file for the letter > read frames from letter file > write frames to output file > close output file > > Kent > From cbabcock at asciiking.com Tue Jan 20 13:30:18 2009 From: cbabcock at asciiking.com (Chris Babcock) Date: Tue, 20 Jan 2009 05:30:18 -0700 Subject: [Tutor] MySqldb problem In-Reply-To: <20090120111014.59680.qmail@f5mail-237-208.rediffmail.com> References: <20090120111014.59680.qmail@f5mail-237-208.rediffmail.com> Message-ID: <20090120053018.58f9937d@mail.asciiking.com> On 20 Jan 2009 11:10:14 -0000 "Manoj kumar" wrote: > i am a newbie to python programming. i just know basics of the > language. i came across MySqldb. i able to manipulate database with > MySqldb but i wasn't able to add files in database through the lib > MySqldb. Right. Whatever you want to do in the database, you'll have to have a user defined in MySQL with the necessary permissions and have that user configured in your program. Details: Generally, you want to follow the principle of least permissions for security in your app. Almost all database apps need select privileges for their database user. A good many need insert, update and/or delete privileges. Dynamically generated tables aren't sound relational design, so your tables should be created using an administrative user for the database rather than giving the MySQL user defined for your app unnecessary privileges. As long as you're in development and no untrusted users have access to the app, do what you want. Before setting it wild or running it as server, whatever it does, replace the user that you've defined as having "ALL" privilege on the database with one that has only those privileges needed for what the app does. Alternative: Also, MySqldb is the manual way to use a MySQL database. It's fine if you want to generate query strings manually because you know what you're doing and you're sure that your code will never be used with a different database. The problem for a new user is that using MySqldb means learning Python and SQL at the same time to build your app. You aren't learning Python because you're a mental masochist. You're learning Python because it's an easy way to get programs working. A more Pythonic way to work with databases would be to use an Object Relational Mapper like SQLAlchemy. The simple explanation is that the ORM lets you just work with objects in your app instead of generating query strings. This approach also gets you a lot of other features for free like independence from being database specific and protection from SQL injection attacks. Chris -- Thank you everyone! USAK is live on its new connection. So far you have given \$198 towards next quarter. To make a donation, use this link (opens on PayPal): http://tinyurl.com/USAK2009 From norman at khine.net Tue Jan 20 14:12:33 2009 From: norman at khine.net (Norman Khine) Date: Tue, 20 Jan 2009 14:12:33 +0100 Subject: [Tutor] creating a sound file from a string In-Reply-To: <1c2a2c590901200403k3a4008d2la504ed9746d0fdcb@mail.gmail.com> References: <49759E43.2020902@khine.net> <1c2a2c590901200403k3a4008d2la504ed9746d0fdcb@mail.gmail.com> Message-ID: <4975CDC1.9020203@khine.net> Is this a safe way to generate random sound files on a web server? >>> from os import popen >>> merge = popen('sox uppercase-b.wav uppercase-a.wav merge.wav') Thanks Norman Kent Johnson wrote: > On Tue, Jan 20, 2009 at 4:49 AM, Norman Khine wrote: >> does anyone know of a python module which would create a single sound file >> based on the randomly generated string? >> >> i have looked at the python wave module, but if i am not wrong this works >> with one file at the time. > > I think you can do this with the wave module. The code would be > something like this: > > open output file and set number of channels, etc > for each letter of input: > open wave file for the letter > read frames from letter file > write frames to output file > close output file > > Kent > From kent37 at tds.net Tue Jan 20 14:27:56 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 20 Jan 2009 08:27:56 -0500 Subject: [Tutor] Finding the shortest word in a list of words In-Reply-To: <652641e90901200413x64f662bdsb91f04b2ee574ee9@mail.gmail.com> References: <652641e90901191818i43253d11p25db401076b13e81@mail.gmail.com> <5e58f2e40901191831n45ab7d07h558244efeb52dd99@mail.gmail.com> <652641e90901191847m40c1853ibac006364519ad54@mail.gmail.com> <1c2a2c590901200345y2e7ef466s42be9975328363a1@mail.gmail.com> <652641e90901200413x64f662bdsb91f04b2ee574ee9@mail.gmail.com> Message-ID: <1c2a2c590901200527j76c50d8cyb33a71d56ba1b1b5@mail.gmail.com> On Tue, Jan 20, 2009 at 7:13 AM, Emad Nawfal (???? ????) wrote: > 2009/1/20 Kent Johnson >> decorate-sort-undecorate is pretty much obsolete since the key= >> parameter was added to sort() in Python 2.4. > When you say that something is obsolete, what does this mean? Is that just > because there is a simpler way, or are there other technical considerations? In this case, it is because there is a better, simpler way. Decorate-sort-undecorate used to be the recommended way to sort on a key; now key= is preferred. Kent From kent37 at tds.net Tue Jan 20 14:35:11 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 20 Jan 2009 08:35:11 -0500 Subject: [Tutor] creating a sound file from a string In-Reply-To: <4975CDC1.9020203@khine.net> References: <49759E43.2020902@khine.net> <1c2a2c590901200403k3a4008d2la504ed9746d0fdcb@mail.gmail.com> <4975CDC1.9020203@khine.net> Message-ID: <1c2a2c590901200535n624a55b7l12b3391ec4294197@mail.gmail.com> On Tue, Jan 20, 2009 at 8:12 AM, Norman Khine wrote: > Is this a safe way to generate random sound files on a web server? > >>>> from os import popen >>>> merge = popen('sox uppercase-b.wav uppercase-a.wav merge.wav') I'm not sure but you may have to read from merge to allow the process to complete. You might want to use os.system() or one of the subprocess replacements: http://docs.python.org/library/subprocess.html#subprocess-replacements if your webserver allows multiple simultaneous connections, and you are going to serve merge.wav to a client, make sure you use different names for each connection so they don't collide. Kent From lie.1296 at gmail.com Tue Jan 20 14:42:42 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 20 Jan 2009 13:42:42 +0000 (UTC) Subject: [Tutor] Finding the shortest word in a list of words References: <652641e90901191818i43253d11p25db401076b13e81@mail.gmail.com> <5e58f2e40901191831n45ab7d07h558244efeb52dd99@mail.gmail.com> <40af687b0901191913s6f566835h8e518cec7c47d734@mail.gmail.com> Message-ID: On Mon, 19 Jan 2009 19:13:32 -0800, Marc Tompkins wrote: > 2009/1/19 John Fouhy > >> 2009/1/20 Emad Nawfal (???? ????) : Of course, >> this is not necessarily the best answer for your particular problem. >> The problem with sorting is that you have to look at some elements more >> than once. For short lists, it's not a problem, but it can slow you >> down on bigger lists. You could also find the shortest element by >> going through the list, remembering the shortest element you've seen so >> far. This will be quicker if you only want to find the single >> shortest. >> >> > Here's the first thing that came to mind: > Using sys.maxint to prime minLen is overkill, of course - > "antidisestablishmentarianism" is only 28 letters long, after all - but > it should be larger than any word you can expect to see. This doesn't > catch ties, though... could do that like so: Other than overkill, it is wrong. If the shortest "word" is longer than maxint it'd give wrong result. You could just simply use the len of the first word. The best solution though, have been answered by Kent Johnson. From norman at khine.net Tue Jan 20 15:00:09 2009 From: norman at khine.net (Norman Khine) Date: Tue, 20 Jan 2009 15:00:09 +0100 Subject: [Tutor] creating a sound file from a string In-Reply-To: <1c2a2c590901200535n624a55b7l12b3391ec4294197@mail.gmail.com> References: <49759E43.2020902@khine.net> <1c2a2c590901200403k3a4008d2la504ed9746d0fdcb@mail.gmail.com> <4975CDC1.9020203@khine.net> <1c2a2c590901200535n624a55b7l12b3391ec4294197@mail.gmail.com> Message-ID: <4975D8E9.7090704@khine.net> Thanks, Kent Johnson wrote: > On Tue, Jan 20, 2009 at 8:12 AM, Norman Khine wrote: >> Is this a safe way to generate random sound files on a web server? >> >>>>> from os import popen >>>>> merge = popen('sox uppercase-b.wav uppercase-a.wav merge.wav') > > I'm not sure but you may have to read from merge to allow the process > to complete. You might want to use os.system() or one of the > subprocess replacements: > http://docs.python.org/library/subprocess.html#subprocess-replacements How do I check if the process has completed? Would I have to explicitly close the file? > > if your webserver allows multiple simultaneous connections, and you > are going to serve merge.wav to a client, make sure you use different > names for each connection so they don't collide. Each merge.wav file will be unique and only for the specific session, after which it will be removed from the server. > > Kent What I am trying to do is a sound captcha, just to learn in putting the pieces together. Norman > From kent37 at tds.net Tue Jan 20 15:11:34 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 20 Jan 2009 09:11:34 -0500 Subject: [Tutor] creating a sound file from a string In-Reply-To: <4975D8E9.7090704@khine.net> References: <49759E43.2020902@khine.net> <1c2a2c590901200403k3a4008d2la504ed9746d0fdcb@mail.gmail.com> <4975CDC1.9020203@khine.net> <1c2a2c590901200535n624a55b7l12b3391ec4294197@mail.gmail.com> <4975D8E9.7090704@khine.net> Message-ID: <1c2a2c590901200611neea872ew40ddbce272a99076@mail.gmail.com> On Tue, Jan 20, 2009 at 9:00 AM, Norman Khine wrote: >>>>>> from os import popen >>>>>> merge = popen('sox uppercase-b.wav uppercase-a.wav merge.wav') >> >> I'm not sure but you may have to read from merge to allow the process >> to complete. You might want to use os.system() or one of the >> subprocess replacements: >> http://docs.python.org/library/subprocess.html#subprocess-replacements > > How do I check if the process has completed? > > Would I have to explicitly close the file? I suggest something like subprocess.call(['sox', 'uppercase-b.wav', 'uppercase-a.wav', 'merge.wav']) which will wait for the process to complete. sox is responsible for closing the file. Kent From lie.1296 at gmail.com Tue Jan 20 15:18:14 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 20 Jan 2009 14:18:14 +0000 (UTC) Subject: [Tutor] Ip address References: <49748A20.50604@unknownsoftware.ro> <333efb450901190727s261437dbi3cdb8fe55e85b8bb@mail.gmail.com> <386909.88079.qm@web110802.mail.gq1.yahoo.com> Message-ID: On Mon, 19 Jan 2009 19:47:54 -0800, wormwood_3 wrote: > Hello, > > This is definitely possible. It's more a matter of system and OS > configuration than Python though, so you might want to check out some > Linux forums ( http://www.linuxforums.org/ ) for additional help. In > short, I think the simplest would be: Have 3 separate network interfaces > in your physical box, have your router provide one of the three > addresses to each. Then you could configure the client to only connect > through its associated interface/IP. > > If this sort of setup wouldn't work, please tell us more about your > configuration between your client and your network. Definitely not what he expected, I'm sure. It is impossible for a single network interface to have more than 1 IP address. I want to ask what is he going to do with such set up though. It is trivial to emulate IP addressess through ports, so use that instead. Also inter-process communication in a single machine is usually better done using pipes. From ptmcg at austin.rr.com Tue Jan 20 16:33:40 2009 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 20 Jan 2009 09:33:40 -0600 Subject: [Tutor] Finding the shortest word in a list of words In-Reply-To: References: Message-ID: <05B96BA361DD4053A753FD05C17CDB4E@AWA2> "Finding the shortest word among a list of words" sounds like something of a trick question to me. I think a more complete problem statement would be "Find the list of words that are the shortest", since there is no guarantee that the list does not contain two words of the same shortest length. If you just add "me" to your sample set, you now get misleading answers: words = "man woman children he me".split() print min(words, key=len) prints: he What happened to "me"? It is just as short as "he"! To get *all* the words that are the shortest length, I'll show two approaches. The first uses a defaultdict, from the collections module of the Python stdlib. With a defaultdict, I can have new dict entries get initialized with a default value using a specified factory function, without first having to check to see if that entry exists. I would like to create a dict of lists of words, keyed by the lengths of the words. Something that would give me this dict: { 2 : ['he', 'me'], 3 : ['man'], ... etc. } from which I could then find the minimum length using min(wordlendict.keys()). By using a defaultdict, I can just build things up by iterating over the list and adding each word to the entry for the current word's length - if the current word is the first one for this length to be found, the defaultdict will initialize the value to an empty list for me. This allows me to safely append the current word regardless of whether there was an existing entry or not. Here is the code that does this: from collections import defaultdict wordlendict = defaultdict(list) for w in words: wordlendict[len(w)].append(w) minlen = min(wordlendict.keys()) minlist = wordlendict[minlen] print minlist prints: ['he', 'me'] Now we are getting a more complete answer! A second approach uses the groupby method of the itertools module in the stdlib. groupby usually takes me several attempts to get everything right: the input must be sorted by the grouping feature, and then the results returned by groupby are in the form of an iterator that returns key-iterator tuples. I need to go through some mental gymnastics to unwind the data to get the group I'm really interested in. Here is a step-by-step code to use groupby: from itertools import groupby grpsbylen = groupby(sorted(words,key=len),len) mingrp = grpsbylen.next() minlen = mingrp[0] minlist = list(mingrp[1]) print minlist The input list of words gets sorted, and then passed to groupby, which uses len as the grouping criteria (groupby is not inherently aware of how the input list was sorted, so len must be repeated). The first group tuple is pulled from the grpsbylen iterator using next(). The 0'th tuple element is the grouping value - in this case, it is the minimum length 2. The 1'th tuple element is the group itself, given as an iterator. Passing this to the list constructor gives us the list of all the 2-character words, which then gets printed: ['he', 'me'] Again, 'me' no longer gets left out. Maybe this will get you some extra credit... -- Paul From irimia.suleapa at unknownsoftware.ro Tue Jan 20 16:56:18 2009 From: irimia.suleapa at unknownsoftware.ro (Irimia, Suleapa) Date: Tue, 20 Jan 2009 17:56:18 +0200 Subject: [Tutor] Ip address In-Reply-To: <386909.88079.qm@web110802.mail.gq1.yahoo.com> References: <49748A20.50604@unknownsoftware.ro> <333efb450901190727s261437dbi3cdb8fe55e85b8bb@mail.gmail.com> <386909.88079.qm@web110802.mail.gq1.yahoo.com> Message-ID: <4975F422.6080003@unknownsoftware.ro> wormwood_3 wrote: > Hello, > > This is definitely possible. It's more a matter of system and OS > configuration than Python though, so you might want to check out some > Linux forums ( http://www.linuxforums.org/ ) for additional help. In > short, I think the simplest would be: Have 3 separate network interfaces > in your physical box, have your router provide one of the three > addresses to each. Then you could configure the client to only connect > through its associated interface/IP. > > If this sort of setup wouldn't work, please tell us more about your > configuration between your client and your network. > > -Sam > > _______________________ > Samuel Huckins > > Homepage - http://samuelhuckins.com > Tech blog - http://dancingpenguinsoflight.com/ > Photos - http://www.flickr.com/photos/samuelhuckins/ > AIM - samushack | Gtalk - samushack | Skype - shuckins > > It is about Ubuntu 8.04. I have 5 Ip address there (4 aliases). The idea is simple, i want to grab something from internet (website) using this client which was created in python. When the client is running, on the other server i see the first ip address from client server interface. What do i want is to have the possibility to chose or to use another ip from the list. I think Wayne told me the answer, using proxy or i was thinking about socks. But if anyone know anything better than this, i will be glad to hear. Thank you, From emadnawfal at gmail.com Tue Jan 20 17:12:18 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Tue, 20 Jan 2009 11:12:18 -0500 Subject: [Tutor] Finding the shortest word in a list of words In-Reply-To: <05B96BA361DD4053A753FD05C17CDB4E@AWA2> References: <05B96BA361DD4053A753FD05C17CDB4E@AWA2> Message-ID: <652641e90901200812r1c0c0849l40f3cab0c2f95e90@mail.gmail.com> On Tue, Jan 20, 2009 at 10:33 AM, Paul McGuire wrote: > "Finding the shortest word among a list of words" sounds like something of > a > trick question to me. I think a more complete problem statement would be > "Find the list of words that are the shortest", since there is no guarantee > that the list does not contain two words of the same shortest length. If > you just add "me" to your sample set, you now get misleading answers: > > words = "man woman children he me".split() > print min(words, key=len) > > prints: > he > > What happened to "me"? It is just as short as "he"! > > To get *all* the words that are the shortest length, I'll show two > approaches. The first uses a defaultdict, from the collections module of > the Python stdlib. With a defaultdict, I can have new dict entries get > initialized with a default value using a specified factory function, > without > first having to check to see if that entry exists. I would like to create > a > dict of lists of words, keyed by the lengths of the words. Something that > would give me this dict: > > { 2 : ['he', 'me'], 3 : ['man'], ... etc. } > > from which I could then find the minimum length using > min(wordlendict.keys()). By using a defaultdict, I can just build things > up > by iterating over the list and adding each word to the entry for the > current > word's length - if the current word is the first one for this length to be > found, the defaultdict will initialize the value to an empty list for me. > This allows me to safely append the current word regardless of whether > there > was an existing entry or not. Here is the code that does this: > > from collections import defaultdict > wordlendict = defaultdict(list) > for w in words: > wordlendict[len(w)].append(w) > minlen = min(wordlendict.keys()) > minlist = wordlendict[minlen] > print minlist > > prints: > ['he', 'me'] > > Now we are getting a more complete answer! > > A second approach uses the groupby method of the itertools module in the > stdlib. groupby usually takes me several attempts to get everything right: > the input must be sorted by the grouping feature, and then the results > returned by groupby are in the form of an iterator that returns > key-iterator > tuples. I need to go through some mental gymnastics to unwind the data to > get the group I'm really interested in. Here is a step-by-step code to use > groupby: > > from itertools import groupby > grpsbylen = groupby(sorted(words,key=len),len) > mingrp = grpsbylen.next() > minlen = mingrp[0] > minlist = list(mingrp[1]) > print minlist > > The input list of words gets sorted, and then passed to groupby, which uses > len as the grouping criteria (groupby is not inherently aware of how the > input list was sorted, so len must be repeated). The first group tuple is > pulled from the grpsbylen iterator using next(). The 0'th tuple element is > the grouping value - in this case, it is the minimum length 2. The 1'th > tuple element is the group itself, given as an iterator. Passing this to > the list constructor gives us the list of all the 2-character words, which > then gets printed: > ['he', 'me'] > > Again, 'me' no longer gets left out. > > Maybe this will get you some extra credit... > > -- Paul Thank you so much Paul for this. In my original post, I wrote word(s), which means word or words. Your solutions look a little bit too advanced to me. I never used the collections module, and used itertools only once or twice. I will study these solutions for sure, not for extra credit, simply because I'm simply a linguistics person who uses corpora to find information without any official interest in computer science or programming classes. Maybe when I'm good enough at programming, I will take a Python class for credit, although I'm past the classes thing now. Thank you all again for helping me get a better understanding of Python. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From david at abbottdavid.com Tue Jan 20 16:04:51 2009 From: david at abbottdavid.com (David) Date: Tue, 20 Jan 2009 10:04:51 -0500 Subject: [Tutor] MySqldb problem In-Reply-To: <20090120111014.59680.qmail@f5mail-237-208.rediffmail.com> References: <20090120111014.59680.qmail@f5mail-237-208.rediffmail.com> Message-ID: <4975E813.3010402@abbottdavid.com> Manoj kumar wrote: > > > hi all, > > i am a newbie to python programming. i just know basics of the > language. i came across MySqldb. i able to manipulate database with > MySqldb but i wasn't able to add files in database through the lib > MySqldb. > > any help will be welcomed gracefully. > > thanks. > > MANOJ SHEOKAND > > (+919728523528) > > "some day there won't be a song in ur heart, sing anyway" > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > I am new to python also, here are my notes, it helps me understand how it works, may be of some help; http://asterisklinks.com/wiki/doku.php?id=wiki:mysql_fun -david -- powered by Gentoo/GNU Linux http://linuxcrazy.com From lie.1296 at gmail.com Tue Jan 20 17:19:28 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 20 Jan 2009 23:19:28 +0700 Subject: [Tutor] Question about pygame/tkinter interaction In-Reply-To: <4975F5FA.1040708@alchemy.com> References: <4a289b480901142200k3e376eaeg39de1ed8de1e239c@mail.gmail.com> <200901191857.36613.eike.welk@gmx.net> <20090119180522.GA66977@dragon.alchemy.com> <1c2a2c590901191430o561da1a6o952229c05c4afd6f@mail.gmail.com> <20090119234627.GA91182@dragon.alchemy.com> <4975F5FA.1040708@alchemy.com> Message-ID: <1232468368.24572.5.camel@lieryan-laptop> On Tue, 2009-01-20 at 08:04 -0800, Steve Willoughby wrote: > > In this case, that might be enough. I just need to show a video clip > in > an otherwise fairly simple GUI. A decorationless, borderless window > popped up on the screen over the Tk stuff would probably work. Thanks > for the advice, I'll play with this a bit. I've never used decoration-less pygame window, but I suspect it'd be much easier/better to popup a fully decorated window with a separate control panel (like mplayer). I think a lot of problems might arise with decorator-less window, such as minimizing/resizing/moving Tk window doesn't minimize/resize/move pygame's. From norman at khine.net Tue Jan 20 17:30:19 2009 From: norman at khine.net (Norman Khine) Date: Tue, 20 Jan 2009 17:30:19 +0100 Subject: [Tutor] lists Message-ID: <4975FC1B.4050306@khine.net> Hi What am I doing wrong >>> media_list = ['upper_b.wav', 'upper_a.wav'] >>> print '%s' % (for x in media_list) File "", line 1 print '%s' % (for x in media_list) ^ SyntaxError: invalid syntax >>> print '%s' % (x for x in media_list) I want to replace %s with the items of the list as individual item string, i.e 'upper_b.wav', 'upper_a.wav' if I change the list to string I still get one item: "'upper_b.wav', 'upper_a.wav'" thanks norman From kent37 at tds.net Tue Jan 20 18:00:58 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 20 Jan 2009 12:00:58 -0500 Subject: [Tutor] lists In-Reply-To: <4975FC1B.4050306@khine.net> References: <4975FC1B.4050306@khine.net> Message-ID: <1c2a2c590901200900i550fe646if7a8ace4e45a73a3@mail.gmail.com> On Tue, Jan 20, 2009 at 11:30 AM, Norman Khine wrote: > Hi > What am I doing wrong > >>>> media_list = ['upper_b.wav', 'upper_a.wav'] >>>> print '%s' % (for x in media_list) > File "", line 1 > print '%s' % (for x in media_list) > ^ > SyntaxError: invalid syntax >>>> print '%s' % (x for x in media_list) > > > I want to replace %s with the items of the list as individual item string, > i.e > > 'upper_b.wav', 'upper_a.wav' I'm not sure what you want, maybe one of these? In [1]: media_list = ['upper_b.wav', 'upper_a.wav'] In [2]: print ', '.join(media_list) upper_b.wav, upper_a.wav In [3]: print ', '.join(repr(x) for x in media_list) 'upper_b.wav', 'upper_a.wav' Kent From marc.tompkins at gmail.com Tue Jan 20 18:20:22 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 20 Jan 2009 09:20:22 -0800 Subject: [Tutor] Finding the shortest word in a list of words In-Reply-To: References: <652641e90901191818i43253d11p25db401076b13e81@mail.gmail.com> <5e58f2e40901191831n45ab7d07h558244efeb52dd99@mail.gmail.com> <40af687b0901191913s6f566835h8e518cec7c47d734@mail.gmail.com> Message-ID: <40af687b0901200920h2cecdddfma59eb961af61341e@mail.gmail.com> On Tue, Jan 20, 2009 at 5:42 AM, Lie Ryan wrote: > > Using sys.maxint to prime minLen is overkill, of course - > > "antidisestablishmentarianism" is only 28 letters long, after all - but > > it should be larger than any word you can expect to see. This doesn't > > catch ties, though... could do that like so: > > > Other than overkill, it is wrong. If the shortest "word" is longer than > maxint it'd give wrong result. What language do you speak (or machine do you use), where the shortest word in a potential list is longer than maxint? On my machine maxint is 2,147,483,647. That's what I meant by overkill. You could just simply use the len of the first word. True dat. Requires an extra step or two, though - initializing with some impossibly huge number is quick. > The best solution though, have been answered by Kent Johnson. > Extremely terse and elegant, doesn't find ties. def MinKent(corpora=""): > words= corpora.split() > return min(words, key=len) > > print MinKent("No victim has ever been more repressed and alienated than > the truth is") > Output: No Mine returns (2, ['No', 'is'], 9, ['repressed', 'alienated']). I could be wrong - it seemed more like what the OP actually wanted, but he'd be the judge of that. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From tomar.arun at gmail.com Tue Jan 20 18:34:52 2009 From: tomar.arun at gmail.com (Arun Tomar) Date: Tue, 20 Jan 2009 23:04:52 +0530 Subject: [Tutor] lists In-Reply-To: <1c2a2c590901200900i550fe646if7a8ace4e45a73a3@mail.gmail.com> References: <4975FC1B.4050306@khine.net> <1c2a2c590901200900i550fe646if7a8ace4e45a73a3@mail.gmail.com> Message-ID: <202c460901200934u3e73497cq656d9e94de213c05@mail.gmail.com> hi! On Tue, Jan 20, 2009 at 10:30 PM, Kent Johnson wrote: > On Tue, Jan 20, 2009 at 11:30 AM, Norman Khine wrote: >> Hi >> What am I doing wrong >> >>>>> media_list = ['upper_b.wav', 'upper_a.wav'] >>>>> print '%s' % (for x in media_list) >> File "", line 1 >> print '%s' % (for x in media_list) >> ^ >> SyntaxError: invalid syntax >>>>> print '%s' % (x for x in media_list) >> >> >> I want to replace %s with the items of the list as individual item string, >> i.e >> >> 'upper_b.wav', 'upper_a.wav' > > I'm not sure what you want, maybe one of these? > > In [1]: media_list = ['upper_b.wav', 'upper_a.wav'] > > In [2]: print ', '.join(media_list) > upper_b.wav, upper_a.wav > > In [3]: print ', '.join(repr(x) for x in media_list) > 'upper_b.wav', 'upper_a.wav' > > Kent may be you want to do it this way: In [10]: for x in media_list: ....: print "%s" % x ....: ....: upper_b.wav upper_a.wav -- Regards, Arun Tomar blog: http://linuxguy.in website: http://www.solutionenterprises.co.in From norman at khine.net Tue Jan 20 19:02:57 2009 From: norman at khine.net (Norman Khine) Date: Tue, 20 Jan 2009 19:02:57 +0100 Subject: [Tutor] lists In-Reply-To: <1c2a2c590901200900i550fe646if7a8ace4e45a73a3@mail.gmail.com> References: <4975FC1B.4050306@khine.net> <1c2a2c590901200900i550fe646if7a8ace4e45a73a3@mail.gmail.com> Message-ID: <497611D1.2050505@khine.net> Hi, actually what I was trying to do carries from my last post, where my media files are a list that I want to add to the subprocess.call(['sox', ', '.join(media_list), 'list.wav']) >>> print ', '.join(media_list) upper_b.wav, upper_a.wav >>> subprocess.call(['sox', ', '.join(media_list), 'list.wav']) sox formats: can't open input file `upper_b.wav, upper_a.wav': No such file or directory 2 >>> but this is treated as one item, rather than the two. Kent Johnson wrote: > On Tue, Jan 20, 2009 at 11:30 AM, Norman Khine wrote: >> Hi >> What am I doing wrong >> >>>>> media_list = ['upper_b.wav', 'upper_a.wav'] >>>>> print '%s' % (for x in media_list) >> File "", line 1 >> print '%s' % (for x in media_list) >> ^ >> SyntaxError: invalid syntax >>>>> print '%s' % (x for x in media_list) >> >> >> I want to replace %s with the items of the list as individual item string, >> i.e >> >> 'upper_b.wav', 'upper_a.wav' > > I'm not sure what you want, maybe one of these? > > In [1]: media_list = ['upper_b.wav', 'upper_a.wav'] > > In [2]: print ', '.join(media_list) > upper_b.wav, upper_a.wav > > In [3]: print ', '.join(repr(x) for x in media_list) > 'upper_b.wav', 'upper_a.wav' > > Kent > From dbibarra at ucdavis.edu Tue Jan 20 19:04:17 2009 From: dbibarra at ucdavis.edu (Donna Belle Ibarra) Date: Tue, 20 Jan 2009 10:04:17 -0800 Subject: [Tutor] Concerning Programming Exercise #6 of Chapter 2 of Python Programming John Zelle Textbook Message-ID: Hi! I need help with program exericse #6 entitled "Futval.py" which is a program that computes the value of an investment carried 10 years into the future. This is the coding I have.. yet it does not seem to spit out the correct numbers (Am I using an incorrect equation?) *def main(): print "This program calculates the future value" print "of a 10-year investment." principal = input("Enter the amount invested each year: ") apr = input("Enter the annual interest rate: ") years = input("Enter the number of years: ") for i in range (1, years + 1): principal = principal * (1 + apr)**i print "The value in", i, " years is:", principal main()* The output is suppose to appear like this: This program calculates the future value of a 10-year investment. Enter the amount invested each year: 100.00 Enter the annual interst rate: 0.05 Enter the number of years: 10 The value in 1 years is 105.0 The value in 2 years is 215.25 The value in 3 years is 331.0125 The value in 4 years is 452.563125 And so on.. ^Please help me!!! -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Jan 20 19:57:14 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 20 Jan 2009 13:57:14 -0500 Subject: [Tutor] lists In-Reply-To: <497611D1.2050505@khine.net> References: <4975FC1B.4050306@khine.net> <1c2a2c590901200900i550fe646if7a8ace4e45a73a3@mail.gmail.com> <497611D1.2050505@khine.net> Message-ID: <1c2a2c590901201057s2077e5b6y34d6cc2a88e6b853@mail.gmail.com> On Tue, Jan 20, 2009 at 1:02 PM, Norman Khine wrote: > Hi, > actually what I was trying to do carries from my last post, where my media > files are a list that I want to add to the > > subprocess.call(['sox', ', '.join(media_list), 'list.wav']) OK, you want a list, not a string. You can use + to concatenate lists: ['sox'] + media_list + ['list.wav'] or args = ['sox'] args.extend(media_list) args.add('list.wav') Kent From bgailer at gmail.com Tue Jan 20 20:02:52 2009 From: bgailer at gmail.com (bob gailer) Date: Tue, 20 Jan 2009 14:02:52 -0500 Subject: [Tutor] Concerning Programming Exercise #6 of Chapter 2 of Python Programming John Zelle Textbook In-Reply-To: References: Message-ID: <49761FDC.5020800@gmail.com> An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Tue Jan 20 20:23:43 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 20 Jan 2009 19:23:43 +0000 (UTC) Subject: [Tutor] Finding the shortest word in a list of words References: <652641e90901191818i43253d11p25db401076b13e81@mail.gmail.com> <5e58f2e40901191831n45ab7d07h558244efeb52dd99@mail.gmail.com> <40af687b0901191913s6f566835h8e518cec7c47d734@mail.gmail.com> <40af687b0901200920h2cecdddfma59eb961af61341e@mail.gmail.com> Message-ID: On Tue, 20 Jan 2009 09:20:22 -0800, Marc Tompkins wrote: > On Tue, Jan 20, 2009 at 5:42 AM, Lie Ryan wrote: > >> > Using sys.maxint to prime minLen is overkill, of course - >> > "antidisestablishmentarianism" is only 28 letters long, after all - >> > but it should be larger than any word you can expect to see. This >> > doesn't catch ties, though... could do that like so: > >> Other than overkill, it is wrong. If the shortest "word" is longer than >> maxint it'd give wrong result. > > What language do you speak (or machine do you use), where the shortest > word in a potential list is longer than maxint? On my machine maxint is > 2,147,483,647. That's what I meant by overkill. what I meant as wrong is that it is possible that the code would be used for a string that doesn't represent human language, but arbitrary array of bytes. Also, it is a potential security issue. > You could just simply use the len of the first word. > > True dat. Requires an extra step or two, though - initializing with > some impossibly huge number is quick. len() is fast, and it also removes the need to import sys, which actually removes an extra step or two >> The best solution though, have been answered by Kent Johnson. >> > Extremely terse and elegant, doesn't find ties. > Output: No which, at the time of writing, was my impression on the OP's request. > Mine returns (2, ['No', 'is'], 9, ['repressed', 'alienated']). I could > be wrong - it seemed more like what the OP actually wanted, but he'd be > the judge of that. From david at abbottdavid.com Tue Jan 20 20:29:02 2009 From: david at abbottdavid.com (David) Date: Tue, 20 Jan 2009 14:29:02 -0500 Subject: [Tutor] lists In-Reply-To: <497611D1.2050505@khine.net> References: <4975FC1B.4050306@khine.net> <1c2a2c590901200900i550fe646if7a8ace4e45a73a3@mail.gmail.com> <497611D1.2050505@khine.net> Message-ID: <497625FE.6090302@abbottdavid.com> Norman Khine wrote: > Hi, > actually what I was trying to do carries from my last post, where my > media files are a list that I want to add to the > > subprocess.call(['sox', ', '.join(media_list), 'list.wav']) Something like this may work; #!/usr/bin/python import subprocess def play(filename): player = "/usr/bin/sox" fname = "/home/yorname/dir/" + filname subprocess.call([player, fname]) def playall(files): for name in files: play(name) def run(): files =['wav1.wav', 'wav2.wav'] playall(files) run() -- powered by Gentoo/GNU Linux http://linuxcrazy.com From marc.tompkins at gmail.com Tue Jan 20 21:14:36 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 20 Jan 2009 12:14:36 -0800 Subject: [Tutor] Finding the shortest word in a list of words In-Reply-To: References: <652641e90901191818i43253d11p25db401076b13e81@mail.gmail.com> <5e58f2e40901191831n45ab7d07h558244efeb52dd99@mail.gmail.com> <40af687b0901191913s6f566835h8e518cec7c47d734@mail.gmail.com> <40af687b0901200920h2cecdddfma59eb961af61341e@mail.gmail.com> Message-ID: <40af687b0901201214v22cb2aa9v560fe10fbbbac31e@mail.gmail.com> On Tue, Jan 20, 2009 at 11:23 AM, Lie Ryan wrote: > what I meant as wrong is that it is possible that the code would be used > for a string that doesn't represent human language, but arbitrary array > of bytes. Also, it is a potential security issue. This is something I need to know, then - sys.maxint is a potential security issue? How? Should it be avoided? (Guess I'd better get Googling...) > > You could just simply use the len of the first word. > > > > True dat. Requires an extra step or two, though - initializing with > > some impossibly huge number is quick. > > len() is fast, and it also removes the need to import sys, which actually > removes an extra step or two > Unintended consequence - initializing minLen with the length of the first word results in trying to append to a list that doesn't exist yet - so must create minWord and maxWord ahead of time. (Could use try/except... no.) Also - it occurred to me that the input might be sentences, and sentences contain punctuation... I already took the liberty of adding "is" to the end of the OP's signature quotation; now I add a period: > corpus = "No victim has ever been more repressed and alienated than the > truth is." Now "is." has length 3, not 2; probably not what we had in mind. So, new version: > def MinMax(corpus=""): > import string > corpus = "".join( [x for x in corpus if x not in string.punctuation] ) > words = corpus.split() > minLen = len(words[0]) > maxLen = 0 > minWord, maxWord = [],[] > for word in words: > curLen = len(word) > if curLen == minLen: > minWord.append(word) > if curLen == maxLen: > maxWord.append(word) > if curLen > maxLen: > maxWord = [word] > maxLen = curLen > if curLen < minLen: > minWord = [word] > minLen = curLen > return minLen, minWord, maxLen, maxWord > Is there a good/efficient way to do this without importing string? Obviously best to move the import outside the function to minimize redundancy, but any way to avoid it at all? which, at the time of writing, was my impression on the OP's request. > Quote: "I need to find the shortest / longest word(s) in a sequence of words." I'm sure the OP has moved on by now... time I did likewise. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From emadnawfal at gmail.com Tue Jan 20 22:08:00 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Tue, 20 Jan 2009 16:08:00 -0500 Subject: [Tutor] Finding the shortest word in a list of words In-Reply-To: <40af687b0901201214v22cb2aa9v560fe10fbbbac31e@mail.gmail.com> References: <652641e90901191818i43253d11p25db401076b13e81@mail.gmail.com> <5e58f2e40901191831n45ab7d07h558244efeb52dd99@mail.gmail.com> <40af687b0901191913s6f566835h8e518cec7c47d734@mail.gmail.com> <40af687b0901200920h2cecdddfma59eb961af61341e@mail.gmail.com> <40af687b0901201214v22cb2aa9v560fe10fbbbac31e@mail.gmail.com> Message-ID: <652641e90901201308w1f9102bap12edfe1d1f69850f@mail.gmail.com> On Tue, Jan 20, 2009 at 3:14 PM, Marc Tompkins wrote: > On Tue, Jan 20, 2009 at 11:23 AM, Lie Ryan wrote: > >> what I meant as wrong is that it is possible that the code would be used >> for a string that doesn't represent human language, but arbitrary array >> of bytes. Also, it is a potential security issue. > > > This is something I need to know, then - sys.maxint is a potential security > issue? How? Should it be avoided? (Guess I'd better get Googling...) > > >> > You could just simply use the len of the first word. >> > >> > True dat. Requires an extra step or two, though - initializing with >> > some impossibly huge number is quick. >> >> len() is fast, and it also removes the need to import sys, which actually >> removes an extra step or two >> > Unintended consequence - initializing minLen with the length of the first > word results in trying to append to a list that doesn't exist yet - so must > create minWord and maxWord ahead of time. (Could use try/except... no.) > Also - it occurred to me that the input might be sentences, and sentences > contain punctuation... I already took the liberty of adding "is" to the end > of the OP's signature quotation; now I add a period: > >> corpus = "No victim has ever been more repressed and alienated than the >> truth is." > > Now "is." has length 3, not 2; probably not what we had in mind. > So, new version: > > >> def MinMax(corpus=""): >> import string >> corpus = "".join( [x for x in corpus if x not in string.punctuation] ) >> words = corpus.split() >> minLen = len(words[0]) >> maxLen = 0 >> minWord, maxWord = [],[] >> for word in words: >> curLen = len(word) >> if curLen == minLen: >> minWord.append(word) >> if curLen == maxLen: >> maxWord.append(word) >> if curLen > maxLen: >> maxWord = [word] >> maxLen = curLen >> if curLen < minLen: >> minWord = [word] >> minLen = curLen >> return minLen, minWord, maxLen, maxWord >> > > Is there a good/efficient way to do this without importing string? > Obviously best to move the import outside the function to minimize > redundancy, but any way to avoid it at all? > > > which, at the time of writing, was my impression on the OP's request. >> > > Quote: "I need to find the shortest / longest word(s) in a sequence of > words." > > I'm sure the OP has moved on by now... time I did likewise. > -- > www.fsrtechnologies.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > Yes, I have moved on. I got what i needed . I have nonetheless been following your advanced discussion trying to understand what you're saying. Have not done this fully yet As far as punctuation is concerned, I separate the punctuation marks from the text before I find for the shortest / longest words. I'm working with two agglutinative languages (Swahili and Arabic), and I wanted to see how much agglutination there could be in both languages. Thank you all for your help -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From metolone+gmane at gmail.com Wed Jan 21 04:18:11 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Tue, 20 Jan 2009 19:18:11 -0800 Subject: [Tutor] Concerning Programming Exercise #6 of Chapter 2 of Python Programming John Zelle Textbook References: <49761FDC.5020800@gmail.com> Message-ID: Since you are updating the principal value each year, use the following to grow the principal by the interest rate each year: principal = principal * (1 + apr) -Mark "bob gailer" wrote in message news:49761FDC.5020800 at gmail.com... Donna Belle Ibarra wrote: Hi! I need help with program exericse #6 entitled "Futval.py" which is a program that computes the value of an investment carried 10 years into the future. This is the coding I have.. yet it does not seem to spit out the correct numbers (Am I using an incorrect equation?) Take a look at http://en.wikipedia.org/wiki/Time_value_of_money#Present_value_of_a_future_sum for the various formulas. I am not sure which applies in your case. def main(): print "This program calculates the future value" print "of a 10-year investment." principal = input("Enter the amount invested each year: ") apr = input("Enter the annual interest rate: ") years = input("Enter the number of years: ") for i in range (1, years + 1): principal = principal * (1 + apr)**i print "The value in", i, " years is:", principal main() The output is suppose to appear like this: This program calculates the future value of a 10-year investment. Enter the amount invested each year: 100.00 Enter the annual interst rate: 0.05 Enter the number of years: 10 The value in 1 years is 105.0 The value in 2 years is 215.25 The value in 3 years is 331.0125 The value in 4 years is 452.563125 And so on.. ^Please help me!!! ---------------------------------------------------------------------------- _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -- Bob Gailer Chapel Hill NC 919-636-4239 ------------------------------------------------------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From bermanrl at cfl.rr.com Wed Jan 21 14:33:50 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Wed, 21 Jan 2009 08:33:50 -0500 Subject: [Tutor] The better Python approach Message-ID: <4977243E.4010507@cfl.rr.com> Good Morning, Given a string consisting of numbers separated by spaces such as '1234 5678 1 233 476'. I can see I have two obvious choices to extract or parse out the numbers. The first relying on iteration so that as I search for a blank, I build a substring of all characters found before the space and then, once the space is found, I can then use the int(n) function to determine the number. From my C++ background, that is the approach that seems not only most natural but also most efficient......but....the rules of Python are different and I easily see that I can also search for the first blank, then using the character count, I can use the slice operation to get the characters. Of even further interest I see a string built-in function called split which, I think, will return all the distinct character sub strings for me. My question is what is the most correct python oriented solution for extracting those substrings? Thanks, Robert Berman From jadrifter at gmail.com Wed Jan 21 14:40:00 2009 From: jadrifter at gmail.com (jadrifter) Date: Wed, 21 Jan 2009 05:40:00 -0800 Subject: [Tutor] The better Python approach In-Reply-To: <4977243E.4010507@cfl.rr.com> References: <4977243E.4010507@cfl.rr.com> Message-ID: <1232545201.6121.3.camel@ltop> >>>a = '1234 5678 1 233 476' >>>a.split() ['1234', '5678', '1', '233', '476'] Where the '>>>' are the command prompt from python. Don't type those. A space is the default split delimiter. If you wish to use a '-' or new line feed them as strings to the split method. John On Wed, 2009-01-21 at 08:33 -0500, Robert Berman wrote: > Good Morning, > > Given a string consisting of numbers separated by spaces such as '1234 > 5678 1 233 476'. I can see I have two obvious choices to extract or > parse out the numbers. The first relying on iteration so that as I > search for a blank, I build a substring of all characters found before > the space and then, once the space is found, I can then use the int(n) > function to determine the number. From my C++ background, that is the > approach that seems not only most natural but also most > efficient......but....the rules of Python are different and I easily see > that I can also search for the first blank, then using the character > count, I can use the slice operation to get the characters. Of even > further interest I see a string built-in function called split which, I > think, will return all the distinct character sub strings for me. > > My question is what is the most correct python oriented solution for > extracting those substrings? > > Thanks, > > > Robert Berman > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From mail at timgolden.me.uk Wed Jan 21 14:40:15 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 21 Jan 2009 13:40:15 +0000 Subject: [Tutor] The better Python approach In-Reply-To: <4977243E.4010507@cfl.rr.com> References: <4977243E.4010507@cfl.rr.com> Message-ID: <497725BF.9060501@timgolden.me.uk> Robert Berman wrote: > Given a string consisting of numbers separated by spaces such as '1234 > 5678 1 233 476'. I can see I have two obvious choices to extract or > parse out the numbers. The first relying on iteration so that as I > search for a blank, I build a substring of all characters found before > the space and then, once the space is found, I can then use the int(n) > function to determine the number. From my C++ background, that is the > approach that seems not only most natural but also most > efficient......but....the rules of Python are different and I easily see > that I can also search for the first blank, then using the character > count, I can use the slice operation to get the characters. Of even > further interest I see a string built-in function called split which, I > think, will return all the distinct character sub strings for me. > > My question is what is the most correct python oriented solution for > extracting those substrings? Correct? I don't know. Working; try this: ``` s = '1234 5678 1 233 476' nums = [int (i) for i in s.split ()] print nums ``` If you had some more sophisticated need (he says, inventing requirements as he goes along) such as pulling the numbers out of a string of mixed numbers and letters, you could use a regular expression: ``` import re s = '1234 abc 5678 *** 1 233 xyz 476' nums = [int (i) for i in re.findall ("\d+", s)] print nums ``` TJG From bermanrl at cfl.rr.com Wed Jan 21 14:50:29 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Wed, 21 Jan 2009 08:50:29 -0500 Subject: [Tutor] The better Python approach In-Reply-To: <497725BF.9060501@timgolden.me.uk> References: <4977243E.4010507@cfl.rr.com> <497725BF.9060501@timgolden.me.uk> Message-ID: <49772825.5060000@cfl.rr.com> An HTML attachment was scrubbed... URL: From teachv at taconic.net Wed Jan 21 14:59:08 2009 From: teachv at taconic.net (Vince Teachout) Date: Wed, 21 Jan 2009 08:59:08 -0500 Subject: [Tutor] The better Python approach In-Reply-To: <1232545201.6121.3.camel@ltop> References: <4977243E.4010507@cfl.rr.com> <1232545201.6121.3.camel@ltop> Message-ID: <49772A2C.6010107@taconic.net> jadrifter wrote: >>>> a = '1234 5678 1 233 476' >>>> a.split() > ['1234', '5678', '1', '233', '476'] > > Where the '>>>' are the command prompt from python. Don't type those. > A space is the default split delimiter. If you wish to use a '-' or new > line feed them as strings to the split method. > Ok, that's it. That was the last straw. I'm digging up my copy of "Dive into Python" and starting today! From alan.gauld at btinternet.com Wed Jan 21 15:44:18 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 21 Jan 2009 14:44:18 -0000 Subject: [Tutor] The better Python approach References: <4977243E.4010507@cfl.rr.com> <497725BF.9060501@timgolden.me.uk> <49772825.5060000@cfl.rr.com> Message-ID: "Robert Berman" wrote > Perhaps i should not have said the most Python correct. > It looks as if it may well be the approach using the least > amount of work the interpreter must complete. That's generally true. Python can always do things the long way but its generally more efficient both in programmer time and performance speed to use the built-in functions/methods as much as possible. Most of them are written in C after all! Alan G From andreas at kostyrka.org Wed Jan 21 18:29:03 2009 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Wed, 21 Jan 2009 18:29:03 +0100 Subject: [Tutor] The better Python approach In-Reply-To: <1232545201.6121.3.camel@ltop> References: <4977243E.4010507@cfl.rr.com> <1232545201.6121.3.camel@ltop> Message-ID: <20090121182903.0602ac78@andi-lap> Am Wed, 21 Jan 2009 05:40:00 -0800 schrieb jadrifter : > >>>a = '1234 5678 1 233 476' > >>>a.split() > ['1234', '5678', '1', '233', '476'] [int(x) for x in a.split()] # [1234, 5678, 1, 233, 476] Andreas From andreas at kostyrka.org Wed Jan 21 18:39:57 2009 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Wed, 21 Jan 2009 18:39:57 +0100 Subject: [Tutor] Finding the shortest word in a list of words In-Reply-To: <05B96BA361DD4053A753FD05C17CDB4E@AWA2> References: <05B96BA361DD4053A753FD05C17CDB4E@AWA2> Message-ID: <20090121183957.3b8b093b@andi-lap> Am Tue, 20 Jan 2009 09:33:40 -0600 schrieb "Paul McGuire" : No need for a defaultdict, all dicts have a setdefault method that works fine for this assign an empty dict/list as starting point problem: wordlendict = {} for w in words: wordlendict.setdefault(len(w), []).append(w) try: minlen, minlist = min(wordlendict.items()) except ValueError: minlen = 0 minlist = [] Andreas > from collections import defaultdict > wordlendict = defaultdict(list) > for w in words: > wordlendict[len(w)].append(w) > minlen = min(wordlendict.keys()) > minlist = wordlendict[minlen] > print minlist > > prints: > ['he', 'me'] > > Now we are getting a more complete answer! > > A second approach uses the groupby method of the itertools module in > the stdlib. groupby usually takes me several attempts to get > everything right: the input must be sorted by the grouping feature, > and then the results returned by groupby are in the form of an > iterator that returns key-iterator tuples. I need to go through some > mental gymnastics to unwind the data to get the group I'm really > interested in. Here is a step-by-step code to use groupby: > > from itertools import groupby > grpsbylen = groupby(sorted(words,key=len),len) > mingrp = grpsbylen.next() > minlen = mingrp[0] > minlist = list(mingrp[1]) > print minlist > > The input list of words gets sorted, and then passed to groupby, > which uses len as the grouping criteria (groupby is not inherently > aware of how the input list was sorted, so len must be repeated). > The first group tuple is pulled from the grpsbylen iterator using > next(). The 0'th tuple element is the grouping value - in this case, > it is the minimum length 2. The 1'th tuple element is the group > itself, given as an iterator. Passing this to the list constructor > gives us the list of all the 2-character words, which then gets > printed: ['he', 'me'] > > Again, 'me' no longer gets left out. > > Maybe this will get you some extra credit... > > -- Paul > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From ptmcg at austin.rr.com Wed Jan 21 19:45:34 2009 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 21 Jan 2009 12:45:34 -0600 Subject: [Tutor] Tutor Digest, Vol 59, Issue 109 In-Reply-To: References: Message-ID: -----Original Message----- From: tutor-bounces+ptmcg=austin.rr.com at python.org [mailto:tutor-bounces+ptmcg=austin.rr.com at python.org] On Behalf Of tutor-request at python.org Sent: Wednesday, January 21, 2009 11:29 AM To: tutor at python.org Subject: Tutor Digest, Vol 59, Issue 109 Send Tutor mailing list submissions to tutor at python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/tutor or, via email, send a message with subject or body 'help' to tutor-request at python.org You can reach the person managing the list at tutor-owner at python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Tutor digest..." Today's Topics: 1. The better Python approach (Robert Berman) 2. Re: The better Python approach (jadrifter) 3. Re: The better Python approach (Tim Golden) 4. Re: The better Python approach (Robert Berman) 5. Re: The better Python approach (Vince Teachout) 6. Re: The better Python approach (Alan Gauld) 7. Re: The better Python approach (Andreas Kostyrka) ---------------------------------------------------------------------- Message: 1 Date: Wed, 21 Jan 2009 08:33:50 -0500 From: Robert Berman Subject: [Tutor] The better Python approach To: Tutor at python.org Message-ID: <4977243E.4010507 at cfl.rr.com> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Good Morning, Given a string consisting of numbers separated by spaces such as '1234 5678 1 233 476'. I can see I have two obvious choices to extract or parse out the numbers. The first relying on iteration so that as I search for a blank, I build a substring of all characters found before the space and then, once the space is found, I can then use the int(n) function to determine the number. From my C++ background, that is the approach that seems not only most natural but also most efficient......but....the rules of Python are different and I easily see that I can also search for the first blank, then using the character count, I can use the slice operation to get the characters. Of even further interest I see a string built-in function called split which, I think, will return all the distinct character sub strings for me. My question is what is the most correct python oriented solution for extracting those substrings? Thanks, Robert Berman ------------------------------ Message: 2 Date: Wed, 21 Jan 2009 05:40:00 -0800 From: jadrifter Subject: Re: [Tutor] The better Python approach To: Robert Berman Cc: Tutor at python.org Message-ID: <1232545201.6121.3.camel at ltop> Content-Type: text/plain >>>a = '1234 5678 1 233 476' >>>a.split() ['1234', '5678', '1', '233', '476'] Where the '>>>' are the command prompt from python. Don't type those. A space is the default split delimiter. If you wish to use a '-' or new line feed them as strings to the split method. John On Wed, 2009-01-21 at 08:33 -0500, Robert Berman wrote: > Good Morning, > > Given a string consisting of numbers separated by spaces such as '1234 > 5678 1 233 476'. I can see I have two obvious choices to extract or > parse out the numbers. The first relying on iteration so that as I > search for a blank, I build a substring of all characters found before > the space and then, once the space is found, I can then use the int(n) > function to determine the number. From my C++ background, that is the > approach that seems not only most natural but also most > efficient......but....the rules of Python are different and I easily > see that I can also search for the first blank, then using the > character count, I can use the slice operation to get the characters. > Of even further interest I see a string built-in function called split > which, I think, will return all the distinct character sub strings for me. > > My question is what is the most correct python oriented solution for > extracting those substrings? > > Thanks, > > > Robert Berman > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor ------------------------------ Message: 3 Date: Wed, 21 Jan 2009 13:40:15 +0000 From: Tim Golden Subject: Re: [Tutor] The better Python approach Cc: Tutor at python.org Message-ID: <497725BF.9060501 at timgolden.me.uk> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Robert Berman wrote: > Given a string consisting of numbers separated by spaces such as '1234 > 5678 1 233 476'. I can see I have two obvious choices to extract or > parse out the numbers. The first relying on iteration so that as I > search for a blank, I build a substring of all characters found before > the space and then, once the space is found, I can then use the int(n) > function to determine the number. From my C++ background, that is the > approach that seems not only most natural but also most > efficient......but....the rules of Python are different and I easily > see that I can also search for the first blank, then using the > character count, I can use the slice operation to get the characters. > Of even further interest I see a string built-in function called split > which, I think, will return all the distinct character sub strings for me. > > My question is what is the most correct python oriented solution for > extracting those substrings? Correct? I don't know. Working; try this: ``` s = '1234 5678 1 233 476' nums = [int (i) for i in s.split ()] print nums ``` If you had some more sophisticated need (he says, inventing requirements as he goes along) such as pulling the numbers out of a string of mixed numbers and letters, you could use a regular expression: ``` import re s = '1234 abc 5678 *** 1 233 xyz 476' nums = [int (i) for i in re.findall ("\d+", s)] print nums ``` TJG ------------------------------ Message: 4 Date: Wed, 21 Jan 2009 08:50:29 -0500 From: Robert Berman Subject: Re: [Tutor] The better Python approach To: Tutor at python.org Message-ID: <49772825.5060000 at cfl.rr.com> Content-Type: text/plain; charset="us-ascii" An HTML attachment was scrubbed... URL: ------------------------------ Message: 5 Date: Wed, 21 Jan 2009 08:59:08 -0500 From: Vince Teachout Subject: Re: [Tutor] The better Python approach To: Tutor at python.org Message-ID: <49772A2C.6010107 at taconic.net> Content-Type: text/plain; charset=ISO-8859-1; format=flowed jadrifter wrote: >>>> a = '1234 5678 1 233 476' >>>> a.split() > ['1234', '5678', '1', '233', '476'] > > Where the '>>>' are the command prompt from python. Don't type those. > A space is the default split delimiter. If you wish to use a '-' or > new line feed them as strings to the split method. > Ok, that's it. That was the last straw. I'm digging up my copy of "Dive into Python" and starting today! ------------------------------ Message: 6 Date: Wed, 21 Jan 2009 14:44:18 -0000 From: "Alan Gauld" Subject: Re: [Tutor] The better Python approach To: tutor at python.org Message-ID: Content-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=original "Robert Berman" wrote > Perhaps i should not have said the most Python correct. > It looks as if it may well be the approach using the least > amount of work the interpreter must complete. That's generally true. Python can always do things the long way but its generally more efficient both in programmer time and performance speed to use the built-in functions/methods as much as possible. Most of them are written in C after all! Alan G ------------------------------ Message: 7 Date: Wed, 21 Jan 2009 18:29:03 +0100 From: Andreas Kostyrka Subject: Re: [Tutor] The better Python approach To: jadrifter at gmail.com Cc: Tutor at python.org Message-ID: <20090121182903.0602ac78 at andi-lap> Content-Type: text/plain; charset=US-ASCII Am Wed, 21 Jan 2009 05:40:00 -0800 schrieb jadrifter : > >>>a = '1234 5678 1 233 476' > >>>a.split() > ['1234', '5678', '1', '233', '476'] [int(x) for x in a.split()] # [1234, 5678, 1, 233, 476] Andreas ------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor End of Tutor Digest, Vol 59, Issue 109 ************************************** From bermanrl at cfl.rr.com Wed Jan 21 20:02:01 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Wed, 21 Jan 2009 14:02:01 -0500 Subject: [Tutor] The better Python approach In-Reply-To: References: <4977243E.4010507@cfl.rr.com> <497725BF.9060501@timgolden.me.uk> <49772825.5060000@cfl.rr.com> Message-ID: <49777129.7060709@cfl.rr.com> Alan, Thank you for the clarification. Using that as my guide, I revamped my solution to this small challenge and attempted to make the script as concise as possible. The challenge is at the Challenge-You web page, http://www.challenge-you.com/challenge?id=61 I am relatively certain I could have made it more concise with some more detailed examination. If there are some obvious glaring deficiencies, please, anyone feel free to comment. Thanks, Robert Berman #!/usr/bin/env python #findsum.py import string def openinput(thepath = '/home/bermanrl/usbdirbig/Challenges/sum.txt'): ''' Opens text file ''' try: infile = open(thepath, 'r') except: print 'Open file failure.' return infile def runprocess(): '''Reads file and passes string to parsing function ''' bigtotal = 0 myfile = openinput() for line in myfile: jlist = line.split() for x in jlist: bigtotal += int(x) print bigtotal return if __name__ == '__main__': runprocess() Alan Gauld wrote: > > "Robert Berman" wrote > >> Perhaps i should not have said the most Python correct. >> It looks as if it may well be the approach using the least >> amount of work the interpreter must complete. > > That's generally true. Python can always do things the long way but its > generally more efficient both in programmer time and performance > speed to use the built-in functions/methods as much as possible. > Most of them are written in C after all! > > Alan G > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Wed Jan 21 20:47:36 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 21 Jan 2009 14:47:36 -0500 Subject: [Tutor] The better Python approach In-Reply-To: <49777129.7060709@cfl.rr.com> References: <4977243E.4010507@cfl.rr.com> <497725BF.9060501@timgolden.me.uk> <49772825.5060000@cfl.rr.com> <49777129.7060709@cfl.rr.com> Message-ID: <1c2a2c590901211147v3e62eaf5kab9e25614888a058@mail.gmail.com> On Wed, Jan 21, 2009 at 2:02 PM, Robert Berman wrote: > myfile = openinput() > for line in myfile: > jlist = line.split() > for x in jlist: > bigtotal += int(x) Python has a sum() function that sums the elements of a numeric sequence, so the inner loop can be written as bigtotal += sum(int(x) for x in line.split()) But this is just summing another sequence - the line sums - so the whole thing can be written as bigtotal = sum(sum(int(x) for x in line.split()) for line in myfile) or more simply as a single sum over a double loop: bigtotal = sum(int(x) for line in myfile for x in line.split()) which you may or may not see as an improvement... Kent From bermanrl at cfl.rr.com Wed Jan 21 21:42:04 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Wed, 21 Jan 2009 15:42:04 -0500 Subject: [Tutor] The better Python approach In-Reply-To: <1c2a2c590901211147v3e62eaf5kab9e25614888a058@mail.gmail.com> References: <4977243E.4010507@cfl.rr.com> <497725BF.9060501@timgolden.me.uk> <49772825.5060000@cfl.rr.com> <49777129.7060709@cfl.rr.com> <1c2a2c590901211147v3e62eaf5kab9e25614888a058@mail.gmail.com> Message-ID: <4977889C.9020703@cfl.rr.com> An HTML attachment was scrubbed... URL: From david at abbottdavid.com Wed Jan 21 23:29:19 2009 From: david at abbottdavid.com (David) Date: Wed, 21 Jan 2009 17:29:19 -0500 Subject: [Tutor] bruteforce match word in text file Message-ID: <4977A1BF.5040801@abbottdavid.com> I have to ask for a pointer, not sure what I am doing wrong. thanks -david #!/usr/bin/python password = 'loser' wordlist = '/home/david/Challenge-You/wordlist.txt' try: words = open(wordlist, 'r').readlines() except IOError, e: print "Sorry no words" for word in words: word = word.replace("\n","") if password in word: print word else: print 'You are a loser' -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From bgailer at gmail.com Wed Jan 21 23:41:50 2009 From: bgailer at gmail.com (bob gailer) Date: Wed, 21 Jan 2009 17:41:50 -0500 Subject: [Tutor] bruteforce match word in text file In-Reply-To: <4977A1BF.5040801@abbottdavid.com> References: <4977A1BF.5040801@abbottdavid.com> Message-ID: <4977A4AE.30403@gmail.com> David wrote: > I have to ask for a pointer, not sure what I am doing wrong. The first thing you are doing "wrong" is failing to tell us what is in the wordlist file and what results you get when you run the program. Please re-post with that information. > > #!/usr/bin/python > password = 'loser' > wordlist = '/home/david/Challenge-You/wordlist.txt' > try: > words = open(wordlist, 'r').readlines() > except IOError, e: > print "Sorry no words" > for word in words: > word = word.replace("\n","") > if password in word: > print word > else: > print 'You are a loser' > -- Bob Gailer Chapel Hill NC 919-636-4239 From david at abbottdavid.com Wed Jan 21 23:52:05 2009 From: david at abbottdavid.com (David) Date: Wed, 21 Jan 2009 17:52:05 -0500 Subject: [Tutor] bruteforce match word in text file In-Reply-To: <4977A4AE.30403@gmail.com> References: <4977A1BF.5040801@abbottdavid.com> <4977A4AE.30403@gmail.com> Message-ID: <4977A715.4020601@abbottdavid.com> bob gailer wrote: > David wrote: >> I have to ask for a pointer, not sure what I am doing wrong. > > The first thing you are doing "wrong" is failing to tell us what is in > the wordlist file and what results you get when you run the program. > > Please re-post with that information. >> >> #!/usr/bin/python >> password = 'loser' >> wordlist = '/home/david/Challenge-You/wordlist.txt' >> try: >> words = open(wordlist, 'r').readlines() >> except IOError, e: >> print "Sorry no words" >> for word in words: >> word = word.replace("\n","") >> if password in word: >> print word >> else: >> print 'You are a loser' >> > > wordlist.txt next block is the meat the script will go through the list of words create our form with information encode that form and then apply that loser get source added comments above each line to help you understand results; ./py_bruteforce.py next block is the meat the script will go through the list of words create our form with information encode that form and then apply that loser get source added comments above each line to help you understand You are a loser -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From bgailer at gmail.com Thu Jan 22 00:00:51 2009 From: bgailer at gmail.com (bob gailer) Date: Wed, 21 Jan 2009 18:00:51 -0500 Subject: [Tutor] bruteforce match word in text file In-Reply-To: <4977A715.4020601@abbottdavid.com> References: <4977A1BF.5040801@abbottdavid.com> <4977A4AE.30403@gmail.com> <4977A715.4020601@abbottdavid.com> Message-ID: <4977A923.4090403@gmail.com> David wrote: > bob gailer wrote: >> David wrote: >>> I have to ask for a pointer, not sure what I am doing wrong. >> >> The first thing you are doing "wrong" is failing to tell us what is >> in the wordlist file and what results you get when you run the program. >> >> Please re-post with that information. >>> >>> #!/usr/bin/python >>> password = 'loser' >>> wordlist = '/home/david/Challenge-You/wordlist.txt' >>> try: >>> words = open(wordlist, 'r').readlines() >>> except IOError, e: >>> print "Sorry no words" >>> for word in words: >>> word = word.replace("\n","") >>> if password in word: >>> print word >>> else: >>> print 'You are a loser' >>> >> >> > wordlist.txt > > next block is the meat the script will go through the list of words > create our form with information encode that form and then apply that > loser get source added comments above each line to help you understand > > results; > > ./py_bruteforce.py > next block is the meat the script will go through the list of words > create our form with information encode that form and then apply that > loser get source added comments above each line to help you understand > You are a loser > Thank you. Please always post the relevant information, and if you get an exception, post the full traceback. It looks like the file contains 1 line. So the for statement will put that line in word. 'loser' is in word so the print statement prints the line. The program is working as written. Now what can you change to get it to do what (I assume) you want - examine each "word" in the file, print the word if 'loser' is in it, and print 'You are a loser' ONLY if no words match. -- Bob Gailer Chapel Hill NC 919-636-4239 From alan.gauld at btinternet.com Thu Jan 22 00:25:18 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 21 Jan 2009 23:25:18 -0000 Subject: [Tutor] The better Python approach References: <4977243E.4010507@cfl.rr.com> <497725BF.9060501@timgolden.me.uk> <49772825.5060000@cfl.rr.com> <49777129.7060709@cfl.rr.com><1c2a2c590901211147v3e62eaf5kab9e25614888a058@mail.gmail.com> <4977889C.9020703@cfl.rr.com> Message-ID: "Robert Berman" wrote > Wow! That is all worth knowing. I am fascinated by the single sum > over a double loop. > > > or more simply as a single sum over a double loop: > > bigtotal = sum(int(x) for line in myfile for x in line.split()) > > > which you may or may not see as an improvement... And that nicely illustrates the caveat with using the most concise form. You have to make a judgement about when it becomes too concise to be readable and therefore maintainable. Personally I prefer the double loop to the double sum, but in practice I'd probably have been happy to stick with the outer for loop and only one sum() call inside that. But that uis where taste comes into programming, there is no absolute correct form - which takes us back to your original post! :-) -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From david at abbottdavid.com Thu Jan 22 01:01:36 2009 From: david at abbottdavid.com (David) Date: Wed, 21 Jan 2009 19:01:36 -0500 Subject: [Tutor] bruteforce match word in text file In-Reply-To: <4977A923.4090403@gmail.com> References: <4977A1BF.5040801@abbottdavid.com> <4977A4AE.30403@gmail.com> <4977A715.4020601@abbottdavid.com> <4977A923.4090403@gmail.com> Message-ID: <4977B760.3020601@abbottdavid.com> bob gailer wrote: > David wrote: >> bob gailer wrote: >>> David wrote: >>>> I have to ask for a pointer, not sure what I am doing wrong. >>> >>> The first thing you are doing "wrong" is failing to tell us what is >>> in the wordlist file and what results you get when you run the program. >>> >>> Please re-post with that information. >>>> >>>> #!/usr/bin/python >>>> password = 'loser' >>>> wordlist = '/home/david/Challenge-You/wordlist.txt' >>>> try: >>>> words = open(wordlist, 'r').readlines() >>>> except IOError, e: >>>> print "Sorry no words" >>>> for word in words: >>>> word = word.replace("\n","") >>>> if password in word: >>>> print word >>>> else: >>>> print 'You are a loser' > > Now what can you change to get it to do what (I assume) you want - > examine each "word" in the file, print the word if 'loser' is in it, and > print 'You are a loser' ONLY if no words match. > Thanks Bob, I changed the wordlist.txt to next block is meat and the program; #!/usr/bin/python import re password = 'loser' wordlist = '/home/david/Challenge-You/wordlist.txt' try: words = open(wordlist, 'r').readlines() except IOError, e: print "Sorry no words" for word in words: word = word.replace("\n","") if password in word: print "The password is: ", word else: pass I could not figure out how to split the file into words. -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From david at abbottdavid.com Thu Jan 22 01:09:14 2009 From: david at abbottdavid.com (David) Date: Wed, 21 Jan 2009 19:09:14 -0500 Subject: [Tutor] bruteforce match word in text file In-Reply-To: <4977B760.3020601@abbottdavid.com> References: <4977A1BF.5040801@abbottdavid.com> <4977A4AE.30403@gmail.com> <4977A715.4020601@abbottdavid.com> <4977A923.4090403@gmail.com> <4977B760.3020601@abbottdavid.com> Message-ID: <4977B92A.3000008@abbottdavid.com> > #!/usr/bin/python > import re > password = 'loser' > wordlist = '/home/david/Challenge-You/wordlist.txt' > try: > words = open(wordlist, 'r').readlines() > except IOError, e: > print "Sorry no words" > for word in words: > word = word.replace("\n","") > if password in word: > print "The password is: ", word > else: > pass > > I could not figure out how to split the file into words. > > I removed the import re as that was left over from my experimenting. -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From bgailer at gmail.com Thu Jan 22 02:19:03 2009 From: bgailer at gmail.com (bob gailer) Date: Wed, 21 Jan 2009 20:19:03 -0500 Subject: [Tutor] bruteforce match word in text file In-Reply-To: <4977B760.3020601@abbottdavid.com> References: <4977A1BF.5040801@abbottdavid.com> <4977A4AE.30403@gmail.com> <4977A715.4020601@abbottdavid.com> <4977A923.4090403@gmail.com> <4977B760.3020601@abbottdavid.com> Message-ID: <4977C987.7080809@gmail.com> David wrote: > > Thanks Bob, > I changed the wordlist.txt to > next > block > is > meat > > and the program; > > #!/usr/bin/python > password = 'loser' > wordlist = '/home/david/Challenge-You/wordlist.txt' > try: > words = open(wordlist, 'r').readlines() > except IOError, e: > print "Sorry no words" > for word in words: > word = word.replace("\n","") > if password in word: > print "The password is: ", word > else: > pass Good work! > > I could not figure out how to split the file into words. look up the string method split. Also take a look at the syntax of the for statement and notice it has an else clause. -- Bob Gailer Chapel Hill NC 919-636-4239 From dorseye at gmail.com Thu Jan 22 02:38:33 2009 From: dorseye at gmail.com (Eric Dorsey) Date: Wed, 21 Jan 2009 18:38:33 -0700 Subject: [Tutor] Volunteer Opportunities? Message-ID: -- eric dorsey | www.perfecteyedesign.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From dorseye at gmail.com Thu Jan 22 03:07:48 2009 From: dorseye at gmail.com (Eric Dorsey) Date: Wed, 21 Jan 2009 19:07:48 -0700 Subject: [Tutor] Volunteer opportunities Message-ID: (My apologies if a blank message comes up first with this heading -- The first time I meant to type this I managed to tab accidently to Send and hit it before even filling out the message.. :/ ) Does anyone know of any good volunteer opportunities for projects that learning Python coders can work on? Or possibly nonprofits or the like that need smaller-type applications worked on? Much thanks! -- eric dorsey | www.perfecteyedesign.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Thu Jan 22 04:53:29 2009 From: bgailer at gmail.com (bob gailer) Date: Wed, 21 Jan 2009 22:53:29 -0500 Subject: [Tutor] Volunteer opportunities In-Reply-To: References: Message-ID: <4977EDB9.8030306@gmail.com> Eric Dorsey wrote: > > Does anyone know of any good volunteer opportunities for projects that > learning Python coders can work on? Or possibly nonprofits or the like > that need smaller-type applications worked on? I have an open source project that could use some help. See http://en.wikipedia.org/wiki/Python_Pipelines for a brief description. Let me know if you want to know more. -- Bob Gailer Chapel Hill NC 919-636-4239 From wormwood_3 at yahoo.com Thu Jan 22 04:54:23 2009 From: wormwood_3 at yahoo.com (wormwood_3) Date: Wed, 21 Jan 2009 19:54:23 -0800 (PST) Subject: [Tutor] dict() versus {} Message-ID: <411938.23613.qm@web110813.mail.gq1.yahoo.com> When creating a list of dictionaries through a loop, I ran into a strange issue. I'll let the code talk: >>> l = 'i am a special new list'.split() >>> t = [] >>> for thing in l: ... t.append({thing: 1}) ... >>> t [{'i': 1}, {'am': 1}, {'a': 1}, {'special': 1}, {'new': 1}, {'list': 1}] This is what I expected. {} says to make a dictionary. Thing, not being quoted, is clearing a variable, which needs to be evaluated and used as the key. >>> t = [] >>> for thing in l: ... t.append(dict(thing=1)) ... >>> t [{'thing': 1}, {'thing': 1}, {'thing': 1}, {'thing': 1}, {'thing': 1}, {'thing': 1}] This was what threw me. Why would the dict() function not evaluate thing? How can it take it as a literal string without quotes? Thanks for any insight, Sam _______________________ Samuel Huckins Homepage - http://samuelhuckins.com Tech blog - http://dancingpenguinsoflight.com/ Photos - http://www.flickr.com/photos/samuelhuckins/ AIM - samushack | Gtalk - samushack | Skype - shuckins -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Thu Jan 22 05:02:35 2009 From: bgailer at gmail.com (bob gailer) Date: Wed, 21 Jan 2009 23:02:35 -0500 Subject: [Tutor] dict() versus {} In-Reply-To: <411938.23613.qm@web110813.mail.gq1.yahoo.com> References: <411938.23613.qm@web110813.mail.gq1.yahoo.com> Message-ID: <4977EFDB.6070405@gmail.com> An HTML attachment was scrubbed... URL: From wormwood_3 at yahoo.com Thu Jan 22 05:14:23 2009 From: wormwood_3 at yahoo.com (wormwood_3) Date: Wed, 21 Jan 2009 20:14:23 -0800 (PST) Subject: [Tutor] dict() versus {} References: <411938.23613.qm@web110813.mail.gq1.yahoo.com> <4977EFDB.6070405@gmail.com> Message-ID: <677806.43227.qm@web110802.mail.gq1.yahoo.com> Hmm, looked through the latest docs, in the sections on dictionary types, don't see examples that point to this case well. Can you link to what you had in mind? _______________________ Samuel Huckins Homepage - http://samuelhuckins.com Tech blog - http://dancingpenguinsoflight.com/ Photos - http://www.flickr.com/photos/samuelhuckins/ AIM - samushack | Gtalk - samushack | Skype - shuckins ________________________________ From: bob gailer To: wormwood_3 Cc: Python Tutorlist Sent: Wednesday, January 21, 2009 11:02:35 PM Subject: Re: [Tutor] dict() versus {} wormwood_3 wrote: When creating a list of dictionaries through a loop, I ran into a strange issue. I'll let the code talk: >>> l = 'i am a special new list'.split() >>> t = [] >>> for thing in l: ... t.append({thing: 1}) ... >>> t [{'i': 1}, {'am': 1}, {'a': 1}, {'special': 1}, {'new': 1}, {'list': 1}] This is what I expected. {} says to make a dictionary. Thing, not being quoted, is clearing a variable, which needs to be evaluated and used as the key. >>> t = [] >>> for thing in l: ... t.append(dict(thing=1)) ... >>> t [{'thing': 1}, {'thing': 1}, {'thing': 1}, {'thing': 1}, {'thing': 1}, {'thing': 1}] This was what threw me. Why would the dict() function not evaluate thing? How can it take it as a literal string without quotes? I suggest you look dict up in the Python documentation. There it shows the result you got as an example. When in doubt read the manual. -- Bob Gailer Chapel Hill NC 919-636-4239 -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Thu Jan 22 05:25:12 2009 From: bgailer at gmail.com (bob gailer) Date: Wed, 21 Jan 2009 23:25:12 -0500 Subject: [Tutor] dict() versus {} In-Reply-To: <677806.43227.qm@web110802.mail.gq1.yahoo.com> References: <411938.23613.qm@web110813.mail.gq1.yahoo.com> <4977EFDB.6070405@gmail.com> <677806.43227.qm@web110802.mail.gq1.yahoo.com> Message-ID: <4977F528.2050907@gmail.com> An HTML attachment was scrubbed... URL: From bgailer at gmail.com Thu Jan 22 05:31:23 2009 From: bgailer at gmail.com (bob gailer) Date: Wed, 21 Jan 2009 23:31:23 -0500 Subject: [Tutor] Volunteer opportunities In-Reply-To: <1232597996.6121.19.camel@ltop> References: <4977EDB9.8030306@gmail.com> <1232597996.6121.19.camel@ltop> Message-ID: <4977F69B.60408@gmail.com> An HTML attachment was scrubbed... URL: From wormwood_3 at yahoo.com Thu Jan 22 05:39:07 2009 From: wormwood_3 at yahoo.com (wormwood_3) Date: Wed, 21 Jan 2009 20:39:07 -0800 (PST) Subject: [Tutor] dict() versus {} References: <411938.23613.qm@web110813.mail.gq1.yahoo.com> <4977EFDB.6070405@gmail.com> <677806.43227.qm@web110802.mail.gq1.yahoo.com> <4977F528.2050907@gmail.com> Message-ID: <454349.94041.qm@web110811.mail.gq1.yahoo.com> dict( [arg]) Return a new dictionary initialized from an optional positional argument or from a set of keyword arguments. If no arguments are given, return a new empty dictionary. If the positional argument arg is a mapping object, return a dictionary mapping the same keys to the same values as does the mapping object. But why doesn't the optional positional argument arg in this case, not being a mapping type, get evaluated?: dict(thing=1) And even if it makes sense for it not to be evaluated, wouldn't it be better for dict() to complain that it didn't get a string or an int as it expects for a keyword argument? Maybe I am missing the use case, so far it just seems strange to force the keyword to a string. -Sam ________________________________ From: bob gailer To: wormwood_3 Cc: Python Tutorlist Sent: Wednesday, January 21, 2009 11:25:12 PM Subject: Re: [Tutor] dict() versus {} wormwood_3 wrote: Hmm, looked through the latest docs, in the sections on dictionary types, don't see examples that point to this case well. Can you link to what you had in mind? 2.1 Built-in Functions ... dict( [mapping-or-sequence]) ... these all return a dictionary equal to {"one": 2, "two": 3}: ... dict(one=2, two=3) ________________________________ From: bob gailer To: wormwood_3 Cc: Python Tutorlist Sent: Wednesday, January 21, 2009 11:02:35 PM Subject: Re: [Tutor] dict() versus {} wormwood_3 wrote: When creating a list of dictionaries through a loop, I ran into a strange issue. I'll let the code talk: >>> l = 'i am a special new list'.split() >>> t = [] >>> for thing in l: ... t.append({thing: 1}) ... >>> t [{'i': 1}, {'am': 1}, {'a': 1}, {'special': 1}, {'new': 1}, {'list': 1}] This is what I expected. {} says to make a dictionary. Thing, not being quoted, is clearing a variable, which needs to be evaluated and used as the key. >>> t = [] >>> for thing in l: ... t.append(dict(thing=1)) ... >>> t [{'thing': 1}, {'thing': 1}, {'thing': 1}, {'thing': 1}, {'thing': 1}, {'thing': 1}] This was what threw me. Why would the dict() function not evaluate thing? How can it take it as a literal string without quotes? I suggest you look dict up in the Python documentation. There it shows the result you got as an example. When in doubt read the manual. -- Bob Gailer Chapel Hill NC 919-636-4239 ________________________________ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -- Bob Gailer Chapel Hill NC 919-636-4239 -------------- next part -------------- An HTML attachment was scrubbed... URL: From jadrifter at gmail.com Thu Jan 22 06:05:11 2009 From: jadrifter at gmail.com (jadrifter) Date: Wed, 21 Jan 2009 21:05:11 -0800 Subject: [Tutor] Volunteer opportunities In-Reply-To: <4977F69B.60408@gmail.com> References: <4977EDB9.8030306@gmail.com> <1232597996.6121.19.camel@ltop> <4977F69B.60408@gmail.com> Message-ID: <1232600711.6121.26.camel@ltop> On Wed, 2009-01-21 at 23:31 -0500, bob gailer wrote: > Depends on your knowledge of Python and (if any) CMS Pipelines. > > Testing > Design critique (devil's advocate) > Cleaning up and fine-tuning the parser > Coding built-in stages > Documentation > Financial support > > Let me know what sparks your interest. And say a bit about your > background and why this interests you. > > -- > Bob Gailer > Chapel Hill NC > 919-636-4239 Bob, Honestly the first thing that caught my eye was that you were in Chapel Hill. I grew up in Durham NC. I'm in Tacoma WA now. I'm a disabled vet who got into computers and programming from an accounting career. Most of what I've done has been database oriented. I started playing with Python a few years ago and just enjoy the language and would like to find some practical application to use it with. I'm more of a consumer than producer on the tutor list. I read a lot, mostly technical stuff, but nothing that complex. I took a peek at the 889 manual for Pipelines from the wiki page you linked to. It seems to assume a LOT of knowledge I don't have so I'm not sure I'm suitable at all for the project. John Purser From metolone+gmane at gmail.com Thu Jan 22 07:01:08 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Wed, 21 Jan 2009 22:01:08 -0800 Subject: [Tutor] dict() versus {} References: <411938.23613.qm@web110813.mail.gq1.yahoo.com><4977EFDB.6070405@gmail.com><677806.43227.qm@web110802.mail.gq1.yahoo.com><4977F528.2050907@gmail.com> <454349.94041.qm@web110811.mail.gq1.yahoo.com> Message-ID: This: >>> dict(one=1,two=2,three=3) {'three': 3, 'two': 2, 'one': 1} Is a shortcut for the longer: >>> dict((('one',1),('two',2),('three',3))) {'three': 3, 'two': 2, 'one': 1} and given how this works: >>> def function(**kwargs): ... print kwargs ... >>> function(one=1,two=2,three=3) {'three': 3, 'two': 2, 'one': 1} One can guess how the shortcut is implemented. -Mark "wormwood_3" wrote in message news:454349.94041.qm at web110811.mail.gq1.yahoo.com... dict( [arg]) Return a new dictionary initialized from an optional positional argument or from a set of keyword arguments. If no arguments are given, return a new empty dictionary. If the positional argument arg is a mapping object, return a dictionary mapping the same keys to the same values as does the mapping object. But why doesn't the optional positional argument arg in this case, not being a mapping type, get evaluated?: dict(thing=1) And even if it makes sense for it not to be evaluated, wouldn't it be better for dict() to complain that it didn't get a string or an int as it expects for a keyword argument? Maybe I am missing the use case, so far it just seems strange to force the keyword to a string. -Sam ------------------------------------------------------------------------------ From: bob gailer To: wormwood_3 Cc: Python Tutorlist Sent: Wednesday, January 21, 2009 11:25:12 PM Subject: Re: [Tutor] dict() versus {} wormwood_3 wrote: Hmm, looked through the latest docs, in the sections on dictionary types, don't see examples that point to this case well. Can you link to what you had in mind? 2.1 Built-in Functions ... dict( [mapping-or-sequence]) ... these all return a dictionary equal to {"one": 2, "two": 3}: ... dict(one=2, two=3) ---------------------------------------------------------------------------- From: bob gailer To: wormwood_3 Cc: Python Tutorlist Sent: Wednesday, January 21, 2009 11:02:35 PM Subject: Re: [Tutor] dict() versus {} wormwood_3 wrote: When creating a list of dictionaries through a loop, I ran into a strange issue. I'll let the code talk: >>> l = 'i am a special new list'.split() >>> t = [] >>> for thing in l: ... t.append({thing: 1}) ... >>> t [{'i': 1}, {'am': 1}, {'a': 1}, {'special': 1}, {'new': 1}, {'list': 1}] This is what I expected. {} says to make a dictionary. Thing, not being quoted, is clearing a variable, which needs to be evaluated and used as the key. >>> t = [] >>> for thing in l: ... t.append(dict(thing=1)) ... >>> t [{'thing': 1}, {'thing': 1}, {'thing': 1}, {'thing': 1}, {'thing': 1}, {'thing': 1}] This was what threw me. Why would the dict() function not evaluate thing? How can it take it as a literal string without quotes? I suggest you look dict up in the Python documentation. There it shows the result you got as an example. When in doubt read the manual. -- Bob Gailer Chapel Hill NC 919-636-4239 ---------------------------------------------------------------------------- _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -- Bob Gailer Chapel Hill NC 919-636-4239 ------------------------------------------------------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From norman at khine.net Thu Jan 22 10:18:21 2009 From: norman at khine.net (Norman Khine) Date: Thu, 22 Jan 2009 10:18:21 +0100 Subject: [Tutor] profiling python code Message-ID: <497839DD.6060604@khine.net> Hello, I have this output when running the profile on one of my modules: 9815/9644 0.009 0.000 0.009 0.000 {len} 6 0.000 0.000 0.000 0.000 {locals} 5 0.000 0.000 0.001 0.000 {map} 1 0.000 0.000 0.000 0.000 {math.exp} 3 0.000 0.000 0.000 0.000 {math.log} 1 0.000 0.000 0.000 0.000 {math.sqrt} 97 0.000 0.000 0.000 0.000 {max} 9 0.001 0.000 0.001 0.000 {method '__reduce_ex__' of 'object' objects} 7539 0.009 0.000 0.009 0.000 {method 'append' of 'list' objects} The 9815/9644 0.009 0.000 0.009 0.000 {len} line does it mean that the module is making 9815 requests to the len function? Also the line 7539 0.009 0.000 0.009 0.000 {method 'append' of 'list' objects} it looks high!?! How should I interpret this? Cheers Norman From kent37 at tds.net Thu Jan 22 12:33:27 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 22 Jan 2009 06:33:27 -0500 Subject: [Tutor] dict() versus {} In-Reply-To: <411938.23613.qm@web110813.mail.gq1.yahoo.com> References: <411938.23613.qm@web110813.mail.gq1.yahoo.com> Message-ID: <1c2a2c590901220333r7a77f6ecude827cca2ea9d257@mail.gmail.com> On Wed, Jan 21, 2009 at 10:54 PM, wormwood_3 wrote: > When creating a list of dictionaries through a loop, I ran into a strange > issue. I'll let the code talk: >>>> t = [] >>>> for thing in l: > ... t.append(dict(thing=1)) > ... >>>> t > [{'thing': 1}, {'thing': 1}, {'thing': 1}, {'thing': 1}, {'thing': 1}, > {'thing': 1}] > > This was what threw me. Why would the dict() function not evaluate thing? > How can it take it as a literal string without quotes? The call dict(thing=1) is using the standard keyword parameter syntax, and it handles the keywords the same as any other function call - the keywords are tokens, not variable names or expressions, and they are not evaluated. The current behaviour is consistent with other uses of keyword arguments. Use your first method if you want to evaluate the key. Kent From kent37 at tds.net Thu Jan 22 12:41:48 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 22 Jan 2009 06:41:48 -0500 Subject: [Tutor] profiling python code In-Reply-To: <497839DD.6060604@khine.net> References: <497839DD.6060604@khine.net> Message-ID: <1c2a2c590901220341i2845f16eq8c11b8825b9b3246@mail.gmail.com> On Thu, Jan 22, 2009 at 4:18 AM, Norman Khine wrote: > Hello, > > I have this output when running the profile on one of my modules: > It's a bit easier to intepret with the headers: ncalls tottime percall cumtime percall filename:lineno(function) > 9815/9644 0.009 0.000 0.009 0.000 {len} > 6 0.000 0.000 0.000 0.000 {locals} > 5 0.000 0.000 0.001 0.000 {map} > 1 0.000 0.000 0.000 0.000 {math.exp} > 3 0.000 0.000 0.000 0.000 {math.log} > 1 0.000 0.000 0.000 0.000 {math.sqrt} > 97 0.000 0.000 0.000 0.000 {max} > 9 0.001 0.000 0.001 0.000 {method '__reduce_ex__' of > 'object' objects} > 7539 0.009 0.000 0.009 0.000 {method 'append' of 'list' > objects} > > > The > 9815/9644 0.009 0.000 0.009 0.000 {len} > > line does it mean that the module is making 9815 requests to the len > function? Yes. > Also the line > > 7539 0.009 0.000 0.009 0.000 {method 'append' of 'list' objects} > > it looks high!?! That depends on what the code is doing. > How should I interpret this? That your code is spending most of its time in len() and list.append(). The cumtime column is the most useful for figuring out where the time goes. If ncalls is higher than expected then it might be worth figuring out why. Is this an exercise to understand the profiler or real code you are trying to speed up? Showing the code might help. Kent From amit.pureenergy at gmail.com Thu Jan 22 18:08:28 2009 From: amit.pureenergy at gmail.com (amit sethi) Date: Thu, 22 Jan 2009 22:38:28 +0530 Subject: [Tutor] fetching wikipedia articles Message-ID: hi , I need help as to how i can fetch a wikipedia article i tried changing my user agent but it did not work . Although as far as my knowledge of robots.txt goes , looking at en.wikipedia.org/robots.txt it does not seem it should block a useragent (*, which is what i would normally use) from accesing a simple article like say " http://en.wikipedia.org/wiki/Sachin_Tendulkar" but still robotparser returns false status=rp.can_fetch("*", "http://en.wikipedia.org/wiki/Sachin_Tendulkar") where rp is a robot parser object . why is that? -- A-M-I-T S|S -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Thu Jan 22 18:15:09 2009 From: andreengels at gmail.com (Andre Engels) Date: Thu, 22 Jan 2009 18:15:09 +0100 Subject: [Tutor] fetching wikipedia articles In-Reply-To: <6faf39c90901220913h585ce27bue36a111e0c34e6f6@mail.gmail.com> References: <6faf39c90901220913h585ce27bue36a111e0c34e6f6@mail.gmail.com> Message-ID: <6faf39c90901220915i67696c3iff28afc15ed85f92@mail.gmail.com> On Thu, Jan 22, 2009 at 6:08 PM, amit sethi wrote: > hi , I need help as to how i can fetch a wikipedia article i tried changing > my user agent but it did not work . Although as far as my knowledge of > robots.txt goes , looking at en.wikipedia.org/robots.txt it does not seem it > should block a useragent (*, which is what i would normally use) from > accesing a simple article like say > "http://en.wikipedia.org/wiki/Sachin_Tendulkar" but still robotparser > returns false > status=rp.can_fetch("*", "http://en.wikipedia.org/wiki/Sachin_Tendulkar") > where rp is a robot parser object . why is that? Yes, Wikipedia is blocking the Python default user agent. This was done to block the main internal bot in its early days (it was misbehaving by getting each page twice); when it got to allowing the bot again, it had already changed to having its own user agent string, and apparently it was not deemed necessary to unblock the user string... -- Andr? Engels, andreengels at gmail.com From juryef at yahoo.com Thu Jan 22 20:33:20 2009 From: juryef at yahoo.com (Judith Flores) Date: Thu, 22 Jan 2009 11:33:20 -0800 (PST) Subject: [Tutor] Writing long strings (that include commas) to a csv file Message-ID: <745293.44861.qm@web34706.mail.mud.yahoo.com> Hello dear Python experts, How can I write a complete string (which sometimes will include many commas) to a cell in a CSV file? With the code below, what I obtain is a cell per letter of every string: file1=open('myfile.csv','w') writer=csv.writer(file1) mylist=[ " first , txt+words , more" , " second, text + words, and more"] listnumbers=["0","5"] for i in range(0,len(mylist)): writer.writerow(mylist[i] + listnumbers[i]) file1.close() So the first element of mylist should fill up only one cell in the csv file, and the same for the second elemente, and so on. Any help would be very much appreciated. Thank you! Judith From magoldfish at gmail.com Thu Jan 22 21:04:45 2009 From: magoldfish at gmail.com (Marcus Goldfish) Date: Thu, 22 Jan 2009 15:04:45 -0500 Subject: [Tutor] class design - base classes with optional properties? Message-ID: <5e183f3d0901221204wadbdfb6gcdb47da20bf7b5fd@mail.gmail.com> I'm trying to design a base class for a hierarchy. The properties I want to specify for the base class depend on the values of other properties of the base class. For instance, in this toy example of a base FoodProcessor class: class FoodProcessor: "Model for a kitchen appliance food processor" speed_settings # example [1, 2, 3, 4] blade_settings # example ["slice", "grate", "grind"] slice_thickness # example ["thin", "thick"], but only if blade_setting is "slice" it only make sense to have the slice_thickness property set when blade_settings = "slice"; otherwise, it would be preferable to only define the speed_settings and blade_settings properties. For example: class ProcessorA(FoodProcessor): "A slicing-only processor" speed_settings = [1, 2, 3, 4] blade_settings = "slice" slice_thickness = ["thin", "thick"] class ProcessorB(FoodProcessor): "A non-slicing processor" speed_settings = [1,2,3,4] blade_settings = ["grate", "grind"] slice_thickness = None Can anyone suggest some work-arounds, or refactoring for this type of design? Is there a design pattern for this? Thanks! Marcus -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu Jan 22 21:36:49 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 22 Jan 2009 15:36:49 -0500 Subject: [Tutor] Writing long strings (that include commas) to a csv file In-Reply-To: <745293.44861.qm@web34706.mail.mud.yahoo.com> References: <745293.44861.qm@web34706.mail.mud.yahoo.com> Message-ID: <1c2a2c590901221236g450ab89atee7a46c574a01cc7@mail.gmail.com> On Thu, Jan 22, 2009 at 2:33 PM, Judith Flores wrote: > Hello dear Python experts, > > How can I write a complete string (which sometimes will include many commas) to a cell in a CSV file? With the code below, what I obtain is a cell per letter of every string: > > > file1=open('myfile.csv','w') > writer=csv.writer(file1) > > mylist=[ " first , txt+words , more" , " second, text + words, and more"] > listnumbers=["0","5"] > > for i in range(0,len(mylist)): > > writer.writerow(mylist[i] + listnumbers[i]) The argument passed to writerow() is a sequence where each element of the sequence is one cell value. Here, you are passing a string as the argument. A string is a sequence of characters, so you are telling writerow() to write one character per cell. What you want to give writerow() is a list containing the two strings that you want placed in the two cells. Like this: writer.writerow([mylist[i], listnumbers[i]]) You could also use the zip() function and writerows() to do this more simply. zip(mylist, listnumbers) returns a list of pairs: In [3]: zip(mylist, listnumbers) Out[3]: [(' first , txt+words , more', '0'), (' second, text + words, and more', '5')] This is exactly the rows you want to write to the file, so writer.writerows(zip(mylist, listnumbers)) will do what you want without an explicit loop. Kent From kent37 at tds.net Thu Jan 22 21:41:08 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 22 Jan 2009 15:41:08 -0500 Subject: [Tutor] class design - base classes with optional properties? In-Reply-To: <5e183f3d0901221204wadbdfb6gcdb47da20bf7b5fd@mail.gmail.com> References: <5e183f3d0901221204wadbdfb6gcdb47da20bf7b5fd@mail.gmail.com> Message-ID: <1c2a2c590901221241r5c52b669o5422fba5c1a2e9c8@mail.gmail.com> On Thu, Jan 22, 2009 at 3:04 PM, Marcus Goldfish wrote: > I'm trying to design a base class for a hierarchy. The properties I want to > specify for the base class depend on the values of other properties of the > base class. For instance, in this toy example of a base FoodProcessor > class: > class FoodProcessor: > "Model for a kitchen appliance food processor" > speed_settings # example [1, 2, 3, 4] > blade_settings # example ["slice", "grate", "grind"] > slice_thickness # example ["thin", "thick"], but only if > blade_setting is "slice" > it only make sense to have the slice_thickness property set when > blade_settings = "slice"; otherwise, it would be preferable to only define > the speed_settings and blade_settings properties. For example: > class ProcessorA(FoodProcessor): > "A slicing-only processor" > speed_settings = [1, 2, 3, 4] > blade_settings = "slice" > slice_thickness = ["thin", "thick"] > class ProcessorB(FoodProcessor): > "A non-slicing processor" > speed_settings = [1,2,3,4] > blade_settings = ["grate", "grind"] > slice_thickness = None > Can anyone suggest some work-arounds, or refactoring for this type of > design? Is there a design pattern for this? I'm not sure what the problem is. You can provide default values in the base class: class FoodProcessor(object): speed_settings = None blade_settings = None slice_thickness = None Then in a derived class you can override just the ones you want to use: class ProcessorB(FoodProcessor): "A non-slicing processor" speed_settings = [1,2,3,4] blade_settings = ["grate", "grind"] If you want to validate that the current settings make sense, you could put a test in the __init__() method, which is simple to implement but happens at instance creation time, or you could write a metaclass to validate the settings at class creation time, which is more difficult (to understand, anyway). Kent From denis.spir at free.fr Thu Jan 22 22:51:04 2009 From: denis.spir at free.fr (spir) Date: Thu, 22 Jan 2009 22:51:04 +0100 Subject: [Tutor] class arguments? Message-ID: <20090122225104.03c677f4@o> Hello, is there a way to give arguments to a class definition? Eg class MonoList(list, typ, number): item_type = typ item_number = number [I guess you understand what I try to do...] denis ------ la vida e estranya From alan.gauld at btinternet.com Thu Jan 22 23:01:39 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 22 Jan 2009 22:01:39 -0000 Subject: [Tutor] class arguments? References: <20090122225104.03c677f4@o> Message-ID: "spir" wrote > is there a way to give arguments to a class definition? Eg > > class MonoList(list, typ, number): > item_type = typ > item_number = number Yes thats what the __init__ method is for. class MonoList: def __init__(self, lst, typ, num): self.item_type = typ self.number = num etc... myList = MonoList([1,2,3], int, 3) # or whatever... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Thu Jan 22 23:18:54 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 22 Jan 2009 17:18:54 -0500 Subject: [Tutor] class arguments? In-Reply-To: <20090122225104.03c677f4@o> References: <20090122225104.03c677f4@o> Message-ID: <1c2a2c590901221418h418f5030ua2ae253be3e6099e@mail.gmail.com> On Thu, Jan 22, 2009 at 4:51 PM, spir wrote: > Hello, > > is there a way to give arguments to a class definition? Eg > > class MonoList(list, typ, number): > item_type = typ > item_number = number Use the type() function (which is the constructor for the type 'type') to dynamically create classes (i.e. types), e.g. In [1]: typ = int In [2]: number = 3 In [3]: MonoList = type("MonoList", (list,), dict(item_type=typ, item_number=number)) In [4]: ml = MonoList() In [5]: ml.item_type Out[5]: In [6]: ml.item_number Out[6]: 3 In [7]: isinstance(ml, list) Out[7]: True http://docs.python.org/library/functions.html#type Kent From kent37 at tds.net Thu Jan 22 23:47:46 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 22 Jan 2009 17:47:46 -0500 Subject: [Tutor] class arguments? In-Reply-To: <1c2a2c590901221418h418f5030ua2ae253be3e6099e@mail.gmail.com> References: <20090122225104.03c677f4@o> <1c2a2c590901221418h418f5030ua2ae253be3e6099e@mail.gmail.com> Message-ID: <1c2a2c590901221447s78b5588fw534fcbb20b8757d3@mail.gmail.com> On Thu, Jan 22, 2009 at 5:18 PM, Kent Johnson wrote: > On Thu, Jan 22, 2009 at 4:51 PM, spir wrote: >> Hello, >> >> is there a way to give arguments to a class definition? Eg >> >> class MonoList(list, typ, number): >> item_type = typ >> item_number = number > > Use the type() function (which is the constructor for the type 'type') > to dynamically create classes (i.e. types), e.g. > > In [1]: typ = int > > In [2]: number = 3 > > In [3]: MonoList = type("MonoList", (list,), dict(item_type=typ, > item_number=number)) > > In [4]: ml = MonoList() > > In [5]: ml.item_type > Out[5]: > > In [6]: ml.item_number > Out[6]: 3 > > In [7]: isinstance(ml, list) > Out[7]: True And to show that these are class attributes: In [4]: MonoList.item_number Out[4]: 3 In [5]: MonoList.item_type Out[5]: Kent From alan.gauld at btinternet.com Fri Jan 23 00:24:22 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 22 Jan 2009 23:24:22 -0000 Subject: [Tutor] class design - base classes with optional properties? References: <5e183f3d0901221204wadbdfb6gcdb47da20bf7b5fd@mail.gmail.com> Message-ID: "Marcus Goldfish" wrote > I'm trying to design a base class for a hierarchy. The properties I > want to > specify for the base class depend on the values of other properties > of the > base class. Don't worry so much about the properties, the important thing to focus on in your base classes is the behaviour. What exactly will these classes do? What methods will they have? How will they be overridden in your subclasses. Ideally the properties are invisible to the users of the class so the interactions of the properties should all be controlled by the methods. > class FoodProcessor: > "Model for a kitchen appliance food processor" > speed_settings # example [1, 2, 3, 4] > blade_settings # example ["slice", "grate", "grind"] > slice_thickness # example ["thin", "thick"], but only if > blade_setting is "slice" > > it only make sense to have the slice_thickness property set when > blade_settings = "slice"; otherwise, it would be preferable to only > define > the speed_settings and blade_settings properties. For example: So create a method to initialise slicing which sets both properties (with appropriate default values if you like) Similarly define methods for grating and grinding. Think about what you want to *do* with a class not what you want to store. The function should dictate the attributes. > class ProcessorA(FoodProcessor): > "A slicing-only processor" > speed_settings = [1, 2, 3, 4] > blade_settings = "slice" > slice_thickness = ["thin", "thick"] > > class ProcessorB(FoodProcessor): > "A non-slicing processor" > speed_settings = [1,2,3,4] > blade_settings = ["grate", "grind"] > slice_thickness = None Unless this is a multi function food processor I'd probably go for a heirarchy of FoodProcessor Slicer Grater Grinder In fact I might do that anyway and then create MultiFunction as a subclass of of all 3 food processors... class MultiFunction(Slicer, Grater, Grinder): etc... Remember that ideally nothing outside the class should be manipulating the attributes directly, everything should be done by sending messages (ie calling methods) to the objects. The fact that you want a heirarchy suggests that you have some form of polymorphic operations to be performed? What are those operations at the abstract FoodProcessor level? It is actually very common that the root object in a heirarchy has very few if any attributes but will have all the methods needed for the concept to work. As you subclass you add attributes to support the subclass specific implementation of the methods. If you truly want a multi purpose mixer and don't want to subclass from all 3 types then you could have a changeBlade method that specifies the blade type and any additional attributes. The Blades could even be a class heirarchy in their own right: Blade Slicer Grinder Grater # create a new processor with initially a slicer blade p = FoodProcessor(Slicer(thickness)) p..process(spam) p.changeBlade(Grater(granularity)) p.process(Cheese(5, 'oz')) # uses a Cheese object with weight in ounces... and so on... But the only real solution will depend on what you intend to do with your classes. Think about how you want to write the client code. Think about doing that using method calls rather than manipulating the inner data. That way you can leverage polymorphism to your advantage. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Fri Jan 23 00:29:59 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 22 Jan 2009 23:29:59 -0000 Subject: [Tutor] class arguments? References: <20090122225104.03c677f4@o> Message-ID: "Alan Gauld" wrote >> is there a way to give arguments to a class definition? I see that Kent interpreted your question differently to me. If you do mean that you want to dynamically define class attributes rather than instance attributes then __init__() won't work. But I'd be interested to understand why and how you would want to do that? And in particular how you would use them after creating them? > Yes thats what the __init__ method is for. > > class MonoList: > def __init__(self, lst, typ, num): > self.item_type = typ > self.number = num > etc... > > myList = MonoList([1,2,3], int, 3) # or whatever... Alan G. From kent37 at tds.net Fri Jan 23 01:05:44 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 22 Jan 2009 19:05:44 -0500 Subject: [Tutor] class design - base classes with optional properties? In-Reply-To: References: <5e183f3d0901221204wadbdfb6gcdb47da20bf7b5fd@mail.gmail.com> Message-ID: <1c2a2c590901221605l77ac5f28id6883d75d0d607b2@mail.gmail.com> On Thu, Jan 22, 2009 at 6:24 PM, Alan Gauld wrote: > "Marcus Goldfish" wrote > >> I'm trying to design a base class for a hierarchy. The properties I want >> to >> specify for the base class depend on the values of other properties of the >> base class. > > Don't worry so much about the properties, the important thing to focus on > in your base classes is the behaviour. What exactly will these classes do? > What methods will they have? How will they be overridden in your > subclasses. > > Ideally the properties are invisible to the users of the class so the > interactions of the properties should all be controlled by the > methods. Class attributes can be a useful way to configure behaviour of subclasses. For example an HTML rendering widget might have attributes giving the type of tag to use to render or other HTML attributes. The Django HTML widgets are an example of this: http://code.djangoproject.com/browser/django/trunk/django/forms/widgets.py Look at the Input class and subclasses. Kent From sierra_mtnview at sbcglobal.net Fri Jan 23 01:44:36 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 22 Jan 2009 16:44:36 -0800 Subject: [Tutor] Available filetypes for AskSaveasfilenam in Tkinter? Message-ID: <497912F4.3020803@sbcglobal.net> An HTML attachment was scrubbed... URL: From john at fouhy.net Fri Jan 23 01:52:44 2009 From: john at fouhy.net (John Fouhy) Date: Fri, 23 Jan 2009 13:52:44 +1300 Subject: [Tutor] Available filetypes for AskSaveasfilenam in Tkinter? In-Reply-To: <497912F4.3020803@sbcglobal.net> References: <497912F4.3020803@sbcglobal.net> Message-ID: <5e58f2e40901221652j1dbfefedtadb916ee2a37b5ec@mail.gmail.com> 2009/1/23 Wayne Watson : > How do I know what file types are available for asksaveasfilename? Suppose > one isn't available, for example, FITS. How do I get it? You pass the file types as an argument to the function. tkFileDialog.asksaveasfilename(filetypes=[('Text', '*.txt'), ('Stuff', '*.stf'), ('Et cetera', '*.etc')]) http://www.pythonware.com/library/tkinter/introduction/x1164-data-entry.htm -- John. From sierra_mtnview at sbcglobal.net Fri Jan 23 02:41:10 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 22 Jan 2009 17:41:10 -0800 Subject: [Tutor] Available filetypes for AskSaveasfilenam in Tkinter? In-Reply-To: <5e58f2e40901221652j1dbfefedtadb916ee2a37b5ec@mail.gmail.com> References: <497912F4.3020803@sbcglobal.net> <5e58f2e40901221652j1dbfefedtadb916ee2a37b5ec@mail.gmail.com> Message-ID: <49792036.9090709@sbcglobal.net> An HTML attachment was scrubbed... URL: From john at fouhy.net Fri Jan 23 02:53:29 2009 From: john at fouhy.net (John Fouhy) Date: Fri, 23 Jan 2009 14:53:29 +1300 Subject: [Tutor] Available filetypes for AskSaveasfilenam in Tkinter? In-Reply-To: <49792036.9090709@sbcglobal.net> References: <497912F4.3020803@sbcglobal.net> <5e58f2e40901221652j1dbfefedtadb916ee2a37b5ec@mail.gmail.com> <49792036.9090709@sbcglobal.net> Message-ID: <5e58f2e40901221753q2b90b78n9d780e3de43f2f34@mail.gmail.com> 2009/1/23 Wayne Watson : > And if I pass it, 'pcx', 'fits', 'dog', 'cat', ...? I don't understand your question. You can certainly do this: tkFileDialog.asksaveasfilename(filetypes=[('PCX files', '*.pcx'), ('FITS files', '*.fits'), ('Dogs', '*.dog')]) If that's not what you want, you need to explain yourself better.. -- John. From sierra_mtnview at sbcglobal.net Fri Jan 23 03:29:29 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 22 Jan 2009 18:29:29 -0800 Subject: [Tutor] Available filetypes for AskSaveasfilenam in Tkinter? In-Reply-To: <5e58f2e40901221753q2b90b78n9d780e3de43f2f34@mail.gmail.com> References: <497912F4.3020803@sbcglobal.net> <5e58f2e40901221652j1dbfefedtadb916ee2a37b5ec@mail.gmail.com> <49792036.9090709@sbcglobal.net> <5e58f2e40901221753q2b90b78n9d780e3de43f2f34@mail.gmail.com> Message-ID: <49792B89.5080807@sbcglobal.net> An HTML attachment was scrubbed... URL: From john at fouhy.net Fri Jan 23 03:34:56 2009 From: john at fouhy.net (John Fouhy) Date: Fri, 23 Jan 2009 15:34:56 +1300 Subject: [Tutor] Available filetypes for AskSaveasfilenam in Tkinter? In-Reply-To: <49792B89.5080807@sbcglobal.net> References: <497912F4.3020803@sbcglobal.net> <5e58f2e40901221652j1dbfefedtadb916ee2a37b5ec@mail.gmail.com> <49792036.9090709@sbcglobal.net> <5e58f2e40901221753q2b90b78n9d780e3de43f2f34@mail.gmail.com> <49792B89.5080807@sbcglobal.net> Message-ID: <5e58f2e40901221834g159c7309gb72d94c48abb5948@mail.gmail.com> 2009/1/23 Wayne Watson : > What I'm getting at it is when I see something in a program as: > path = asksaveasfilename(defaultextension=".jpg", > title="Save as JPEG", > initialfile=default_path, > filetypes=IMAGE_FILE_TYPES) > > I'm guessing when the program executes this, it's really saves a file in the > jpg format. [...] All asksaveasfilename does is give you a filename/path. You then have to open the file and write the data to it. It's up to you to make sure the data is in the right format.. -- John. From sierra_mtnview at sbcglobal.net Fri Jan 23 03:48:23 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 22 Jan 2009 18:48:23 -0800 Subject: [Tutor] Available filetypes for AskSaveasfilenam in Tkinter? In-Reply-To: <5e58f2e40901221834g159c7309gb72d94c48abb5948@mail.gmail.com> References: <497912F4.3020803@sbcglobal.net> <5e58f2e40901221652j1dbfefedtadb916ee2a37b5ec@mail.gmail.com> <49792036.9090709@sbcglobal.net> <5e58f2e40901221753q2b90b78n9d780e3de43f2f34@mail.gmail.com> <49792B89.5080807@sbcglobal.net> <5e58f2e40901221834g159c7309gb72d94c48abb5948@mail.gmail.com> Message-ID: <49792FF7.7030703@sbcglobal.net> An HTML attachment was scrubbed... URL: From john at fouhy.net Fri Jan 23 04:03:23 2009 From: john at fouhy.net (John Fouhy) Date: Fri, 23 Jan 2009 16:03:23 +1300 Subject: [Tutor] Available filetypes for AskSaveasfilenam in Tkinter? In-Reply-To: <49792FF7.7030703@sbcglobal.net> References: <497912F4.3020803@sbcglobal.net> <5e58f2e40901221652j1dbfefedtadb916ee2a37b5ec@mail.gmail.com> <49792036.9090709@sbcglobal.net> <5e58f2e40901221753q2b90b78n9d780e3de43f2f34@mail.gmail.com> <49792B89.5080807@sbcglobal.net> <5e58f2e40901221834g159c7309gb72d94c48abb5948@mail.gmail.com> <49792FF7.7030703@sbcglobal.net> Message-ID: <5e58f2e40901221903y36439944wcc3802e5fe2b09e3@mail.gmail.com> 2009/1/23 Wayne Watson : > Continuing. The code that is eventually used to do the save is: > =================== > def SaveGIF(self): > if self.current_path: > default_path = splitext(basename(self.current_path))[0] + ".gif" > path = asksaveasfilename(defaultextension=".gif", > title="Save as GIF", > initialfile=default_path, > filetypes=GIF_FILE_TYPES) > else: > path = asksaveasfilename(defaultextension=".gif", > title="Save as GIF", > filetypes=GIF_FILE_TYPES): > if not path: > return > gif = self.current_image.convert("RGB") > gif.save(path) > ================== > > I would think convert makes the conversion. If so, then it must know a lot > of formats. How do I know which ones it has available? If it has a small > set, is there some way to find another "convert" that produces, say, a 'pcx" > formated file. > > Apparently, "RGB" and "GIF" mean the same thing. Seems a bit odd. Well, "RGB" stands for "Red Green Blue". I'm not much of a graphics format guy, but I think it means basically a bitmap, where each pixel has an associated tuple (red, green, blue) containing the proportion of each (on a range from 0..255). (as opposed to vector formats like EPS, or layered formats that programs like photoshop use) It is possible that the save() function inspects the file name extension and produces output appropriately. At any rate, your question seems more to do with the image library you are using, and nothing at all to do with tkFileDialog.asksaveasformat. It's probably PIL -- the Python Image Library. See the documentation here: http://www.pythonware.com/library/pil/handbook/index.htm -- John. From sierra_mtnview at sbcglobal.net Fri Jan 23 04:27:08 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 22 Jan 2009 19:27:08 -0800 Subject: [Tutor] Available filetypes for AskSaveasfilenam in Tkinter? In-Reply-To: <5e58f2e40901221903y36439944wcc3802e5fe2b09e3@mail.gmail.com> References: <497912F4.3020803@sbcglobal.net> <5e58f2e40901221652j1dbfefedtadb916ee2a37b5ec@mail.gmail.com> <49792036.9090709@sbcglobal.net> <5e58f2e40901221753q2b90b78n9d780e3de43f2f34@mail.gmail.com> <49792B89.5080807@sbcglobal.net> <5e58f2e40901221834g159c7309gb72d94c48abb5948@mail.gmail.com> <49792FF7.7030703@sbcglobal.net> <5e58f2e40901221903y36439944wcc3802e5fe2b09e3@mail.gmail.com> Message-ID: <4979390C.1020003@sbcglobal.net> An HTML attachment was scrubbed... URL: From amit.pureenergy at gmail.com Fri Jan 23 09:09:19 2009 From: amit.pureenergy at gmail.com (amit sethi) Date: Fri, 23 Jan 2009 13:39:19 +0530 Subject: [Tutor] fetching wikipedia articles In-Reply-To: <6faf39c90901220915i67696c3iff28afc15ed85f92@mail.gmail.com> References: <6faf39c90901220913h585ce27bue36a111e0c34e6f6@mail.gmail.com> <6faf39c90901220915i67696c3iff28afc15ed85f92@mail.gmail.com> Message-ID: Well that is interesting but why should that happen in case I am using a different User Agent because I tried doing status=rp.can_fetch('Mozilla/5.0', " http://en.wikipedia.org/wiki/Sachin_Tendulkar") but even that returns false Is there something wrong with the syntax , Is there a catch that i don't understand. On Thu, Jan 22, 2009 at 10:45 PM, Andre Engels wrote: > On Thu, Jan 22, 2009 at 6:08 PM, amit sethi > wrote: > > hi , I need help as to how i can fetch a wikipedia article i tried > changing > > my user agent but it did not work . Although as far as my knowledge of > > robots.txt goes , looking at en.wikipedia.org/robots.txt it does not > seem it > > should block a useragent (*, which is what i would normally use) from > > accesing a simple article like say > > "http://en.wikipedia.org/wiki/Sachin_Tendulkar" but still robotparser > > returns false > > status=rp.can_fetch("*", "http://en.wikipedia.org/wiki/Sachin_Tendulkar > ") > > where rp is a robot parser object . why is that? > > Yes, Wikipedia is blocking the Python default user agent. This was > done to block the main internal bot in its early days (it was > misbehaving by getting each page twice); when it got to allowing the > bot again, it had already changed to having its own user agent string, > and apparently it was not deemed necessary to unblock the user > string... > > > > > -- > Andr? Engels, andreengels at gmail.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- A-M-I-T S|S -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Fri Jan 23 09:55:03 2009 From: andreengels at gmail.com (Andre Engels) Date: Fri, 23 Jan 2009 09:55:03 +0100 Subject: [Tutor] fetching wikipedia articles In-Reply-To: References: <6faf39c90901220913h585ce27bue36a111e0c34e6f6@mail.gmail.com> <6faf39c90901220915i67696c3iff28afc15ed85f92@mail.gmail.com> Message-ID: <6faf39c90901230055r2f1d5469r85d1eadc4ed3adf8@mail.gmail.com> On Fri, Jan 23, 2009 at 9:09 AM, amit sethi wrote: > Well that is interesting but why should that happen in case I am using a > different User Agent because I tried doing > status=rp.can_fetch('Mozilla/5.0', > "http://en.wikipedia.org/wiki/Sachin_Tendulkar") > but even that returns false > Is there something wrong with the syntax , Is there a catch that i don't > understand. The problem is that you are using the standard Python user agent when getting the robots.txt. Because the user agent is refused, it cannot get the robots.txt file itself to look at. -- Andr? Engels, andreengels at gmail.com From amit.pureenergy at gmail.com Fri Jan 23 10:37:09 2009 From: amit.pureenergy at gmail.com (amit sethi) Date: Fri, 23 Jan 2009 15:07:09 +0530 Subject: [Tutor] fetching wikipedia articles In-Reply-To: <6faf39c90901230055r2f1d5469r85d1eadc4ed3adf8@mail.gmail.com> References: <6faf39c90901220913h585ce27bue36a111e0c34e6f6@mail.gmail.com> <6faf39c90901220915i67696c3iff28afc15ed85f92@mail.gmail.com> <6faf39c90901230055r2f1d5469r85d1eadc4ed3adf8@mail.gmail.com> Message-ID: so is there a way around that problem ?? On Fri, Jan 23, 2009 at 2:25 PM, Andre Engels wrote: > On Fri, Jan 23, 2009 at 9:09 AM, amit sethi > wrote: > > Well that is interesting but why should that happen in case I am using a > > different User Agent because I tried doing > > status=rp.can_fetch('Mozilla/5.0', > > "http://en.wikipedia.org/wiki/Sachin_Tendulkar") > > but even that returns false > > Is there something wrong with the syntax , Is there a catch that i don't > > understand. > > The problem is that you are using the standard Python user agent when > getting the robots.txt. Because the user agent is refused, it cannot > get the robots.txt file itself to look at. > > -- > Andr? Engels, andreengels at gmail.com > -- A-M-I-T S|S -------------- next part -------------- An HTML attachment was scrubbed... URL: From vginer at gmail.com Fri Jan 23 11:17:15 2009 From: vginer at gmail.com (Vicent) Date: Fri, 23 Jan 2009 11:17:15 +0100 Subject: [Tutor] Customizing Eclipse text editor Message-ID: <50ed08f40901230217h473e98c4r5b26e4858b6d8dd9@mail.gmail.com> Hello everyone. I work with Eclipse+PyDev. I've managed to customize colors and fonts of the text editor, but I don't know how to change the appearance of the vertical zone that contains folding controls which is next to the line number zone, at the left of the editor window. Here you can see a screenshot for what I mean (it is the white vertical zone close to the line number zone): http://dl.getdropbox.com/u/155485/screenshot01.png Can you help me? As you can see there, I prefer a black background, so I've changed colors a little. My second question is: do you know any kind of recomended (I mean, optimized for a good working experience, good for eyes health, etc.) color palette or color combination with black background? Thank you in advance. -- Vicent -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Fri Jan 23 11:25:43 2009 From: andreengels at gmail.com (Andre Engels) Date: Fri, 23 Jan 2009 11:25:43 +0100 Subject: [Tutor] fetching wikipedia articles In-Reply-To: References: <6faf39c90901220913h585ce27bue36a111e0c34e6f6@mail.gmail.com> <6faf39c90901220915i67696c3iff28afc15ed85f92@mail.gmail.com> <6faf39c90901230055r2f1d5469r85d1eadc4ed3adf8@mail.gmail.com> Message-ID: <6faf39c90901230225q3d6ec030sb224315810f584a0@mail.gmail.com> On Fri, Jan 23, 2009 at 10:37 AM, amit sethi wrote: > so is there a way around that problem ?? Ok, I have done some checking around, and it seems that the Wikipedia server is giving a return code of 403 (forbidden), but still giving the page - which I think is weird behaviour. I will check with the developers of Wikimedia why this is done, but for now you can resolve this by editing robotparser.py in the following way: In the __init__ of the class URLopener, add the following at the end: self.addheaders = [header for header in self.addheaders if header[0] != "User-Agent"] + [('User-Agent', '')] (probably self.addheaders = [('User-Agent', '')] does the same, but my version is more secure) -- Andr? Engels, andreengels at gmail.com From andreengels at gmail.com Fri Jan 23 11:37:53 2009 From: andreengels at gmail.com (Andre Engels) Date: Fri, 23 Jan 2009 11:37:53 +0100 Subject: [Tutor] fetching wikipedia articles In-Reply-To: <6faf39c90901230225q3d6ec030sb224315810f584a0@mail.gmail.com> References: <6faf39c90901220913h585ce27bue36a111e0c34e6f6@mail.gmail.com> <6faf39c90901220915i67696c3iff28afc15ed85f92@mail.gmail.com> <6faf39c90901230055r2f1d5469r85d1eadc4ed3adf8@mail.gmail.com> <6faf39c90901230225q3d6ec030sb224315810f584a0@mail.gmail.com> Message-ID: <6faf39c90901230237v724df84dgeebac6075f2b798f@mail.gmail.com> On Fri, Jan 23, 2009 at 11:25 AM, Andre Engels wrote: > In the __init__ of the class URLopener, add the following at the end: > > self.addheaders = [header for header in self.addheaders if header[0] > != "User-Agent"] + [('User-Agent', '')] > > (probably > > self.addheaders = [('User-Agent', '')] > > does the same, but my version is more secure) Looking further I found that a 'cleaner' way to make the same change is to add to the code of URLopener (outside any method): version = '' -- Andr? Engels, andreengels at gmail.com From denis.spir at free.fr Fri Jan 23 12:04:39 2009 From: denis.spir at free.fr (spir) Date: Fri, 23 Jan 2009 12:04:39 +0100 Subject: [Tutor] class arguments? In-Reply-To: References: <20090122225104.03c677f4@o> Message-ID: <20090123120439.1a12b4db@o> Le Thu, 22 Jan 2009 23:29:59 -0000, "Alan Gauld" a ?crit : > > "Alan Gauld" wrote > > >> is there a way to give arguments to a class definition? > > I see that Kent interpreted your question differently to me. > If you do mean that you want to dynamically define class > attributes rather than instance attributes then __init__() > won't work. But I'd be interested to understand why and > how you would want to do that? And in particular how > you would use them after creating them? Thank you Alan and sorry for not having been clear enough. The point actually was class (definition) attributes. I thought at e.g. Guido's views that lists were for homogeneous sequences as opposed to tuples rather like records. And a way to ensure sich a homogeneity, in the sense of items beeing of the same type or super type. The straightforward path to ensure that, as I see it, is to add proper argument to a class definition. But I couldn't find a way to do this. In pseudo-code, it would look like that: class MonoList(list, item_type): typ = item_type def __init__(self,items): self._check_types(items) list.__init__(self,items) def _check_types(self,items): for item in items: if not isinstance(item,MonoList.typ): message = "blah!" raise TypeError(message) def __setitem__(self,index,item): if not isinstance(item,MonoList.typ): message = "blah!" raise TypeError(message) list.__setitem__(self,index,item) def __add__(self,other): self._check_types(other) list.__add__(self,other) ....... Well, I realize now that it is a bit more complicated. MonoList itself should be an intermediate base class between list and and subclasses that each allow only a single item type. Otherwise all monolist-s have the same item type ;-) Just exploring around... denis > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > ------ la vida e estranya From amit.pureenergy at gmail.com Fri Jan 23 12:07:53 2009 From: amit.pureenergy at gmail.com (amit sethi) Date: Fri, 23 Jan 2009 16:37:53 +0530 Subject: [Tutor] fetching wikipedia articles In-Reply-To: <6faf39c90901230225q3d6ec030sb224315810f584a0@mail.gmail.com> References: <6faf39c90901220913h585ce27bue36a111e0c34e6f6@mail.gmail.com> <6faf39c90901220915i67696c3iff28afc15ed85f92@mail.gmail.com> <6faf39c90901230055r2f1d5469r85d1eadc4ed3adf8@mail.gmail.com> <6faf39c90901230225q3d6ec030sb224315810f584a0@mail.gmail.com> Message-ID: well thanks ... it worked well ... but robotparser is in urllib isn't there a module like robotparser in urllib2 On Fri, Jan 23, 2009 at 3:55 PM, Andre Engels wrote: > On Fri, Jan 23, 2009 at 10:37 AM, amit sethi > wrote: > > so is there a way around that problem ?? > > Ok, I have done some checking around, and it seems that the Wikipedia > server is giving a return code of 403 (forbidden), but still giving > the page - which I think is weird behaviour. I will check with the > developers of Wikimedia why this is done, but for now you can resolve > this by editing robotparser.py in the following way: > > In the __init__ of the class URLopener, add the following at the end: > > self.addheaders = [header for header in self.addheaders if header[0] > != "User-Agent"] + [('User-Agent', '')] > > (probably > > self.addheaders = [('User-Agent', '')] > > does the same, but my version is more secure) > > -- > Andr? Engels, andreengels at gmail.com > -- A-M-I-T S|S -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Fri Jan 23 12:11:32 2009 From: andreengels at gmail.com (Andre Engels) Date: Fri, 23 Jan 2009 12:11:32 +0100 Subject: [Tutor] fetching wikipedia articles In-Reply-To: References: <6faf39c90901220913h585ce27bue36a111e0c34e6f6@mail.gmail.com> <6faf39c90901220915i67696c3iff28afc15ed85f92@mail.gmail.com> <6faf39c90901230055r2f1d5469r85d1eadc4ed3adf8@mail.gmail.com> <6faf39c90901230225q3d6ec030sb224315810f584a0@mail.gmail.com> Message-ID: <6faf39c90901230311r229114b7r219d601977551319@mail.gmail.com> On Fri, Jan 23, 2009 at 12:07 PM, amit sethi wrote: > well thanks ... it worked well ... but robotparser is in urllib isn't there > a module like robotparser in > urllib2 You'll have to ask someone else about that part... -- Andr? Engels, andreengels at gmail.com From alan.gauld at btinternet.com Fri Jan 23 12:23:11 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 23 Jan 2009 11:23:11 -0000 Subject: [Tutor] fetching wikipedia articles References: <6faf39c90901220913h585ce27bue36a111e0c34e6f6@mail.gmail.com><6faf39c90901220915i67696c3iff28afc15ed85f92@mail.gmail.com><6faf39c90901230055r2f1d5469r85d1eadc4ed3adf8@mail.gmail.com> <6faf39c90901230225q3d6ec030sb224315810f584a0@mail.gmail.com> Message-ID: "Andre Engels" wrote > developers of Wikimedia why this is done, but for now you can > resolve > this by editing robotparser.py in the following way: > > In the __init__ of the class URLopener, add the following at the > end: > > self.addheaders = [header for header in self.addheaders if header[0] > != "User-Agent"] + [('User-Agent', '')] Rather than editing the existing code and making it non standard why not subclass robotparser: class WP_RobotParser(robotparser): def __init__(self, *args, *kwargs): robotparser.__init__(self, *args, *kwargs) self.addheaders = .......blah.... Thats one of the advantages of OOP, you can change the way classes work without modifying the original code. And thus not breaking any code that relies on the original behaviour. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From denis.spir at free.fr Fri Jan 23 12:36:39 2009 From: denis.spir at free.fr (spir) Date: Fri, 23 Jan 2009 12:36:39 +0100 Subject: [Tutor] Customizing Eclipse text editor In-Reply-To: <50ed08f40901230217h473e98c4r5b26e4858b6d8dd9@mail.gmail.com> References: <50ed08f40901230217h473e98c4r5b26e4858b6d8dd9@mail.gmail.com> Message-ID: <20090123123639.115d048a@o> Le Fri, 23 Jan 2009 11:17:15 +0100, Vicent a ?crit : > Hello everyone. [...] > As you can see there, I prefer a black background, so I've changed colors a > little. My second question is: do you know any kind of recomended (I mean, > optimized for a good working experience, good for eyes health, etc.) color > palette or color combination with black background? > > Thank you in advance. I have long talked about that with a web designer who is particuliarly aware of user comfort in relation to colors, brightness, etc. What I remember is the following rules about what factors make reading/watching harmful, difficult and/or tiring: -1- overall brightness --> white background forbidden -2- difficulty to read or distingush shapes (e.g. too small or badly designed fonts) -3- physical effects of low quality monitors -4- too low (rule -2-) or too high (rule -1-) contrast In addition to that, a basic rule of graphical design in any domain is that too many colors or styles -- as usually done in standard syntax highlighting -- rather prevents readibility that helps it. There should be some research done on this topic. After all, it's a relevant aspect of all programmers' everyday life, no? I'm rather sure that for most PLs, a combination of 3 to 5 colors, and bold/italics properties given to only 1 or 2 token types is optimal. I haven't yet found a style sheet to be really happy with, nevertheless. Now, for a language that becomes more and more complex like python... maybe it will be easier with py3 ;-) denis ------ la vida e estranya From kent37 at tds.net Fri Jan 23 12:45:04 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 23 Jan 2009 06:45:04 -0500 Subject: [Tutor] class arguments? In-Reply-To: <20090123120439.1a12b4db@o> References: <20090122225104.03c677f4@o> <20090123120439.1a12b4db@o> Message-ID: <1c2a2c590901230345xfb7dbd2i83bc8ff1928c1f40@mail.gmail.com> On Fri, Jan 23, 2009 at 6:04 AM, spir wrote: > Thank you Alan and sorry for not having been clear enough. The point actually was class (definition) attributes. I thought at e.g. Guido's views that lists were for homogeneous sequences as opposed to tuples rather like records. And a way to ensure sich a homogeneity, in the sense of items beeing of the same type or super type. > The straightforward path to ensure that, as I see it, is to add proper argument to a class definition. A simple way to do this is with a class factory function, for example: def makeMonoList(typ, number): class MonoListSubtype(MonoList): item_type = type item_number = number return MonoListSubtype then e.g. IntegerList = makeMonoList(int, 5) myIntegerList = IntegerList() This is similar in spirit to collections.namedtuple() in Python 2.6 though the implementation is different; namedtuple() actually creates and evaluates the text of the new class definition: http://docs.python.org/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields http://svn.python.org/view/python/trunk/Lib/collections.py?rev=68853&view=auto Kent From kent37 at tds.net Fri Jan 23 13:27:40 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 23 Jan 2009 07:27:40 -0500 Subject: [Tutor] fetching wikipedia articles In-Reply-To: References: <6faf39c90901220913h585ce27bue36a111e0c34e6f6@mail.gmail.com> <6faf39c90901220915i67696c3iff28afc15ed85f92@mail.gmail.com> <6faf39c90901230055r2f1d5469r85d1eadc4ed3adf8@mail.gmail.com> <6faf39c90901230225q3d6ec030sb224315810f584a0@mail.gmail.com> Message-ID: <1c2a2c590901230427h2a20969s192217ebccd406c5@mail.gmail.com> On Fri, Jan 23, 2009 at 6:23 AM, Alan Gauld wrote: > Rather than editing the existing code and making it non standard > why not subclass robotparser: > > class WP_RobotParser(robotparser): > def __init__(self, *args, *kwargs): > robotparser.__init__(self, *args, *kwargs) > self.addheaders = .......blah.... > > Thats one of the advantages of OOP, you can change the way > classes work without modifying the original code. And thus not > breaking any code that relies on the original behaviour. That won't work, it is urllib.URLOpener() that he is patching and robotparser does not supply a way to change the URLOpener subclass that it uses. Ken From kent37 at tds.net Fri Jan 23 13:29:28 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 23 Jan 2009 07:29:28 -0500 Subject: [Tutor] fetching wikipedia articles In-Reply-To: <6faf39c90901230237v724df84dgeebac6075f2b798f@mail.gmail.com> References: <6faf39c90901220913h585ce27bue36a111e0c34e6f6@mail.gmail.com> <6faf39c90901220915i67696c3iff28afc15ed85f92@mail.gmail.com> <6faf39c90901230055r2f1d5469r85d1eadc4ed3adf8@mail.gmail.com> <6faf39c90901230225q3d6ec030sb224315810f584a0@mail.gmail.com> <6faf39c90901230237v724df84dgeebac6075f2b798f@mail.gmail.com> Message-ID: <1c2a2c590901230429j519ce649r52f71afdbb08d8f1@mail.gmail.com> On Fri, Jan 23, 2009 at 5:37 AM, Andre Engels wrote: > Looking further I found that a 'cleaner' way to make the same change > is to add to the code of URLopener (outside any method): > > version = '' You can do this without modifying the standard library source, by import urllib urllib.URLopener.version = '' The version string is used as the User-Agent, that is why this works at all. Kent From alan.gauld at btinternet.com Fri Jan 23 14:51:58 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 23 Jan 2009 13:51:58 -0000 Subject: [Tutor] fetching wikipedia articles References: <6faf39c90901220913h585ce27bue36a111e0c34e6f6@mail.gmail.com><6faf39c90901220915i67696c3iff28afc15ed85f92@mail.gmail.com><6faf39c90901230055r2f1d5469r85d1eadc4ed3adf8@mail.gmail.com><6faf39c90901230225q3d6ec030sb224315810f584a0@mail.gmail.com> <1c2a2c590901230427h2a20969s192217ebccd406c5@mail.gmail.com> Message-ID: "Kent Johnson" wrote >> Rather than editing the existing code and making it non standard >> why not subclass robotparser: > That won't work, it is urllib.URLOpener() that he is patching and Sorry, yes I misread that post as modifying robotparser, it should have been URLOpener. But... > robotparser does not supply a way to change the URLOpener subclass > that it uses. I didn't realize that. So you would need to cut n' paste the robotparser read() method into a subclass of robotparser too. Which is almost as messy as editing the original source. Such a shame that the author didn't either put the opener as an attribute or as a defaulted parameter of read! Pity, I hate to see editing of existing classes in an OO system. Alan G. From vginer at gmail.com Fri Jan 23 14:57:10 2009 From: vginer at gmail.com (Vicent) Date: Fri, 23 Jan 2009 14:57:10 +0100 Subject: [Tutor] Why dictionaries? Message-ID: <50ed08f40901230557w5de9861cj8fd81a3050e97c49@mail.gmail.com> A simple but maybe too wide question: When is it / isn't it useful to use dictionaries, in a Python program? I mean, what kind of tasks are they interesting for? Maybe you can give me some references where they explain it. Thank you!! -- Vicent From alan.gauld at btinternet.com Fri Jan 23 15:00:02 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 23 Jan 2009 14:00:02 -0000 Subject: [Tutor] Customizing Eclipse text editor References: <50ed08f40901230217h473e98c4r5b26e4858b6d8dd9@mail.gmail.com> <20090123123639.115d048a@o> Message-ID: "spir" wrote > There should be some research done on this topic. After all, > it's a relevant aspect of all programmers' everyday life, no? I suspect there has been - just not in our field. The reason I changed the colours on my web tutor about a year ago was because one of my users who was a graphics designer chided me for the use of contrasting colours. It is apparently easier to read something if all the colours on a page are from the same family - different shades of red say. Contrasting colours clash and so should only be used where you want to draw attention away from the main text. I'm no expert but he sounded like he knew what he was talking about and the end result pleases me so I stuck with it! :-) Alan G. From alan.gauld at btinternet.com Fri Jan 23 15:07:36 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 23 Jan 2009 14:07:36 -0000 Subject: [Tutor] Why dictionaries? References: <50ed08f40901230557w5de9861cj8fd81a3050e97c49@mail.gmail.com> Message-ID: "Vicent" wrote > When is it / isn't it useful to use dictionaries, in a Python > program? > I mean, what kind of tasks are they interesting for? They are interesting for any place where you need to store associations of objects and data. Think of a glossary or an index in a book. Both are a type of dictionary. A Glossary takes a single word and returns a paragraph of definition. An index takes a word and retirns a list of page numbers where that word appears. A dictionary can also model a simple database where a single key can retrieve an entire record. It goes on and on, they are one of the most powerful data structures available to us. The biggest snags are that they are not ordered so if you need a sorted data store dictionaries may not be the best choice. > Maybe you can give me some references where they explain it. Try Wikipedia under Associative Array (a fancy term for a dictionary) or Hash Table for a description of the inner workings... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Fri Jan 23 15:15:19 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 23 Jan 2009 09:15:19 -0500 Subject: [Tutor] Why dictionaries? In-Reply-To: <50ed08f40901230557w5de9861cj8fd81a3050e97c49@mail.gmail.com> References: <50ed08f40901230557w5de9861cj8fd81a3050e97c49@mail.gmail.com> Message-ID: <1c2a2c590901230615l2b6f2f7j7f45867b16542c50@mail.gmail.com> On Fri, Jan 23, 2009 at 8:57 AM, Vicent wrote: > A simple but maybe too wide question: > > When is it / isn't it useful to use dictionaries, in a Python program? > I mean, what kind of tasks are they interesting for? Lists are ordered, dicts are not List indices are consecutive integers, dict keys can be any hashable value (most often a number or string) and do not have to be consecutive. Dict lookup is fast, even for large dictionaries. List search is sequential and gets slow for long lists. This can be a performance killer, for example a common performance problem is code like this: for item1 in very_long_list_1: if item1 in very_long_list_2: # do something with item1 that matches This particular example is best solved with a set, not a dict, but the performance of both is similar and sometimes a dict is the correct solution. This will be significantly faster than the previous code: list_2_items = set(very_long_list_2) for item1 in very_long_list_1: if item1 in list_2_items: # do something with item1 Kent From sidewalking at gmail.com Fri Jan 23 19:25:02 2009 From: sidewalking at gmail.com (Scott Stueben) Date: Fri, 23 Jan 2009 11:25:02 -0700 Subject: [Tutor] Possible to search text file for multiple string values at once? Message-ID: <99004bb30901231025i6c04e338tcc373aa9469d0550@mail.gmail.com> Hi all, I understand that python excels at text processing, and wondered if there is a way to use python to accomplish a certain task. I am trying to search large text files for multiple strings (like employee ID number, or name). Any text editor (I use Windows mostly) will certainly have a "find", "replace", or even "find in files" (to search multiple files for a value) function, but this is searching for one string at a time. I would like to search a text file for a list of strings, like a sql query. For instance: To search a text file for the values 'Bob', 'John', 'Joe', 'Jim', and 'Fred', you would have to open the dialog and do five separate searches. Lots of copying and pasting, lots of room for typos. But if you were in a SQL database, you could do something like: "SELECT * FROM my_table WHERE first_name IN ('Bob', 'John', 'Joe', 'Jim', 'Fred')" and you would get results for all five values. I would love to set up a script to parse a file and show results from a list of strings. Is this possible with python? Thanks for the input and help, Scott From bgailer at gmail.com Fri Jan 23 19:38:50 2009 From: bgailer at gmail.com (bob gailer) Date: Fri, 23 Jan 2009 13:38:50 -0500 Subject: [Tutor] Possible to search text file for multiple string values at once? In-Reply-To: <99004bb30901231025i6c04e338tcc373aa9469d0550@mail.gmail.com> References: <99004bb30901231025i6c04e338tcc373aa9469d0550@mail.gmail.com> Message-ID: <497A0EBA.6080305@gmail.com> Scott Stueben wrote: > Hi all, > > I understand that python excels at text processing, and wondered if > there is a way to use python to accomplish a certain task. I am > trying to search large text files for multiple strings (like employee > ID number, or name). Any text editor (I use Windows mostly) will > certainly have a "find", "replace", or even "find in files" (to search > multiple files for a value) function, but this is searching for one > string at a time. > > I would like to search a text file for a list of strings, like a sql query. > > For instance: To search a text file for the values 'Bob', 'John', > 'Joe', 'Jim', and 'Fred', you would have to open the dialog and do > five separate searches. Lots of copying and pasting, lots of room for > typos. > > But if you were in a SQL database, you could do something like: > > "SELECT * FROM my_table WHERE first_name IN ('Bob', 'John', 'Joe', > 'Jim', 'Fred')" > > and you would get results for all five values. > > I would love to set up a script to parse a file and show results from > a list of strings. Is this possible with python? > Yes - and also possible with almost all other programming languages. Here is one of several ways to do it in Python: for first_name in ('Bob', 'John', 'Joe', 'Jim', 'Fred'): if first_name in text: print first_name, 'found' -- Bob Gailer Chapel Hill NC 919-636-4239 From srilyk at gmail.com Fri Jan 23 19:47:07 2009 From: srilyk at gmail.com (W W) Date: Fri, 23 Jan 2009 12:47:07 -0600 Subject: [Tutor] Possible to search text file for multiple string values at once? In-Reply-To: <497A0EBA.6080305@gmail.com> References: <99004bb30901231025i6c04e338tcc373aa9469d0550@mail.gmail.com> <497A0EBA.6080305@gmail.com> Message-ID: <333efb450901231047y63da6f7rf03f9227aea373c0@mail.gmail.com> On Fri, Jan 23, 2009 at 12:38 PM, bob gailer wrote: > Scott Stueben wrote: > >> Hi all, >> >> I understand that python excels at text processing, and wondered if >> there is a way to use python to accomplish a certain task. >> I would love to set up a script to parse a file and show results from >> a list of strings. Is this possible with python? >> >> > > Yes - and also possible with almost all other programming languages. > Here is one of several ways to do it in Python: > > for first_name in ('Bob', 'John', 'Joe', 'Jim', 'Fred'): > if first_name in text: > print first_name, 'found' > Another option, if you really like sql, is to import sqlite3 and then parse your text file into a sqlite database. That's probably overkill, of course. But it's a possibility. It really depends on what matters most. Speed? Comfort(with syntax)? Ease of use? That will give you an idea of which tools you should use. HTH, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Jan 23 19:52:26 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 23 Jan 2009 13:52:26 -0500 Subject: [Tutor] Possible to search text file for multiple string values at once? In-Reply-To: <99004bb30901231025i6c04e338tcc373aa9469d0550@mail.gmail.com> References: <99004bb30901231025i6c04e338tcc373aa9469d0550@mail.gmail.com> Message-ID: <1c2a2c590901231052v5f40b318wfef45f0d437ce59a@mail.gmail.com> On Fri, Jan 23, 2009 at 1:25 PM, Scott Stueben wrote: > I would like to search a text file for a list of strings, like a sql query. What do you want to do if you find one? Do you want to get every line that contains any of the strings, or a list of which strings are found, or just find out if any of the strings are there? > For instance: To search a text file for the values 'Bob', 'John', > 'Joe', 'Jim', and 'Fred', you would have to open the dialog and do > five separate searches. Lots of copying and pasting, lots of room for > typos. You can do this with a regular expression. For example, import re findAny = re.compile('Bob|John|Joe|Jim|Fred') for found in findAny.findall(s): print found will print all occurrences of any of the target names. You can build the regex string dynamically from user input; if 'toFind' is a list of target words, use findAny = re.compile('|'.join(re.escape(target) for target in toFind)) re.escape() cleans up targets that have special characters in them. From andreengels at gmail.com Fri Jan 23 19:53:18 2009 From: andreengels at gmail.com (Andre Engels) Date: Fri, 23 Jan 2009 19:53:18 +0100 Subject: [Tutor] fetching wikipedia articles In-Reply-To: <6faf39c90901230225q3d6ec030sb224315810f584a0@mail.gmail.com> References: <6faf39c90901220913h585ce27bue36a111e0c34e6f6@mail.gmail.com> <6faf39c90901220915i67696c3iff28afc15ed85f92@mail.gmail.com> <6faf39c90901230055r2f1d5469r85d1eadc4ed3adf8@mail.gmail.com> <6faf39c90901230225q3d6ec030sb224315810f584a0@mail.gmail.com> Message-ID: <6faf39c90901231053x6662ceep773a0b755ff4511a@mail.gmail.com> On Fri, Jan 23, 2009 at 11:25 AM, Andre Engels wrote: > On Fri, Jan 23, 2009 at 10:37 AM, amit sethi wrote: >> so is there a way around that problem ?? > > Ok, I have done some checking around, and it seems that the Wikipedia > server is giving a return code of 403 (forbidden), but still giving > the page - which I think is weird behaviour. I will check with the > developers of Wikimedia why this is done, It appears that this is done on purpose, not just for Python but also for the 'standard' user agent in other languages. The idea is that it forces programmers to add their own user agent, so that if the program trying to contact Wikipedia misbehaves, it can be blocked or otherwise handeled with; as a bonus it also gives programmers a small extra hurdle so that the most amateuristic attempts are stopped, but more thought out programs are not. -- Andr? Engels, andreengels at gmail.com From kent37 at tds.net Fri Jan 23 20:02:20 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 23 Jan 2009 14:02:20 -0500 Subject: [Tutor] class arguments? In-Reply-To: <20090123193529.1eeb68aa@o> References: <20090122225104.03c677f4@o> <20090123120439.1a12b4db@o> <1c2a2c590901230345xfb7dbd2i83bc8ff1928c1f40@mail.gmail.com> <20090123193529.1eeb68aa@o> Message-ID: <1c2a2c590901231102u6eb26ab9jefa27c62f20ad33c@mail.gmail.com> Forwarding to the list with my reply... On Fri, Jan 23, 2009 at 1:35 PM, spir wrote: > Le Fri, 23 Jan 2009 06:45:04 -0500, > Kent Johnson a ?crit : > >> On Fri, Jan 23, 2009 at 6:04 AM, spir wrote: >> >> > Thank you Alan and sorry for not having been clear enough. The point actually was class (definition) attributes. I thought at e.g. Guido's views that lists were for homogeneous sequences as opposed to tuples rather like records. And a way to ensure sich a homogeneity, in the sense of items beeing of the same type or super type. >> > The straightforward path to ensure that, as I see it, is to add proper argument to a class definition. >> >> A simple way to do this is with a class factory function, for example: >> >> def makeMonoList(typ, number): >> class MonoListSubtype(MonoList): >> item_type = type >> item_number = number >> return MonoListSubtype > > That's it! Stupid me!! [Just realize I have a kind of mental blocage that prevents me *imagining* a class beeing defined inside a func. As for me a class is a higher level kind of thing. Actually I also have problems with defs insides defs. Maybe there should be more introduction to that in python literature. Probably it may help and simplify a whole lot of models.] > Thank you again. >> then e.g. >> IntegerList = makeMonoList(int, 5) >> myIntegerList = IntegerList() >> >> This is similar in spirit to collections.namedtuple() in Python 2.6 >> though the implementation is different; namedtuple() actually creates >> and evaluates the text of the new class definition: >> http://docs.python.org/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields >> http://svn.python.org/view/python/trunk/Lib/collections.py?rev=68853&view=auto > > I have watched that some time ago -- as you pointed to it already. I take the opportunity to ask why this contruct is so complicated. There is an alternative in the cookbook (also pointed by Kent, if I remmember well) that is only a few lines long. Something like: > > class Record(dict): > def __init__(self,**kwargs): > dict.__init__(self,kwargs) > # and/or > self.__dict__ = kwargs > > [There are several versons around, +/- based on the same principle] namedtuple() creates a new class that has exactly the desired attributes, so it is a bit more specific and typesafe - you have to have the correct number of points. The generated class subclasses tuple so it can be used as a dict key (if the items themselves can be). Class instances are lightweight because they don't have a __dict__ member. > Actually, the thing I like at least in the namedtuple recipe is that it writes the class def as a string to be executed: Yeah, I know...with all the time we spend on the list telling people not to use eval()... > > I know there are several advantages: > * a docstring > * For large collections of records of the same (sub)type, as the list of field is held by the class (instances record the actual data only), which spares memory. But doesn't this lead to lower performance, as attribute access by name requires adressing a class level attribute? The attributes are properties, so attribute access is like a method call, I suppose this is slower than direct field access but it is a common Python technique. > * attributes can be accessed by index, too > > Also, as this factory create kinds of records, meaning data constructs with an identical structure, that would perfectly hold table records, why isn't it simply called "record". > To sum up in a word: why so much *complication*? I guess you would have to search comp.lang.python or python-dev to find the reasons, I don't think there is a PEP for this (at least not referenced in the What's New). Kent > > Denis > ------ > la vida e estranya > From sidewalking at gmail.com Fri Jan 23 20:11:33 2009 From: sidewalking at gmail.com (Scott Stueben) Date: Fri, 23 Jan 2009 12:11:33 -0700 Subject: [Tutor] Possible to search text file for multiple string values at once? In-Reply-To: <1c2a2c590901231052v5f40b318wfef45f0d437ce59a@mail.gmail.com> References: <99004bb30901231025i6c04e338tcc373aa9469d0550@mail.gmail.com> <1c2a2c590901231052v5f40b318wfef45f0d437ce59a@mail.gmail.com> Message-ID: <99004bb30901231111x2e82b99v82b560e1a4da4a05@mail.gmail.com> Thanks for the help so far - it seems easy enough. To clarify on the points you have asked me about: A sqlite3 database on my machine would be an excellent idea for personal use. I would like to be able to get a functional script for others on my team to use, so maybe a script or compiled program (Win32) eventually. As for output, I would probably like to return the entire lines that contain any search results of those strings. Maybe just output to a results.txt that would have the entire line of each line that contains 'Bob', 'John', 'Joe', 'Jim', and or 'Fred'. Speed isn't as important as ease of use, I suppose, since non-technical people should be able to use it, ideally. Maybe, since I am on Win32, I could have a popup window that asks for input filename and path, and then asks for string(s) to search for, and then it would process the search and output all lines to a file. Something like that is what I am imagining, but I am open to suggestions on items that may be easier to use or code. Is that reasonably simple to code for a beginner? Thanks again, Scott On Fri, Jan 23, 2009 at 11:52 AM, Kent Johnson wrote: > On Fri, Jan 23, 2009 at 1:25 PM, Scott Stueben wrote: > >> I would like to search a text file for a list of strings, like a sql query. > > What do you want to do if you find one? Do you want to get every line > that contains any of the strings, or a list of which strings are > found, or just find out if any of the strings are there? > >> For instance: To search a text file for the values 'Bob', 'John', >> 'Joe', 'Jim', and 'Fred', you would have to open the dialog and do >> five separate searches. Lots of copying and pasting, lots of room for >> typos. > > You can do this with a regular expression. For example, > > import re > findAny = re.compile('Bob|John|Joe|Jim|Fred') > > for found in findAny.findall(s): > print found > > will print all occurrences of any of the target names. > > You can build the regex string dynamically from user input; if > 'toFind' is a list of target words, use > findAny = re.compile('|'.join(re.escape(target) for target in toFind)) > > re.escape() cleans up targets that have special characters in them. > -- "Shine on me baby, cause it's rainin' in my heart" --Elliott Smith From srilyk at gmail.com Fri Jan 23 21:45:32 2009 From: srilyk at gmail.com (W W) Date: Fri, 23 Jan 2009 14:45:32 -0600 Subject: [Tutor] Possible to search text file for multiple string values at once? In-Reply-To: <99004bb30901231111x2e82b99v82b560e1a4da4a05@mail.gmail.com> References: <99004bb30901231025i6c04e338tcc373aa9469d0550@mail.gmail.com> <1c2a2c590901231052v5f40b318wfef45f0d437ce59a@mail.gmail.com> <99004bb30901231111x2e82b99v82b560e1a4da4a05@mail.gmail.com> Message-ID: <333efb450901231245j71608f48m48f9c6ab16f99398@mail.gmail.com> On Fri, Jan 23, 2009 at 1:11 PM, Scott Stueben wrote: > Thanks for the help so far - it seems easy enough. To clarify on the > points you have asked me about: > > A sqlite3 database on my machine would be an excellent idea for > personal use. I would like to be able to get a functional script for > others on my team to use, so maybe a script or compiled program > (Win32) eventually. As long as everyone on your team has python installed (or as long as python is installed on the machines they'll be using), a functional script would be fairly easy to get rolling. Sqlite is (AFAIK) included with the newer versions of python by default. Heck, it's on the version I have installed on my phone! (Cingular 8525). Simply zipping up the directory should provide an easy enough distribution method. Although, you *could* even write a python script that does the "install" for them. > As for output, I would probably like to return the entire lines that > contain any search results of those strings. Maybe just output to a > results.txt that would have the entire line of each line that contains > 'Bob', 'John', 'Joe', 'Jim', and or 'Fred'. The simplest method: In [5]: f = open('interculturalinterview2.txt', 'r') In [6]: searchstrings = ('holy', 'hand', 'grenade', 'potato') In [7]: for line in f.readlines(): ...: for word in searchstrings: ...: if word in line: ...: print line ...: ...: Hana: have a bonfire n candy apples n make potatoes on a car lol! Wayne: potatoes on a car? Hana .: yer lol its fun and they taste nicer lol, you wrap a potato in tinfoil a nd put in on the engine of a car and close the bonnet and have the engine run an d it cooks it in about 30 mins Speed isn't as important as ease of use, I suppose, since > non-technical people should be able to use it, ideally. Although that wouldn't be quite so easy to use ;) Of course simple modifications would provide a little more user friendliness. > Maybe, since I am on Win32, I could have a popup window that asks for > input filename and path, and then asks for string(s) to search for, > and then it would process the search and output all lines to a file. > Something like that is what I am imagining, but I am open to > suggestions on items that may be easier to use or code. Using Tkinter (again, which AFAIK comes with all versions of python) is pretty simple. import Tkinter, tkFileDialog, tkMessageBox root = Tkinter.Tk() root.withdraw() if tkMessageBox.askyesno("Choose a file?", "Would you like to choose a file to search?"): f = tkFileDialog.askopenfile() You could also use this method to select a file that contains search strings, or allow the user to input them in some other way. > Is that reasonably simple to code for a beginner? > Yes, it's fairly simple. If you've had minimal programming experience you might encounter some bigger problems, but if you've programmed in PHP or some other language you should find it fairly easy to pick up python, and use all the commands you'll need. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From emadnawfal at gmail.com Sat Jan 24 00:02:13 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Fri, 23 Jan 2009 18:02:13 -0500 Subject: [Tutor] finding words that contain some letters in their respective order Message-ID: <652641e90901231502l4f5c76bbw3e273b0818af3465@mail.gmail.com> Hello Tutors, Arabic words are build around a root of 3 or 4 consonants with lots of letters in between, and also prefixes and suffixes. The root ktb (write) for example, could be found in words like: ktab : book mktob: letter, written wktabhm: and their book yktb: to write lyktbha: in order for him to write it I need to find all the word forms made up of a certain root in a corpus. My idea, which is not completely right, but nonetheless works most of the time, is to find words that have the letters of the root in their respective order. For example, the words that contain k followed by t then followed by b, no matter whether there is something in between. I came up with following which works fine. For learning purposes, please let me know whether this is a good way, and how else I can achieve that. I appreciate your help, as I always did. def getRoot(root, word): result = "" for letter in word: if letter not in root: continue result +=letter return result # main infile = open("myCorpus.txt").read().split() query = "ktb" outcome = set([word for word in infile if query == getRoot(query, word)]) for word in outcome: print(word) -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Sat Jan 24 00:55:51 2009 From: andreengels at gmail.com (Andre Engels) Date: Sat, 24 Jan 2009 00:55:51 +0100 Subject: [Tutor] finding words that contain some letters in their respective order In-Reply-To: <652641e90901231502l4f5c76bbw3e273b0818af3465@mail.gmail.com> References: <652641e90901231502l4f5c76bbw3e273b0818af3465@mail.gmail.com> Message-ID: <6faf39c90901231555r1cbeff26w15f4a403cc3735d4@mail.gmail.com> On Sat, Jan 24, 2009 at 12:02 AM, Emad Nawfal (???? ????) wrote: > Hello Tutors, > Arabic words are build around a root of 3 or 4 consonants with lots of > letters in between, and also prefixes and suffixes. > The root ktb (write) for example, could be found in words like: > ktab : book > mktob: letter, written > wktabhm: and their book > yktb: to write > lyktbha: in order for him to write it > > I need to find all the word forms made up of a certain root in a corpus. My > idea, which is not completely right, but nonetheless works most of the > time, is to find words that have the letters of the root in their > respective order. For example, the words that contain k followed by t > then followed by b, no matter whether there is something in between. I came > up with following which works fine. For learning purposes, please let me > know whether this is a good way, and how else I can achieve that. > I appreciate your help, as I always did. > > > > def getRoot(root, word): > result = "" > > for letter in word: > if letter not in root: > continue > result +=letter > return result > > # main > > infile = open("myCorpus.txt").read().split() > query = "ktb" > outcome = set([word for word in infile if query == getRoot(query, word)]) > for word in outcome: > > print(word) This gets into problems if the letters of the root occur somewhere else in the word as well. For example, if there would be a word bktab, then getRoot("ktb","bktab") would be "bktb", not "ktb". I would use the find method of the string class here - if A and B are strings, and n is a number, then A.find(B,n) is the first location, starting at n, where B is a substring of A, or -1 if there isn't any. Using this, I get: def hasRoot(word, root): # This order I find more logical loc = 0 for letter in root: loc = word.find(letter) if loc == -1: return false return true # main in